-
Notifications
You must be signed in to change notification settings - Fork 28k
/
Copy pathapp-render.tsx
1528 lines (1383 loc) · 50.3 KB
/
app-render.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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import type {
ActionResult,
DynamicParamTypesShort,
FlightData,
FlightRouterState,
FlightSegmentPath,
RenderOpts,
Segment,
CacheNodeSeedData,
} from './types'
import type { StaticGenerationStore } from '../../client/components/static-generation-async-storage.external'
import type { RequestStore } from '../../client/components/request-async-storage.external'
import { getRequestMeta, type NextParsedUrlQuery } from '../request-meta'
import type { LoaderTree } from '../lib/app-dir-module'
import type { AppPageModule } from '../route-modules/app-page/module'
import type { ClientReferenceManifest } from '../../build/webpack/plugins/flight-manifest-plugin'
import type { Revalidate } from '../lib/revalidate'
import type { DeepReadonly } from '../../shared/lib/deep-readonly'
import type { BaseNextRequest, BaseNextResponse } from '../base-http'
import React, { type JSX } from 'react'
import RenderResult, {
type AppPageRenderResultMetadata,
type RenderResultOptions,
type RenderResultResponse,
} from '../render-result'
import {
chainStreams,
renderToInitialFizzStream,
continueFizzStream,
continueDynamicPrerender,
continueStaticPrerender,
continueDynamicHTMLResume,
continueDynamicDataResume,
} from '../stream-utils/node-web-streams-helper'
import { canSegmentBeOverridden } from '../../client/components/match-segments'
import { stripInternalQueries } from '../internal-utils'
import {
NEXT_ROUTER_STATE_TREE,
NEXT_URL,
} from '../../client/components/app-router-headers'
import {
createMetadataComponents,
createMetadataContext,
} from '../../lib/metadata/metadata'
import { RequestAsyncStorageWrapper } from '../async-storage/request-async-storage-wrapper'
import { StaticGenerationAsyncStorageWrapper } from '../async-storage/static-generation-async-storage-wrapper'
import { isNotFoundError } from '../../client/components/not-found'
import {
getURLFromRedirectError,
isRedirectError,
getRedirectStatusCodeFromError,
} from '../../client/components/redirect'
import { addImplicitTags } from '../lib/patch-fetch'
import { AppRenderSpan, NextNodeServerSpan } from '../lib/trace/constants'
import { getTracer } from '../lib/trace/tracer'
import { FlightRenderResult } from './flight-render-result'
import {
createErrorHandler,
ErrorHandlerSource,
type ErrorHandler,
} from './create-error-handler'
import {
getShortDynamicParamType,
dynamicParamTypes,
} from './get-short-dynamic-param-type'
import { getSegmentParam } from './get-segment-param'
import { getScriptNonceFromHeader } from './get-script-nonce-from-header'
import { parseAndValidateFlightRouterState } from './parse-and-validate-flight-router-state'
import { validateURL } from './validate-url'
import { createFlightRouterStateFromLoaderTree } from './create-flight-router-state-from-loader-tree'
import { handleAction } from './action-handler'
import { isBailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr'
import { warn, error } from '../../build/output/log'
import { appendMutableCookies } from '../web/spec-extension/adapters/request-cookies'
import { createServerInsertedHTML } from './server-inserted-html'
import { getRequiredScripts } from './required-scripts'
import { addPathPrefix } from '../../shared/lib/router/utils/add-path-prefix'
import {
getTracedMetadata,
makeGetServerInsertedHTML,
} from './make-get-server-inserted-html'
import { walkTreeWithFlightRouterState } from './walk-tree-with-flight-router-state'
import { createComponentTree } from './create-component-tree'
import { getAssetQueryString } from './get-asset-query-string'
import { setReferenceManifestsSingleton } from './encryption-utils'
import {
createStaticRenderer,
getDynamicDataPostponedState,
getDynamicHTMLPostponedState,
} from './static/static-renderer'
import { isDynamicServerError } from '../../client/components/hooks-server-context'
import {
useFlightStream,
createInlinedDataReadableStream,
flightRenderComplete,
} from './use-flight-response'
import {
StaticGenBailoutError,
isStaticGenBailoutError,
} from '../../client/components/static-generation-bailout'
import { isInterceptionRouteAppPath } from '../lib/interception-routes'
import { getStackWithoutErrorMessage } from '../../lib/format-server-error'
import {
usedDynamicAPIs,
createPostponedAbortSignal,
formatDynamicAPIAccesses,
} from './dynamic-rendering'
import {
getClientComponentLoaderMetrics,
wrapClientComponentLoader,
} from '../client-component-renderer-logger'
import { createServerModuleMap } from './action-utils'
import { isNodeNextRequest } from '../base-http/helpers'
import { parseParameter } from '../../shared/lib/router/utils/route-regex'
export type GetDynamicParamFromSegment = (
// [slug] / [[slug]] / [...slug]
segment: string
) => {
param: string
value: string | string[] | null
treeSegment: Segment
type: DynamicParamTypesShort
} | null
type AppRenderBaseContext = {
staticGenerationStore: StaticGenerationStore
requestStore: RequestStore
componentMod: AppPageModule
renderOpts: RenderOpts
}
export type GenerateFlight = typeof generateFlight
export type AppRenderContext = AppRenderBaseContext & {
getDynamicParamFromSegment: GetDynamicParamFromSegment
query: NextParsedUrlQuery
isPrefetch: boolean
requestTimestamp: number
appUsingSizeAdjustment: boolean
flightRouterState?: FlightRouterState
requestId: string
defaultRevalidate: Revalidate
pagePath: string
clientReferenceManifest: DeepReadonly<ClientReferenceManifest>
assetPrefix: string
flightDataRendererErrorHandler: ErrorHandler
serverComponentsErrorHandler: ErrorHandler
isNotFoundPath: boolean
nonce: string | undefined
res: BaseNextResponse
}
function createNotFoundLoaderTree(loaderTree: LoaderTree): LoaderTree {
// Align the segment with parallel-route-default in next-app-loader
return ['', {}, loaderTree[2]]
}
/* This method is important for intercepted routes to function:
* when a route is intercepted, e.g. /blog/[slug], it will be rendered
* with the layout of the previous page, e.g. /profile/[id]. The problem is
* that the loader tree needs to know the dynamic param in order to render (id and slug in the example).
* Normally they are read from the path but since we are intercepting the route, the path would not contain id,
* so we need to read it from the router state.
*/
function findDynamicParamFromRouterState(
flightRouterState: FlightRouterState | undefined,
segment: string
): {
param: string
value: string | string[] | null
treeSegment: Segment
type: DynamicParamTypesShort
} | null {
if (!flightRouterState) {
return null
}
const treeSegment = flightRouterState[0]
if (canSegmentBeOverridden(segment, treeSegment)) {
if (!Array.isArray(treeSegment) || Array.isArray(segment)) {
return null
}
return {
param: treeSegment[0],
value: treeSegment[1],
treeSegment: treeSegment,
type: treeSegment[2],
}
}
for (const parallelRouterState of Object.values(flightRouterState[1])) {
const maybeDynamicParam = findDynamicParamFromRouterState(
parallelRouterState,
segment
)
if (maybeDynamicParam) {
return maybeDynamicParam
}
}
return null
}
export type CreateSegmentPath = (child: FlightSegmentPath) => FlightSegmentPath
/**
* Returns a function that parses the dynamic segment and return the associated value.
*/
function makeGetDynamicParamFromSegment(
params: { [key: string]: any },
pagePath: string,
flightRouterState: FlightRouterState | undefined
): GetDynamicParamFromSegment {
return function getDynamicParamFromSegment(
// [slug] / [[slug]] / [...slug]
segment: string
) {
const segmentParam = getSegmentParam(segment)
if (!segmentParam) {
return null
}
const key = segmentParam.param
let value = params[key]
// this is a special marker that will be present for interception routes
if (value === '__NEXT_EMPTY_PARAM__') {
value = undefined
}
if (Array.isArray(value)) {
value = value.map((i) => encodeURIComponent(i))
} else if (typeof value === 'string') {
value = encodeURIComponent(value)
}
if (!value) {
const isCatchall = segmentParam.type === 'catchall'
const isOptionalCatchall = segmentParam.type === 'optional-catchall'
if (isCatchall || isOptionalCatchall) {
const dynamicParamType = dynamicParamTypes[segmentParam.type]
// handle the case where an optional catchall does not have a value,
// e.g. `/dashboard/[[...slug]]` when requesting `/dashboard`
if (isOptionalCatchall) {
return {
param: key,
value: null,
type: dynamicParamType,
treeSegment: [key, '', dynamicParamType],
}
}
// handle the case where a catchall or optional catchall does not have a value,
// e.g. `/foo/bar/hello` and `@slot/[...catchall]` or `@slot/[[...catchall]]` is matched
value = pagePath
.split('/')
// remove the first empty string
.slice(1)
// replace any dynamic params with the actual values
.flatMap((pathSegment) => {
const param = parseParameter(pathSegment)
// if the segment matches a param, return the param value
// otherwise, it's a static segment, so just return that
return params[param.key] ?? param.key
})
return {
param: key,
value,
type: dynamicParamType,
// This value always has to be a string.
treeSegment: [key, value.join('/'), dynamicParamType],
}
}
return findDynamicParamFromRouterState(flightRouterState, segment)
}
const type = getShortDynamicParamType(segmentParam.type)
return {
param: key,
// The value that is passed to user code.
value: value,
// The value that is rendered in the router tree.
treeSegment: [key, Array.isArray(value) ? value.join('/') : value, type],
type: type,
}
}
}
// Handle Flight render request. This is only used when client-side navigating. E.g. when you `router.push('/dashboard')` or `router.reload()`.
async function generateFlight(
ctx: AppRenderContext,
options?: {
actionResult: ActionResult
skipFlight: boolean
asNotFound?: boolean
}
): Promise<RenderResult> {
// Flight data that is going to be passed to the browser.
// Currently a single item array but in the future multiple patches might be combined in a single request.
let flightData: FlightData | null = null
const {
componentMod: {
tree: loaderTree,
renderToReadableStream,
createDynamicallyTrackedSearchParams,
},
getDynamicParamFromSegment,
appUsingSizeAdjustment,
staticGenerationStore: { urlPathname },
query,
requestId,
flightRouterState,
} = ctx
if (!options?.skipFlight) {
const [MetadataTree, MetadataOutlet] = createMetadataComponents({
tree: loaderTree,
query,
metadataContext: createMetadataContext(urlPathname, ctx.renderOpts),
getDynamicParamFromSegment,
appUsingSizeAdjustment,
createDynamicallyTrackedSearchParams,
})
flightData = (
await walkTreeWithFlightRouterState({
ctx,
createSegmentPath: (child) => child,
loaderTreeToFilter: loaderTree,
parentParams: {},
flightRouterState,
isFirst: true,
// For flight, render metadata inside leaf page
rscPayloadHead: (
// Adding requestId as react key to make metadata remount for each render
<MetadataTree key={requestId} />
),
injectedCSS: new Set(),
injectedJS: new Set(),
injectedFontPreloadTags: new Set(),
rootLayoutIncluded: false,
asNotFound: ctx.isNotFoundPath || options?.asNotFound,
metadataOutlet: <MetadataOutlet />,
})
).map((path) => path.slice(1)) // remove the '' (root) segment
}
const buildIdFlightDataPair = [ctx.renderOpts.buildId, flightData]
// For app dir, use the bundled version of Flight server renderer (renderToReadableStream)
// which contains the subset React.
const flightReadableStream = renderToReadableStream(
options
? [options.actionResult, buildIdFlightDataPair]
: buildIdFlightDataPair,
ctx.clientReferenceManifest.clientModules,
{
onError: ctx.flightDataRendererErrorHandler,
nonce: ctx.nonce,
}
)
return new FlightRenderResult(flightReadableStream)
}
type RenderToStreamResult = {
stream: RenderResultResponse
err?: unknown
}
type RenderToStreamOptions = {
/**
* This option is used to indicate that the page should be rendered as
* if it was not found. When it's enabled, instead of rendering the
* page component, it renders the not-found segment.
*
*/
asNotFound: boolean
tree: LoaderTree
formState: any
}
/**
* Creates a resolver that eagerly generates a flight payload that is then
* resolved when the resolver is called.
*/
function createFlightDataResolver(ctx: AppRenderContext) {
// Generate the flight data and as soon as it can, convert it into a string.
const promise = generateFlight(ctx)
.then(async (result) => ({
flightData: await result.toUnchunkedBuffer(true),
}))
// Otherwise if it errored, return the error.
.catch((err) => ({ err }))
return async () => {
// Resolve the promise to get the flight data or error.
const result = await promise
// If the flight data failed to render due to an error, re-throw the error
// here.
if ('err' in result) {
throw result.err
}
// Otherwise, return the flight data.
return result.flightData
}
}
type ReactServerAppProps = {
tree: LoaderTree
ctx: AppRenderContext
asNotFound: boolean
}
// This is the root component that runs in the RSC context
async function ReactServerApp({ tree, ctx, asNotFound }: ReactServerAppProps) {
// Create full component tree from root to leaf.
const injectedCSS = new Set<string>()
const injectedJS = new Set<string>()
const injectedFontPreloadTags = new Set<string>()
const missingSlots = new Set<string>()
const {
getDynamicParamFromSegment,
query,
appUsingSizeAdjustment,
componentMod: {
AppRouter,
GlobalError,
createDynamicallyTrackedSearchParams,
},
staticGenerationStore: { urlPathname },
} = ctx
const initialTree = createFlightRouterStateFromLoaderTree(
tree,
getDynamicParamFromSegment,
query
)
const [MetadataTree, MetadataOutlet] = createMetadataComponents({
tree,
errorType: asNotFound ? 'not-found' : undefined,
query,
metadataContext: createMetadataContext(urlPathname, ctx.renderOpts),
getDynamicParamFromSegment: getDynamicParamFromSegment,
appUsingSizeAdjustment: appUsingSizeAdjustment,
createDynamicallyTrackedSearchParams,
})
const { seedData, styles } = await createComponentTree({
ctx,
createSegmentPath: (child) => child,
loaderTree: tree,
parentParams: {},
firstItem: true,
injectedCSS,
injectedJS,
injectedFontPreloadTags,
rootLayoutIncluded: false,
asNotFound: asNotFound,
metadataOutlet: <MetadataOutlet />,
missingSlots,
})
// When the `vary` response header is present with `Next-URL`, that means there's a chance
// it could respond differently if there's an interception route. We provide this information
// to `AppRouter` so that it can properly seed the prefetch cache with a prefix, if needed.
const varyHeader = ctx.res.getHeader('vary')
const couldBeIntercepted =
typeof varyHeader === 'string' && varyHeader.includes(NEXT_URL)
return (
<AppRouter
buildId={ctx.renderOpts.buildId}
assetPrefix={ctx.assetPrefix}
initialCanonicalUrl={urlPathname}
// This is the router state tree.
initialTree={initialTree}
// This is the tree of React nodes that are seeded into the cache
initialSeedData={seedData}
couldBeIntercepted={couldBeIntercepted}
initialHead={
<>
{typeof ctx.res.statusCode === 'number' &&
ctx.res.statusCode > 400 && (
<meta name="robots" content="noindex" />
)}
{/* Adding requestId as react key to make metadata remount for each render */}
<MetadataTree key={ctx.requestId} />
</>
}
initialLayerAssets={styles}
globalErrorComponent={GlobalError}
// This is used to provide debug information (when in development mode)
// about which slots were not filled by page components while creating the component tree.
missingSlots={missingSlots}
/>
)
}
type ReactServerErrorProps = {
tree: LoaderTree
ctx: AppRenderContext
errorType: 'not-found' | 'redirect' | undefined
}
// This is the root component that runs in the RSC context
async function ReactServerError({
tree,
ctx,
errorType,
}: ReactServerErrorProps) {
const {
getDynamicParamFromSegment,
query,
appUsingSizeAdjustment,
componentMod: {
AppRouter,
GlobalError,
createDynamicallyTrackedSearchParams,
},
staticGenerationStore: { urlPathname },
requestId,
res,
} = ctx
const [MetadataTree] = createMetadataComponents({
tree,
metadataContext: createMetadataContext(urlPathname, ctx.renderOpts),
errorType,
query,
getDynamicParamFromSegment,
appUsingSizeAdjustment,
createDynamicallyTrackedSearchParams,
})
const head = (
<>
{/* Adding requestId as react key to make metadata remount for each render */}
<MetadataTree key={requestId} />
{typeof res.statusCode === 'number' && res.statusCode >= 400 && (
<meta name="robots" content="noindex" />
)}
{process.env.NODE_ENV === 'development' && (
<meta name="next-error" content="not-found" />
)}
</>
)
const initialTree = createFlightRouterStateFromLoaderTree(
tree,
getDynamicParamFromSegment,
query
)
// For metadata notFound error there's no global not found boundary on top
// so we create a not found page with AppRouter
const initialSeedData: CacheNodeSeedData = [
initialTree[0],
{},
<html id="__next_error__">
<head></head>
<body></body>
</html>,
null,
]
return (
<AppRouter
buildId={ctx.renderOpts.buildId}
assetPrefix={ctx.assetPrefix}
initialCanonicalUrl={urlPathname}
initialTree={initialTree}
initialHead={head}
initialLayerAssets={null}
globalErrorComponent={GlobalError}
initialSeedData={initialSeedData}
missingSlots={new Set()}
/>
)
}
// This component must run in an SSR context. It will render the RSC root component
function ReactServerEntrypoint<T>({
reactServerStream,
preinitScripts,
clientReferenceManifest,
nonce,
}: {
reactServerStream: BinaryStreamOf<T>
preinitScripts: () => void
clientReferenceManifest: NonNullable<RenderOpts['clientReferenceManifest']>
nonce?: string
}): T {
preinitScripts()
const response = useFlightStream(
reactServerStream,
clientReferenceManifest,
nonce
)
return React.use(response)
}
// We use a trick with TS Generics to branch streams with a type so we can
// consume the parsed value of a Readable Stream if it was constructed with a
// certain object shape. The generic type is not used directly in the type so it
// requires a disabling of the eslint rule disallowing unused vars
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export type BinaryStreamOf<T> = ReadableStream<Uint8Array>
async function renderToHTMLOrFlightImpl(
req: BaseNextRequest,
res: BaseNextResponse,
pagePath: string,
query: NextParsedUrlQuery,
renderOpts: RenderOpts,
baseCtx: AppRenderBaseContext,
requestEndedState: { ended?: boolean }
) {
const isNotFoundPath = pagePath === '/404'
// A unique request timestamp used by development to ensure that it's
// consistent and won't change during this request. This is important to
// avoid that resources can be deduped by React Float if the same resource is
// rendered or preloaded multiple times: `<link href="a.css?v={Date.now()}"/>`.
const requestTimestamp = Date.now()
const {
buildManifest,
subresourceIntegrityManifest,
serverActionsManifest,
ComponentMod,
dev,
nextFontManifest,
supportsDynamicResponse,
serverActions,
appDirDevErrorLogger,
assetPrefix = '',
enableTainting,
} = renderOpts
// We need to expose the bundled `require` API globally for
// react-server-dom-webpack. This is a hack until we find a better way.
if (ComponentMod.__next_app__) {
const instrumented = wrapClientComponentLoader(ComponentMod)
// @ts-ignore
globalThis.__next_require__ = instrumented.require
// @ts-ignore
globalThis.__next_chunk_load__ = instrumented.loadChunk
}
if (
// The type check here ensures that `req` is correctly typed, and the
// environment variable check provides dead code elimination.
process.env.NEXT_RUNTIME !== 'edge' &&
isNodeNextRequest(req)
) {
req.originalRequest.on('end', () => {
requestEndedState.ended = true
if ('performance' in globalThis) {
const metrics = getClientComponentLoaderMetrics({ reset: true })
if (metrics) {
getTracer()
.startSpan(NextNodeServerSpan.clientComponentLoading, {
startTime: metrics.clientComponentLoadStart,
attributes: {
'next.clientComponentLoadCount':
metrics.clientComponentLoadCount,
},
})
.end(
metrics.clientComponentLoadStart +
metrics.clientComponentLoadTimes
)
}
}
})
}
const metadata: AppPageRenderResultMetadata = {}
const appUsingSizeAdjustment = !!nextFontManifest?.appUsingSizeAdjust
// TODO: fix this typescript
const clientReferenceManifest = renderOpts.clientReferenceManifest!
const serverModuleMap = createServerModuleMap({
serverActionsManifest,
pageName: renderOpts.page,
})
setReferenceManifestsSingleton({
clientReferenceManifest,
serverActionsManifest,
serverModuleMap,
})
const digestErrorsMap: Map<string, Error> = new Map()
const allCapturedErrors: Error[] = []
const isNextExport = !!renderOpts.nextExport
const { staticGenerationStore, requestStore } = baseCtx
const { isStaticGeneration } = staticGenerationStore
/**
* Sets the headers on the response object. If we're generating static HTML,
* we store the headers in the metadata object as well so that they can be
* persisted.
*/
const setHeader = isStaticGeneration
? (name: string, value: string | string[]) => {
res.setHeader(name, value)
metadata.headers ??= {}
metadata.headers[name] = res.getHeader(name)
return res
}
: res.setHeader.bind(res)
const isRoutePPREnabled = renderOpts.experimental.isRoutePPREnabled === true
// When static generation fails during PPR, we log the errors separately. We
// intentionally silence the error logger in this case to avoid double
// logging.
const silenceStaticGenerationErrors = isRoutePPREnabled && isStaticGeneration
const serverComponentsErrorHandler = createErrorHandler({
source: ErrorHandlerSource.serverComponents,
dev,
isNextExport,
errorLogger: appDirDevErrorLogger,
digestErrorsMap,
silenceLogger: silenceStaticGenerationErrors,
})
const flightDataRendererErrorHandler = createErrorHandler({
source: ErrorHandlerSource.flightData,
dev,
isNextExport,
errorLogger: appDirDevErrorLogger,
digestErrorsMap,
silenceLogger: silenceStaticGenerationErrors,
})
const htmlRendererErrorHandler = createErrorHandler({
source: ErrorHandlerSource.html,
dev,
isNextExport,
errorLogger: appDirDevErrorLogger,
digestErrorsMap,
allCapturedErrors,
silenceLogger: silenceStaticGenerationErrors,
})
ComponentMod.patchFetch()
if (renderOpts.experimental.after) {
ComponentMod.patchCacheScopeSupportIntoReact()
}
/**
* Rules of Static & Dynamic HTML:
*
* 1.) We must generate static HTML unless the caller explicitly opts
* in to dynamic HTML support.
*
* 2.) If dynamic HTML support is requested, we must honor that request
* or throw an error. It is the sole responsibility of the caller to
* ensure they aren't e.g. requesting dynamic HTML for an AMP page.
*
* These rules help ensure that other existing features like request caching,
* coalescing, and ISR continue working as intended.
*/
const generateStaticHTML = supportsDynamicResponse !== true
// Pull out the hooks/references from the component.
const { tree: loaderTree, taintObjectReference } = ComponentMod
if (enableTainting) {
taintObjectReference(
'Do not pass process.env to client components since it will leak sensitive data',
process.env
)
}
staticGenerationStore.fetchMetrics = []
metadata.fetchMetrics = staticGenerationStore.fetchMetrics
// don't modify original query object
query = { ...query }
stripInternalQueries(query)
const isRSCRequest = Boolean(getRequestMeta(req, 'isRSCRequest'))
const isPrefetchRSCRequest = Boolean(
getRequestMeta(req, 'isPrefetchRSCRequest')
)
/**
* Router state provided from the client-side router. Used to handle rendering
* from the common layout down. This value will be undefined if the request
* is not a client-side navigation request or if the request is a prefetch
* request (except when it's a prefetch request for an interception route
* which is always dynamic).
*/
const shouldProvideFlightRouterState =
isRSCRequest &&
(!isPrefetchRSCRequest ||
!isRoutePPREnabled ||
// Interception routes currently depend on the flight router state to
// extract dynamic params.
isInterceptionRouteAppPath(pagePath))
const parsedFlightRouterState = parseAndValidateFlightRouterState(
req.headers[NEXT_ROUTER_STATE_TREE.toLowerCase()]
)
/**
* The metadata items array created in next-app-loader with all relevant information
* that we need to resolve the final metadata.
*/
let requestId: string
if (process.env.NEXT_RUNTIME === 'edge') {
requestId = crypto.randomUUID()
} else {
requestId = require('next/dist/compiled/nanoid').nanoid()
}
/**
* Dynamic parameters. E.g. when you visit `/dashboard/vercel` which is rendered by `/dashboard/[slug]` the value will be {"slug": "vercel"}.
*/
const params = renderOpts.params ?? {}
const getDynamicParamFromSegment = makeGetDynamicParamFromSegment(
params,
pagePath,
// `FlightRouterState` is unconditionally provided here because this method uses it
// to extract dynamic params as a fallback if they're not present in the path.
parsedFlightRouterState
)
// Get the nonce from the incoming request if it has one.
const csp =
req.headers['content-security-policy'] ||
req.headers['content-security-policy-report-only']
let nonce: string | undefined
if (csp && typeof csp === 'string') {
nonce = getScriptNonceFromHeader(csp)
}
const ctx: AppRenderContext = {
...baseCtx,
getDynamicParamFromSegment,
query,
isPrefetch: isPrefetchRSCRequest,
requestTimestamp,
appUsingSizeAdjustment,
flightRouterState: shouldProvideFlightRouterState
? parsedFlightRouterState
: undefined,
requestId,
defaultRevalidate: false,
pagePath,
clientReferenceManifest,
assetPrefix,
flightDataRendererErrorHandler,
serverComponentsErrorHandler,
isNotFoundPath,
nonce,
res,
}
if (isRSCRequest && !isStaticGeneration) {
return generateFlight(ctx)
}
// Create the resolver that can get the flight payload when it's ready or
// throw the error if it occurred. If we are not generating static HTML, we
// don't need to generate the flight payload because it's a dynamic request
// which means we're either getting the flight payload only or just the
// regular HTML.
const flightDataResolver = isStaticGeneration
? createFlightDataResolver(ctx)
: null
const validateRootLayout = dev
const { HeadManagerContext } =
require('../../shared/lib/head-manager-context.shared-runtime') as typeof import('../../shared/lib/head-manager-context.shared-runtime')
// On each render, create a new `ServerInsertedHTML` context to capture
// injected nodes from user code (`useServerInsertedHTML`).
const { ServerInsertedHTMLProvider, renderServerInsertedHTML } =
createServerInsertedHTML()
getTracer().getRootSpanAttributes()?.set('next.route', pagePath)
const renderToStream = getTracer().wrap(
AppRenderSpan.getBodyResult,
{
spanName: `render route (app) ${pagePath}`,
attributes: {
'next.route': pagePath,
},
},
async ({
asNotFound,
tree,
formState,
}: RenderToStreamOptions): Promise<RenderToStreamResult> => {
const tracingMetadata = getTracedMetadata(
getTracer().getTracePropagationData(),
renderOpts.experimental.clientTraceMetadata
)
const polyfills: JSX.IntrinsicElements['script'][] =
buildManifest.polyfillFiles
.filter(
(polyfill) =>
polyfill.endsWith('.js') && !polyfill.endsWith('.module.js')
)
.map((polyfill) => ({
src: `${assetPrefix}/_next/${polyfill}${getAssetQueryString(
ctx,
false
)}`,
integrity: subresourceIntegrityManifest?.[polyfill],
crossOrigin: renderOpts.crossOrigin,
noModule: true,
nonce,
}))
const [preinitScripts, bootstrapScript] = getRequiredScripts(
buildManifest,
assetPrefix,
renderOpts.crossOrigin,
subresourceIntegrityManifest,
getAssetQueryString(ctx, true),
nonce
)
// We kick off the Flight Request (render) here. It is ok to initiate the render in an arbitrary
// place however it is critical that we only construct the Flight Response inside the SSR
// render so that directives like preloads are correctly piped through
const serverStream = ComponentMod.renderToReadableStream(
<ReactServerApp tree={tree} ctx={ctx} asNotFound={asNotFound} />,
clientReferenceManifest.clientModules,
{
onError: serverComponentsErrorHandler,
nonce,
}
)
// We are going to consume this render both for SSR and for inlining the flight data
let [renderStream, dataStream] = serverStream.tee()
const children = (
<HeadManagerContext.Provider
value={{
appDir: true,
nonce,
}}
>
<ServerInsertedHTMLProvider>
<ReactServerEntrypoint
reactServerStream={renderStream}
preinitScripts={preinitScripts}
clientReferenceManifest={clientReferenceManifest}
nonce={nonce}
/>
</ServerInsertedHTMLProvider>
</HeadManagerContext.Provider>
)
const isResume = !!renderOpts.postponed
const onHeaders =
// During prerenders, we want to capture the headers created so we can
// persist them to the metadata.
staticGenerationStore.prerenderState ||
// During static generation and during resumes we don't
// ask React to emit headers. For Resume this is just not supported
// For static generation we know there will be an entire HTML document
// output and so moving from tag to header for preloading can only
// server to alter preloading priorities in unwanted ways
(!isStaticGeneration && !isResume)
? (headers: Headers) => {
headers.forEach((value, key) => {
setHeader(key, value)
})
}
: undefined