-
Notifications
You must be signed in to change notification settings - Fork 212
Expand file tree
/
Copy pathreact-rendering.js
More file actions
437 lines (384 loc) · 15.1 KB
/
react-rendering.js
File metadata and controls
437 lines (384 loc) · 15.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
/*
* Copyright (c) 2021, salesforce.com, inc.
* All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
* For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
/**
* @module progressive-web-sdk/ssr/server/react-rendering
*/
import path from 'path'
import React from 'react'
import ReactDOMServer from 'react-dom/server'
import {Helmet} from 'react-helmet'
import {ChunkExtractor} from '@loadable/server'
import {StaticRouter as Router, matchPath} from 'react-router-dom'
import serialize from 'serialize-javascript'
import PropTypes from 'prop-types'
import sprite from 'svg-sprite-loader/runtime/sprite.build'
import {isRemote} from '@salesforce/pwa-kit-runtime/utils/ssr-server'
import {proxyConfigs} from '@salesforce/pwa-kit-runtime/utils/ssr-shared'
import {getConfig} from '@salesforce/pwa-kit-runtime/utils/ssr-config'
import {NO_CACHE} from '@salesforce/pwa-kit-runtime/ssr/server/constants'
import {shutdownServerTracing, tracePerformance} from './opentelemetry-server'
import {getAssetUrl} from '../universal/utils'
import {ServerContext, CorrelationIdProvider} from '../universal/contexts'
import Document from '../universal/components/_document'
import App from '../universal/components/_app'
import Throw404 from '../universal/components/throw-404'
import {getAppConfig} from '../universal/compatibility'
import Switch from '../universal/components/switch'
import {getRoutes, routeComponent} from '../universal/components/route-component'
import * as errors from '../universal/errors'
import logger from '../../utils/logger-instance'
import PerformanceTimer from '../../utils/performance'
import {PERFORMANCE_MARKS} from '../../utils/performance-marks'
const CWD = process.cwd()
const BUNDLES_PATH = path.resolve(CWD, 'build/loadable-stats.json')
const VALID_TAG_NAMES = [
'base',
'body',
'head',
'html',
'link',
'meta',
'noscript',
'script',
'style',
'title'
]
export const ALLOWLISTED_INLINE_SCRIPTS = []
/**
* Convert from thrown Error or String to {message, status} that we need for
* rendering.
* @private
* @param err - Error to be converted
* @function
* @return {Object}
*/
const logAndFormatError = (err) => {
if (err instanceof errors.HTTPError) {
// These are safe to display – we expect end-users to throw them
return {message: err.message, status: err.status, stack: err.stack}
} else {
const cause = err.stack || err.toString()
logger.error(cause, {namespace: 'react-rendering.render'})
const safeMessage = 'Internal Server Error'
return {message: safeMessage, status: 500, stack: err.stack}
}
}
const shouldTrackPerformance = (req) => {
const includeServerTimingHeader = '__server_timing' in req.query
return includeServerTimingHeader || process.env.SERVER_TIMING
}
// Because multi-value params are not supported in `aws-serverless-express` create a proper
// search string using the `query` property. We pay special attention to the order the params
// as best as we can.
export const getLocationSearch = (req, opts = {}) => {
const {interpretPlusSignAsSpace = false} = opts
const [_, search] = req.originalUrl.split('?')
const params = new URLSearchParams(search)
const newParams = new URLSearchParams()
const orderedKeys = [...new Set(params.keys())]
// Maintain the original order of the parameters by iterating the
// ordered list of keys, and using the `req.query` object as the source of values.
orderedKeys.forEach((key) => {
const value = req.query[key]
const values = Array.isArray(value) ? value : [value]
values.forEach((v) => {
// To have feature parity to SFRA, the + sign can be treated as space
// However, this could potential a breaking change since not all users want to treat it as such
// Therefore, we create a flag for it via the app configuration
newParams.append(
key,
interpretPlusSignAsSpace ? decodeURIComponent(v).replace(/\+/, ' ') : v
)
})
})
const searchString = newParams.toString()
// Update the location objects reference.
return searchString ? `?${searchString}` : ''
}
/**
* This is the main react-rendering function for SSR. It is an Express handler.
*
* @param req - Request
* @param res - Response
*
* @function
*
* @return {Promise}
*/
const performRender = async (req, res, next) => {
res.__performanceTimer.mark(PERFORMANCE_MARKS.total, 'start')
const AppConfig = getAppConfig()
// Get the application config which should have been stored at this point.
const config = getConfig()
AppConfig.restore(res.locals)
const routes = getRoutes(res.locals)
const WrappedApp = routeComponent(App, false, res.locals)
const [pathname] = req.originalUrl.split('?')
const location = {
pathname,
search: getLocationSearch(req, {
interpretPlusSignAsSpace: config?.app?.url?.interpretPlusSignAsSpace
})
}
// Step 1 - Find the match.
res.__performanceTimer.mark(PERFORMANCE_MARKS.routeMatching, 'start')
let route
let match
routes.some((_route) => {
const _match = matchPath(req.path, _route)
if (_match) {
match = _match
route = _route
}
return !!match
})
res.__performanceTimer.mark(PERFORMANCE_MARKS.routeMatching, 'end')
// Step 2 - Get the component
res.__performanceTimer.mark(PERFORMANCE_MARKS.loadComponent, 'start')
const component = await route.component.getComponent()
res.__performanceTimer.mark(PERFORMANCE_MARKS.loadComponent, 'end')
// Step 3 - Init the app state
const props = {
error: null,
appState: {},
routerContext: {},
req,
res,
App: WrappedApp,
routes,
location
}
let appJSX = <OuterApp {...props} />
let appState, appStateError
if (component === Throw404) {
appState = {}
appStateError = new errors.HTTPNotFound('Not found')
} else {
res.__performanceTimer.mark(PERFORMANCE_MARKS.fetchStrategies, 'start')
const ret = await AppConfig.initAppState({
App: WrappedApp,
component,
match,
route,
req,
res,
location,
appJSX
})
appState = {
...ret.appState,
__STATE_MANAGEMENT_LIBRARY: AppConfig.freeze(res.locals)
}
appStateError = ret.error
res.__performanceTimer.mark(PERFORMANCE_MARKS.fetchStrategies, 'end')
}
res.__performanceTimer.mark(PERFORMANCE_MARKS.renderToString, 'start')
appJSX = React.cloneElement(appJSX, {error: appStateError, appState})
// Step 4 - Render the App
let renderResult
try {
renderResult = renderApp({
App: WrappedApp,
appState,
appStateError: appStateError && logAndFormatError(appStateError),
routes,
req,
res,
location,
config,
appJSX
})
} catch (e) {
// This is an unrecoverable error.
// (errors handled by the AppErrorBoundary are considered recoverable)
// Here, we use Express's convention to invoke error middleware.
// Note, we don't have an error handling middleware yet! This is calling the
// default error handling middleware provided by Express
res.__performanceTimer.cleanup()
shutdownServerTracing()
return next(e)
}
// Step 5 - Determine what is going to happen, redirect, or send html with
// the correct status code.
const {html, routerContext, error} = renderResult
const redirectUrl = routerContext.url
const status = (error && error.status) || res.statusCode
res.__performanceTimer.mark(PERFORMANCE_MARKS.renderToString, 'end')
res.__performanceTimer.mark(PERFORMANCE_MARKS.total, 'end')
res.__performanceTimer.log()
if (shouldTrackPerformance(req)) {
res.setHeader('Server-Timing', res.__performanceTimer.buildServerTimingHeader())
// Override cache-control header to no caching when __server_timing is used
// This happens after React rendering is complete, ensuring it overrides any
// cache headers set by individual page components
res.set('Cache-Control', NO_CACHE)
}
// Cleanup performance timer and OpenTelemetry tracing after response is sent
res.__performanceTimer.cleanup()
shutdownServerTracing()
if (redirectUrl) {
res.redirect(routerContext.status || 302, redirectUrl)
} else {
res.status(status).send(html)
}
}
export const render = (req, res, next) => {
res.__performanceTimer = new PerformanceTimer({enabled: shouldTrackPerformance(req)})
if (shouldTrackPerformance(req)) {
return tracePerformance('ssr.render', () => performRender(req, res, next), res, req)
} else {
return performRender(req, res, next)
}
}
const OuterApp = ({req, res, error, App, appState, routes, routerContext, location}) => {
const AppConfig = getAppConfig()
return (
<ServerContext.Provider value={{req, res}}>
<Router location={location} context={routerContext}>
<CorrelationIdProvider
correlationId={res.locals.requestId}
resetOnPageChange={false}
>
<AppConfig locals={res.locals}>
<Switch error={error} appState={appState} routes={routes} App={App} />
</AppConfig>
</CorrelationIdProvider>
</Router>
</ServerContext.Provider>
)
}
OuterApp.propTypes = {
req: PropTypes.object,
res: PropTypes.object,
error: PropTypes.object,
App: PropTypes.elementType,
appState: PropTypes.object,
routes: PropTypes.array,
routerContext: PropTypes.object,
location: PropTypes.object
}
const renderToString = (jsx, extractor) =>
ReactDOMServer.renderToString(extractor.collectChunks(jsx))
const renderApp = (args) => {
const {req, res, appStateError, appJSX, appState, config} = args
const extractor = new ChunkExtractor({statsFile: BUNDLES_PATH, publicPath: getAssetUrl()})
const ssrOnly = 'mobify_server_only' in req.query || '__server_only' in req.query
const prettyPrint = 'mobify_pretty' in req.query || '__pretty_print' in req.query
const indent = prettyPrint ? 8 : 0
let routerContext
let appHtml
let renderError
// It's important that we render the App before extracting the script elements,
// otherwise it won't return the correct chunks.
try {
routerContext = {}
appHtml = renderToString(React.cloneElement(appJSX, {routerContext}), extractor)
} catch (e) {
// This will catch errors thrown from the app and pass the error
// to the AppErrorBoundary component, and renders the error page.
routerContext = {}
renderError = logAndFormatError(e)
appHtml = renderToString(
React.cloneElement(appJSX, {routerContext, error: renderError}),
extractor
)
}
// Setting type: 'application/json' stops the browser from executing the code.
const scriptProps = ssrOnly ? {type: 'application/json'} : {}
let bundles = []
/* istanbul ignore next */
if (extractor) {
bundles = extractor.getScriptElements().map((el) =>
React.cloneElement(el, {
...el.props,
...scriptProps
})
)
}
const helmet = Helmet.renderStatic()
// Return the first error encountered during the rendering pipeline.
const error = appStateError || renderError
// Remove the stacktrace when executing remotely as to not leak any important
// information to users about our system.
if (error && isRemote()) {
delete error.stack
}
// Do not include *dynamic*, executable inline scripts – these cause issues with
// strict CSP headers that customers often want to use. Avoid inline scripts,
// full-stop, whenever possible.
// Each key in `windowGlobals` is expected to be set on the window
// object, client-side, by code in ssr/browser/main.jsx.
//
// Do *not* add to these without a very good reason - globals are a liability.
const windowGlobals = {
__INITIAL_CORRELATION_ID__: res.locals.requestId,
__CONFIG__: config,
__PRELOADED_STATE__: appState,
__ERROR__: error,
__MRT_ENABLE_HTTPONLY_SESSION_COOKIES__: process.env.MRT_ENABLE_HTTPONLY_SESSION_COOKIES,
// `window.Progressive` has a long history at Mobify and some
// client-side code depends on it. Maintain its name out of tradition.
Progressive: getWindowProgressive(req, res)
}
const scripts = [
<script
id="mobify-data"
key="mobify-data"
type="application/json" // Not executable
dangerouslySetInnerHTML={{
__html: serialize(windowGlobals, {isJSON: true, space: indent})
}}
/>,
...bundles
]
const svgs = [<div key="svg_sprite" dangerouslySetInnerHTML={{__html: sprite.stringify()}} />]
const helmetHeadTags = VALID_TAG_NAMES.map(
(tag) => helmet[tag] && helmet[tag].toComponent()
).filter((tag) => tag)
const html = ReactDOMServer.renderToString(
<Document
head={[...helmetHeadTags]}
html={appHtml}
afterBodyStart={svgs}
beforeBodyEnd={scripts}
htmlAttributes={helmet.htmlAttributes.toComponent()}
bodyAttributes={helmet.bodyAttributes.toComponent()}
/>
)
return {error, html: ['<!doctype html>', html].join(''), routerContext}
}
const getWindowProgressive = (req, res) => {
const options = req.app.options || {}
return {
buildOrigin: getAssetUrl(''),
cacheManifest: options.cacheHashManifest || {},
ssrOptions: {
// The hostname and origin under which this page is served
appHostname: options.appHostname,
appOrigin: options.appOrigin,
// The id of the bundle being served, as a string,
// defaulting to 'development' for the local dev server
bundleId: process.env.BUNDLE_ID || 'development',
// The id of the deploy as a string, defaulting to '0'
// for the local dev server
deployId: process.env.DEPLOY_ID || '0',
// On a local dev server, the DEPLOY_TARGET environment variable
// isn't defined by default. Developers may define it if it's
// used by the UPWA to modify behaviour.
deployTarget: process.env.DEPLOY_TARGET || 'local',
proxyConfigs,
// The request class (undefined by default)
requestClass: res.locals.requestClass
}
}
}
const serverRenderer =
// eslint-disable-next-line @typescript-eslint/no-unused-vars
({clientStats, serverStats}) => {
return (req, res, next) => render(req, res, next)
}
export default serverRenderer