/
createApplicationRouteHandler.tsx
460 lines (426 loc) · 18.2 KB
/
createApplicationRouteHandler.tsx
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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
import {
DefaultOptions as DefaultReactQueryOptions,
QueryClient,
QueryClientProvider,
} from '@tanstack/react-query';
import express from 'express';
import { StrictMode } from 'react';
import { renderToPipeableStream } from 'react-dom/server';
import { Provider as ReduxStoreProvider } from 'react-redux';
import { Store } from 'redux';
import { Shell } from 'framework/applications/shell';
import { ConfigContext } from 'framework/config/react';
import { BaseApplicationConfig } from 'framework/config/types';
import { CSSProvider } from 'framework/infrastructure/css/provider';
import { CSSServerProviderStore } from 'framework/infrastructure/css/provider/serverStore';
import { AppLogger } from 'framework/infrastructure/logger';
import { AppLoggerContext } from 'framework/infrastructure/logger/react/context';
import { createPlatformAPI } from 'framework/infrastructure/platform';
import { createCookieAPI } from 'framework/infrastructure/platform/cookie/server';
import { PlatformAPIContext } from 'framework/infrastructure/platform/shared/context';
import { createWindowApi } from 'framework/infrastructure/platform/window/server';
import { defaultQueryOptions } from 'framework/infrastructure/query/defaultOptions';
import { RaiseErrorContext } from 'framework/infrastructure/raise/react/context';
import { createRaiseErrorStore } from 'framework/infrastructure/raise/store';
import { RouterReduxContext } from 'framework/infrastructure/router/redux/store/context';
import {
AnyAppContext,
AnyAppState,
AnyPage,
ServerRouter,
} from 'framework/infrastructure/router/types';
import { SessionContext } from 'framework/infrastructure/session/context';
import { createJSResourcePathGetter } from 'framework/infrastructure/webpack/getFullPathForStaticResource';
import { Metadata } from 'framework/types/metadata';
import { logApplicationBootstrapError } from './logs/logApplicationBootstrapError';
import { restoreStore } from './store';
import { GetMetadata } from './types';
import { AssetsData, readAssetsInfo, readPageDependenciesStats } from './utils/assets';
import { createOnFinishHadler } from './utils/createOnFinishHadler';
import { createServerSessionObject } from './utils/createServerSessionObject';
import { generateShell } from './utils/generateShell';
import { ReactStreamRenderEnhancer } from './utils/reactStreamRenderEnhancer';
const assetsInfoPromise = readAssetsInfo();
const pageDependenciesStatsPromise = readPageDependenciesStats();
const SERVER_RENDER_ABORT_TIMEOUT = 10000;
/**
* All code is based on https://github.com/facebook/react/blob/master/packages/react-dom/src/server/ReactDOMFizzServerNode.js
* And https://github.com/reactwg/react-18/discussions/37
*/
type Params<Page extends AnyPage<string>> = {
/**
* All methods and configs for a router on a server side
*/
router: ServerRouter;
/**
* React entry point
*/
MainComp: React.ReactNode;
/**
* This config is used during server side lifecycle of the application
*/
serverApplicationConfig: BaseApplicationConfig;
/**
* This config is stored in output HTML
*/
clientApplicationConfig: BaseApplicationConfig;
/**
* Just a logger, which follows AppLogger interface
*/
appLogger: AppLogger;
metadata: {
/**
* An async function, which generates needed metadata
*/
get: GetMetadata<Page>;
defaultBaseMetadata: Pick<Metadata, 'title' | 'description' | 'viewport'>;
};
/**
* A sync function, which returns a static HTML for a error page for the case
* when the problem occured outside of a React scope, or it is a shellError
*/
onErrorFallbackHTML: (error?: Error) => string;
/**
* Default options for react-query
*/
defaultReactQueryOptions?: DefaultReactQueryOptions;
};
/**
* Creates an express handler, which serves an application
*/
export const createApplicationRouteHandler =
<Page extends AnyPage<string>>({
MainComp,
router,
serverApplicationConfig,
clientApplicationConfig,
appLogger,
defaultReactQueryOptions,
metadata,
onErrorFallbackHTML,
}: Params<Page>): express.Handler =>
(req, res) => {
const { parseURL, compileURL, allowedURLQueryKeys, initialAppContext } = router;
res.set('X-Content-Type-Options', 'nosniff');
res.set('X-XSS-Protection', '1');
res.set('X-Frame-Options', 'deny');
let didError = false;
// @JUST_FOR_TEST
const forcedToOnAllReadyRender = req.query['render'] === 'onAllReady';
/**
* For SEO specifically, where the correct status code is extra important,
* you can use onAllReady instead of onReadyToStream as the place
* where you flush the stream. By that point, you'll definitely know if it errored or not.
* However, that also delays when you start giving content to the bot,
* and giving it earlier may give you better rankings due to perf.
*/
const useOnAllReadyRender = req.isSearchBot;
const reactSSRMethodName =
forcedToOnAllReadyRender || useOnAllReadyRender ? 'onAllReady' : 'onShellReady';
const storePromise = restoreStore<Page>({
req,
res,
compileAppURL: compileURL,
parseURL,
initialAppContext,
createReducerOptions: {
allowedURLQueryKeys,
},
});
Promise.all<
[
Promise<Store<AnyAppState<AnyAppContext<Page>>>>,
Promise<AssetsData>,
Promise<{ [pageChunkName: string]: string[] }>,
]
>([storePromise, assetsInfoPromise, pageDependenciesStatsPromise])
.then(([store, assetsInfo, dependencyStats]) => {
const state = store.getState();
const compiledUrl = compileURL(state.appContext);
if (req.url !== '/' && compiledUrl !== req.url.replace(/\/$/, '')) {
if (process.env.NODE_ENV === 'development') {
console.log('--------');
console.log('REDIRECT');
console.log('Requested URL: ', req.url.replace(/\/$/, ''));
console.log('Compiled URL: ', compiledUrl);
console.log('New appContext: ', state.appContext);
console.log('--------');
}
res.redirect(301, compiledUrl);
} else {
const errorRiseStore = createRaiseErrorStore();
const platformAPI = createPlatformAPI({
envSpecificAPIs: {
cookies: createCookieAPI(req, res),
window: createWindowApi(),
},
});
const publicPath = serverApplicationConfig.publicPath;
/**
* Required assets for the application start
*/
const getFullPathForJSFile = createJSResourcePathGetter({
staticResourcesPathMapping: assetsInfo.pathMapping,
publicPath,
});
const reactPath = getFullPathForJSFile('react');
const appPath = getFullPathForJSFile('app');
const vendorPath = getFullPathForJSFile('vendor');
const frameworkPath = getFullPathForJSFile('framework');
const libPath = getFullPathForJSFile('lib');
const rarelyPath = getFullPathForJSFile('rarely');
const queryClient = new QueryClient({
defaultOptions: {
queries: {
...defaultQueryOptions.queries,
...defaultReactQueryOptions?.queries,
},
mutations: {
...defaultQueryOptions.mutations,
...defaultReactQueryOptions?.mutations,
},
},
});
const cssProviderStore = new CSSServerProviderStore();
const session = createServerSessionObject(req, res);
/**
* Each page has its own components, which can be loaded via dynamic import and React.lazy
* These components can have its own children, which are loaded via dynamic import too.
* So, you wait for the first import(), the next import() inside the first one will be delayed.
* And so on.
* The result will be like this:
* comp loading ---- finished
* childComp loading ----- finished
* granChildComp loading ----- finished
* As you can see, we had to wait to much time to load the last dynamic component.
* To prevent this, all dependencies of the current page will be preloaded via async script
*
* As a result you will see something like this:
* comp loading ---- finished
* childComp loading ----- finished
* granChildComp loading ----- finished
*
* Much better!
* More info is here https://github.com/reactwg/react-18/discussions/114
*
* You can manage, what should be preloaded via file name.
* Checkout isNeededToBePreloaded function for more info
*
* Such stats are collected with PageDependenciesManagerPlugin
*/
const pageDependencies = dependencyStats[`${state.appContext.page.name}Page`] || [];
const pageDependenciesScriptTags = pageDependencies
.map(
/**
* onerror is used to fix a bug with webpack and async preloading of dynamic JS-files
* More info: https://github.com/webpack/webpack/issues/14874
*/
(depPath) =>
`<script src="${publicPath}${depPath}" async onerror="this.remove()"></script>`,
)
.join('');
let renderTimeoutId: NodeJS.Timeout | undefined = undefined;
const pipeableStream = renderToPipeableStream(
<StrictMode>
<AppLoggerContext.Provider value={appLogger}>
<PlatformAPIContext.Provider value={platformAPI}>
<SessionContext.Provider value={session}>
<ReduxStoreProvider store={store} context={RouterReduxContext}>
<ConfigContext.Provider value={serverApplicationConfig}>
<QueryClientProvider client={queryClient}>
<CSSProvider cssProviderStore={cssProviderStore}>
<RaiseErrorContext.Provider value={errorRiseStore}>
<Shell
publicPath={publicPath}
assets={{
inlineContent: assetsInfo.inlineContent,
pathMapping: assetsInfo.pathMapping,
}}
state={store.getState()}
mainComp={MainComp}
session={session}
clientApplicationConfig={clientApplicationConfig}
/>
</RaiseErrorContext.Provider>
</CSSProvider>
</QueryClientProvider>
</ConfigContext.Provider>
</ReduxStoreProvider>
</SessionContext.Provider>
</PlatformAPIContext.Provider>
</AppLoggerContext.Provider>
</StrictMode>,
{
bootstrapScripts: [reactPath, appPath, vendorPath, frameworkPath, libPath, rarelyPath],
[reactSSRMethodName]() {
/**
* raisedError can be set in `onAllReady` mode only
* In `onShellReady` raisedError is undefined,
* cause application is not started to render,
* when getRaisedError is called
*/
const raisedError = errorRiseStore.getRaisedError();
/**
* If something errored before we started streaming,
* we set the error code appropriately.
*/
if (didError) {
res.status(500);
/**
* In other case we can try to read raisedError
*/
} else {
res.status(raisedError ? raisedError : 200);
}
res.setHeader('Content-type', 'text/html');
const onFinishHandler = createOnFinishHadler({
res,
queryClient,
renderTimeoutId,
});
/*
* onShellReady do not need correct title and description
* Cause they will be replaced on a client side
* And the main aim here is to start streamming as soon as possible
*/
if (reactSSRMethodName === 'onShellReady') {
res.write(
generateShell({
metadata: metadata.defaultBaseMetadata,
dependencyScript: pageDependenciesScriptTags,
}),
);
pipeableStream
.pipe(new ReactStreamRenderEnhancer(res, queryClient, cssProviderStore))
.once('finish', onFinishHandler);
return;
}
const appContext = store.getState().appContext;
/**
* onCompleteAll will be used for search bots only in the future
* They can not execute any JS, so, there is no any reason to send
* dehydrated data and critical css (which is in a JS wrapper)
*/
metadata
.get({
queryClient,
page: appContext.page,
URLQueryParams: appContext.URLQueryParams,
})
.then(
(metadata) => {
res.write(
generateShell({
metadata,
dependencyScript: pageDependenciesScriptTags,
}),
);
},
(error) => {
logApplicationBootstrapError({
error: error || new Error('getMetaDataError'),
sourceName: 'getMetaData',
appLogger,
});
res.write(
generateShell({
metadata: metadata.defaultBaseMetadata,
dependencyScript: pageDependenciesScriptTags,
}),
);
},
)
/**
* We do not need to block render, if there was a error
* during metadata loading
*/
.finally(() => {
pipeableStream.pipe(res).once('finish', onFinishHandler);
});
},
/**
* If there is an error while generating the shell,
* both onError and onShellError will fire.
* onShellError is used to send the fallback HTML document
*
* Shell contains all compontens from the root to the closest <Suspense />
* Everything inside that <Suspense /> is not a part of the shell.
*
* More info https://beta.reactjs.org/reference/react-dom/server/renderToPipeableStream#recovering-from-errors-outside-the-shell
*/
onShellError(error) {
logApplicationBootstrapError({
error: error instanceof Error ? error : new Error('onShellError'),
sourceName: 'onShellError',
appLogger,
});
if (renderTimeoutId) {
clearTimeout(renderTimeoutId);
}
/**
* Something errored before we could complete the shell,
* so we emit an alternative shell.
*
* We need to check, that headersSent,
* cause tehre is the same handler in onError
*/
if (!res.headersSent) {
res.status(500);
res.setHeader('content-type', 'text/html');
res.send(onErrorFallbackHTML(error as Error));
}
},
/**
* If there is an error while generating the shell,
* both onError and onShellError will fire.
* onError is used for error reporting only
*/
onError(error) {
const preparedError = error instanceof Error ? error : new Error('onError');
didError = true;
if (renderTimeoutId) {
clearTimeout(renderTimeoutId);
}
logApplicationBootstrapError({
error: preparedError,
sourceName: 'onError',
appLogger,
});
/**
* We need to check, that headersSent,
* cause tehre is the same handler in onShellError
*
* In some cases, when error appears somewhere outside of React render
* onError callback is called
*
* But, if error appears in, let's say, shell.tsx,
* both: onError and onShellError are called.
*/
if (!res.headersSent) {
res.status(500);
res.setHeader('content-type', 'text/html');
res.send(onErrorFallbackHTML(preparedError));
}
},
},
);
/**
* Abort current pipeableStream and switch to client rendering
* if enough time passed but server rendering has not been finished yet
*/
renderTimeoutId = setTimeout(() => {
pipeableStream.abort();
}, SERVER_RENDER_ABORT_TIMEOUT);
}
})
.catch((error) => {
logApplicationBootstrapError({
error: error instanceof Error ? error : new Error('InfrastructurePromisesError'),
sourceName: 'InfrastructurePromisesError',
appLogger,
});
res.status(500);
res.setHeader('content-type', 'text/html');
res.send(onErrorFallbackHTML(error));
});
};