-
Notifications
You must be signed in to change notification settings - Fork 27.6k
/
Copy pathbase-server.ts
4221 lines (3743 loc) · 140 KB
/
base-server.ts
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 { __ApiPreviewProps } from './api-utils'
import type { LoadComponentsReturnType } from './load-components'
import type { MiddlewareRouteMatch } from '../shared/lib/router/utils/middleware-route-matcher'
import type { Params } from './request/params'
import {
type FallbackRouteParams,
getFallbackRouteParams,
} from './request/fallback-params'
import type { NextConfig, NextConfigComplete } from './config-shared'
import type {
NextParsedUrlQuery,
NextUrlWithParsedQuery,
RequestMeta,
} from './request-meta'
import type { ParsedUrlQuery } from 'querystring'
import type { RenderOptsPartial as PagesRenderOptsPartial } from './render'
import type {
RenderOptsPartial as AppRenderOptsPartial,
ServerOnInstrumentationRequestError,
} from './app-render/types'
import {
type CachedAppPageValue,
type CachedPageValue,
type ServerComponentsHmrCache,
type ResponseCacheBase,
type ResponseCacheEntry,
type ResponseGenerator,
CachedRouteKind,
type CachedRedirectValue,
} from './response-cache'
import type { UrlWithParsedQuery } from 'url'
import {
NormalizeError,
DecodeError,
normalizeRepeatedSlashes,
MissingStaticPage,
} from '../shared/lib/utils'
import type { PreviewData } from '../types'
import type { PagesManifest } from '../build/webpack/plugins/pages-manifest-plugin'
import type { BaseNextRequest, BaseNextResponse } from './base-http'
import type {
ManifestRewriteRoute,
ManifestRoute,
PrerenderManifest,
} from '../build'
import type { ClientReferenceManifest } from '../build/webpack/plugins/flight-manifest-plugin'
import type { NextFontManifest } from '../build/webpack/plugins/next-font-manifest-plugin'
import type {
AppPageRouteHandlerContext,
AppPageRouteModule,
} from './route-modules/app-page/module'
import type { PagesAPIRouteMatch } from './route-matches/pages-api-route-match'
import type { AppRouteRouteHandlerContext } from './route-modules/app-route/module'
import type {
Server as HTTPServer,
IncomingMessage,
ServerResponse as HTTPServerResponse,
} from 'http'
import type { MiddlewareMatcher } from '../build/analysis/get-page-static-info'
import type { TLSSocket } from 'tls'
import type { PathnameNormalizer } from './normalizers/request/pathname-normalizer'
import type { InstrumentationModule } from './instrumentation/types'
import { format as formatUrl, parse as parseUrl } from 'url'
import { formatHostname } from './lib/format-hostname'
import { getRedirectStatus } from '../lib/redirect-status'
import { isEdgeRuntime } from '../lib/is-edge-runtime'
import {
APP_PATHS_MANIFEST,
NEXT_BUILTIN_DOCUMENT,
PAGES_MANIFEST,
STATIC_STATUS_PAGES,
UNDERSCORE_NOT_FOUND_ROUTE,
UNDERSCORE_NOT_FOUND_ROUTE_ENTRY,
} from '../shared/lib/constants'
import { isDynamicRoute } from '../shared/lib/router/utils'
import { checkIsOnDemandRevalidate } from './api-utils'
import { setConfig } from '../shared/lib/runtime-config.external'
import {
formatRevalidate,
type Revalidate,
type ExpireTime,
} from './lib/revalidate'
import { execOnce } from '../shared/lib/utils'
import { isBlockedPage } from './utils'
import { getBotType, isBot } from '../shared/lib/router/utils/is-bot'
import RenderResult from './render-result'
import { removeTrailingSlash } from '../shared/lib/router/utils/remove-trailing-slash'
import { denormalizePagePath } from '../shared/lib/page-path/denormalize-page-path'
import * as Log from '../build/output/log'
import { getUtils } from './server-utils'
import isError, { getProperError } from '../lib/is-error'
import {
addRequestMeta,
getRequestMeta,
removeRequestMeta,
setRequestMeta,
} from './request-meta'
import { removePathPrefix } from '../shared/lib/router/utils/remove-path-prefix'
import { normalizeAppPath } from '../shared/lib/router/utils/app-paths'
import { getHostname } from '../shared/lib/get-hostname'
import { parseUrl as parseUrlUtil } from '../shared/lib/router/utils/parse-url'
import { getNextPathnameInfo } from '../shared/lib/router/utils/get-next-pathname-info'
import {
RSC_HEADER,
NEXT_RSC_UNION_QUERY,
NEXT_ROUTER_PREFETCH_HEADER,
NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,
NEXT_DID_POSTPONE_HEADER,
NEXT_URL,
NEXT_ROUTER_STATE_TREE_HEADER,
NEXT_IS_PRERENDER_HEADER,
} from '../client/components/app-router-headers'
import type {
MatchOptions,
RouteMatcherManager,
} from './route-matcher-managers/route-matcher-manager'
import { LocaleRouteNormalizer } from './normalizers/locale-route-normalizer'
import { DefaultRouteMatcherManager } from './route-matcher-managers/default-route-matcher-manager'
import { AppPageRouteMatcherProvider } from './route-matcher-providers/app-page-route-matcher-provider'
import { AppRouteRouteMatcherProvider } from './route-matcher-providers/app-route-route-matcher-provider'
import { PagesAPIRouteMatcherProvider } from './route-matcher-providers/pages-api-route-matcher-provider'
import { PagesRouteMatcherProvider } from './route-matcher-providers/pages-route-matcher-provider'
import { ServerManifestLoader } from './route-matcher-providers/helpers/manifest-loaders/server-manifest-loader'
import { getTracer, isBubbledError, SpanKind } from './lib/trace/tracer'
import { BaseServerSpan } from './lib/trace/constants'
import { I18NProvider } from './lib/i18n-provider'
import { sendResponse } from './send-response'
import {
fromNodeOutgoingHttpHeaders,
normalizeNextQueryParam,
toNodeOutgoingHttpHeaders,
} from './web/utils'
import {
CACHE_ONE_YEAR,
INFINITE_CACHE,
MATCHED_PATH_HEADER,
NEXT_CACHE_REVALIDATED_TAGS_HEADER,
NEXT_CACHE_TAGS_HEADER,
NEXT_RESUME_HEADER,
} from '../lib/constants'
import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path'
import {
NextRequestAdapter,
signalFromNodeResponse,
} from './web/spec-extension/adapters/next-request'
import { matchNextDataPathname } from './lib/match-next-data-pathname'
import getRouteFromAssetPath from '../shared/lib/router/utils/get-route-from-asset-path'
import { decodePathParams } from './lib/router-utils/decode-path-params'
import { RSCPathnameNormalizer } from './normalizers/request/rsc'
import { stripFlightHeaders } from './app-render/strip-flight-headers'
import {
isAppPageRouteModule,
isAppRouteRouteModule,
isPagesRouteModule,
} from './route-modules/checks'
import { PrefetchRSCPathnameNormalizer } from './normalizers/request/prefetch-rsc'
import { NextDataPathnameNormalizer } from './normalizers/request/next-data'
import { getIsServerAction } from './lib/server-action-request-meta'
import { isInterceptionRouteAppPath } from './lib/interception-routes'
import { toRoute } from './lib/to-route'
import type { DeepReadonly } from '../shared/lib/deep-readonly'
import { isNodeNextRequest, isNodeNextResponse } from './base-http/helpers'
import { patchSetHeaderWithCookieSupport } from './lib/patch-set-header'
import { checkIsAppPPREnabled } from './lib/experimental/ppr'
import {
getBuiltinRequestContext,
type WaitUntil,
} from './after/builtin-request-context'
import { ENCODED_TAGS } from './stream-utils/encodedTags'
import { NextRequestHint } from './web/adapter'
import { getRevalidateReason } from './instrumentation/utils'
import { RouteKind } from './route-kind'
import type { RouteModule } from './route-modules/route-module'
import { FallbackMode, parseFallbackField } from '../lib/fallback'
import { toResponseCacheEntry } from './response-cache/utils'
import { scheduleOnNextTick } from '../lib/scheduler'
import { SegmentPrefixRSCPathnameNormalizer } from './normalizers/request/segment-prefix-rsc'
import {
shouldServeStreamingMetadata,
isHtmlBotRequestStreamingMetadata,
} from './lib/streaming-metadata'
export type FindComponentsResult = {
components: LoadComponentsReturnType
query: NextParsedUrlQuery
}
export interface MiddlewareRoutingItem {
page: string
match: MiddlewareRouteMatch
matchers?: MiddlewareMatcher[]
}
export type RouteHandler<
ServerRequest extends BaseNextRequest = BaseNextRequest,
ServerResponse extends BaseNextResponse = BaseNextResponse,
> = (
req: ServerRequest,
res: ServerResponse,
parsedUrl: NextUrlWithParsedQuery
) => PromiseLike<boolean> | boolean
/**
* The normalized route manifest is the same as the route manifest, but with
* the rewrites normalized to the object shape that the router expects.
*/
export type NormalizedRouteManifest = {
readonly dynamicRoutes: ReadonlyArray<ManifestRoute>
readonly rewrites: {
readonly beforeFiles: ReadonlyArray<ManifestRewriteRoute>
readonly afterFiles: ReadonlyArray<ManifestRewriteRoute>
readonly fallback: ReadonlyArray<ManifestRewriteRoute>
}
}
export interface Options {
/**
* Object containing the configuration next.config.js
*/
conf: NextConfig
/**
* Set to false when the server was created by Next.js
*/
customServer?: boolean
/**
* Tells if Next.js is running in dev mode
*/
dev?: boolean
/**
* Enables the experimental testing mode.
*/
experimentalTestProxy?: boolean
/**
* Whether or not the dev server is running in experimental HTTPS mode
*/
experimentalHttpsServer?: boolean
/**
* Where the Next project is located
*/
dir?: string
/**
* Tells if Next.js is at the platform-level
*/
minimalMode?: boolean
/**
* Hide error messages containing server information
*/
quiet?: boolean
/**
* The hostname the server is running behind
*/
hostname?: string
/**
* The port the server is running behind
*/
port?: number
/**
* The HTTP Server that Next.js is running behind
*/
httpServer?: HTTPServer
}
export type RenderOpts = PagesRenderOptsPartial & AppRenderOptsPartial
export type LoadedRenderOpts = RenderOpts &
LoadComponentsReturnType &
RequestLifecycleOpts
export type RequestLifecycleOpts = {
waitUntil: ((promise: Promise<any>) => void) | undefined
onClose: (callback: () => void) => void
onAfterTaskError: ((error: unknown) => void) | undefined
}
type BaseRenderOpts = RenderOpts & {
poweredByHeader: boolean
generateEtags: boolean
previewProps: __ApiPreviewProps
}
/**
* The public interface for rendering with the server programmatically. This
* would typically only allow the base request or response to extend it, but
* because this can be programmatically accessed, we assume that it could also
* be the base Node.js request and response types.
*/
export interface BaseRequestHandler<
ServerRequest extends BaseNextRequest | IncomingMessage = BaseNextRequest,
ServerResponse extends
| BaseNextResponse
| HTTPServerResponse = BaseNextResponse,
> {
(
req: ServerRequest,
res: ServerResponse,
parsedUrl?: NextUrlWithParsedQuery | undefined
): Promise<void> | void
}
export type RequestContext<
ServerRequest extends BaseNextRequest = BaseNextRequest,
ServerResponse extends BaseNextResponse = BaseNextResponse,
> = {
req: ServerRequest
res: ServerResponse
pathname: string
query: NextParsedUrlQuery
renderOpts: RenderOpts
}
export class NoFallbackError extends Error {}
// Internal wrapper around build errors at development
// time, to prevent us from propagating or logging them
export class WrappedBuildError extends Error {
innerError: Error
constructor(innerError: Error) {
super()
this.innerError = innerError
}
}
type ResponsePayload = {
type: 'html' | 'json' | 'rsc'
body: RenderResult
revalidate?: Revalidate | undefined
}
export type NextEnabledDirectories = {
readonly pages: boolean
readonly app: boolean
}
export default abstract class Server<
ServerOptions extends Options = Options,
ServerRequest extends BaseNextRequest = BaseNextRequest,
ServerResponse extends BaseNextResponse = BaseNextResponse,
> {
public readonly hostname?: string
public readonly fetchHostname?: string
public readonly port?: number
protected readonly dir: string
protected readonly quiet: boolean
protected readonly nextConfig: NextConfigComplete
protected readonly distDir: string
protected readonly publicDir: string
protected readonly hasStaticDir: boolean
protected readonly pagesManifest?: PagesManifest
protected readonly appPathsManifest?: PagesManifest
protected readonly buildId: string
protected readonly minimalMode: boolean
protected readonly renderOpts: BaseRenderOpts
protected readonly serverOptions: Readonly<ServerOptions>
protected readonly appPathRoutes?: Record<string, string[]>
protected readonly clientReferenceManifest?: DeepReadonly<ClientReferenceManifest>
protected interceptionRoutePatterns: RegExp[]
protected nextFontManifest?: DeepReadonly<NextFontManifest>
protected instrumentation: InstrumentationModule | undefined
private readonly responseCache: ResponseCacheBase
protected abstract getPublicDir(): string
protected abstract getHasStaticDir(): boolean
protected abstract getPagesManifest(): PagesManifest | undefined
protected abstract getAppPathsManifest(): PagesManifest | undefined
protected abstract getBuildId(): string
protected abstract getinterceptionRoutePatterns(): RegExp[]
protected readonly enabledDirectories: NextEnabledDirectories
protected abstract getEnabledDirectories(dev: boolean): NextEnabledDirectories
protected readonly experimentalTestProxy?: boolean
protected abstract findPageComponents(params: {
locale: string | undefined
page: string
query: NextParsedUrlQuery
params: Params
isAppPath: boolean
// The following parameters are used in the development server's
// implementation.
sriEnabled?: boolean
appPaths?: ReadonlyArray<string> | null
shouldEnsure?: boolean
url?: string
}): Promise<FindComponentsResult | null>
protected abstract getPrerenderManifest(): DeepReadonly<PrerenderManifest>
protected abstract getNextFontManifest():
| DeepReadonly<NextFontManifest>
| undefined
protected abstract attachRequestMeta(
req: ServerRequest,
parsedUrl: NextUrlWithParsedQuery
): void
protected abstract hasPage(pathname: string): Promise<boolean>
protected abstract sendRenderResult(
req: ServerRequest,
res: ServerResponse,
options: {
result: RenderResult
type: 'html' | 'json' | 'rsc'
generateEtags: boolean
poweredByHeader: boolean
revalidate: Revalidate | undefined
expireTime: ExpireTime | undefined
}
): Promise<void>
protected abstract runApi(
req: ServerRequest,
res: ServerResponse,
query: ParsedUrlQuery,
match: PagesAPIRouteMatch
): Promise<boolean>
protected abstract renderHTML(
req: ServerRequest,
res: ServerResponse,
pathname: string,
query: NextParsedUrlQuery,
renderOpts: LoadedRenderOpts
): Promise<RenderResult>
protected abstract getIncrementalCache(options: {
requestHeaders: Record<string, undefined | string | string[]>
requestProtocol: 'http' | 'https'
}): Promise<import('./lib/incremental-cache').IncrementalCache>
protected abstract getResponseCache(options: {
dev: boolean
}): ResponseCacheBase
protected getServerComponentsHmrCache():
| ServerComponentsHmrCache
| undefined {
return this.nextConfig.experimental.serverComponentsHmrCache
? (globalThis as any).__serverComponentsHmrCache
: undefined
}
protected abstract loadEnvConfig(params: {
dev: boolean
forceReload?: boolean
}): void
// TODO-APP: (wyattjoh): Make protected again. Used for turbopack in route-resolver.ts right now.
public readonly matchers: RouteMatcherManager
protected readonly i18nProvider?: I18NProvider
protected readonly localeNormalizer?: LocaleRouteNormalizer
protected readonly normalizers: {
readonly rsc: RSCPathnameNormalizer | undefined
readonly prefetchRSC: PrefetchRSCPathnameNormalizer | undefined
readonly segmentPrefetchRSC: SegmentPrefixRSCPathnameNormalizer | undefined
readonly data: NextDataPathnameNormalizer | undefined
}
private readonly isAppPPREnabled: boolean
private readonly isAppSegmentPrefetchEnabled: boolean
/**
* This is used to persist cache scopes across
* prefetch -> full route requests for dynamic IO
* it's only fully used in dev
*/
public constructor(options: ServerOptions) {
const {
dir = '.',
quiet = false,
conf,
dev = false,
minimalMode = false,
hostname,
port,
experimentalTestProxy,
} = options
this.experimentalTestProxy = experimentalTestProxy
this.serverOptions = options
this.dir =
process.env.NEXT_RUNTIME === 'edge' ? dir : require('path').resolve(dir)
this.quiet = quiet
this.loadEnvConfig({ dev })
// TODO: should conf be normalized to prevent missing
// values from causing issues as this can be user provided
this.nextConfig = conf as NextConfigComplete
this.hostname = hostname
if (this.hostname) {
// we format the hostname so that it can be fetched
this.fetchHostname = formatHostname(this.hostname)
}
this.port = port
this.distDir =
process.env.NEXT_RUNTIME === 'edge'
? this.nextConfig.distDir
: require('path').join(this.dir, this.nextConfig.distDir)
this.publicDir = this.getPublicDir()
this.hasStaticDir = !minimalMode && this.getHasStaticDir()
this.i18nProvider = this.nextConfig.i18n?.locales
? new I18NProvider(this.nextConfig.i18n)
: undefined
// Configure the locale normalizer, it's used for routes inside `pages/`.
this.localeNormalizer = this.i18nProvider
? new LocaleRouteNormalizer(this.i18nProvider)
: undefined
// Only serverRuntimeConfig needs the default
// publicRuntimeConfig gets it's default in client/index.js
const {
serverRuntimeConfig = {},
publicRuntimeConfig,
assetPrefix,
generateEtags,
} = this.nextConfig
this.buildId = this.getBuildId()
// this is a hack to avoid Webpack knowing this is equal to this.minimalMode
// because we replace this.minimalMode to true in production bundles.
const minimalModeKey = 'minimalMode'
this[minimalModeKey] =
minimalMode || !!process.env.NEXT_PRIVATE_MINIMAL_MODE
this.enabledDirectories = this.getEnabledDirectories(dev)
this.isAppPPREnabled =
this.enabledDirectories.app &&
checkIsAppPPREnabled(this.nextConfig.experimental.ppr)
this.isAppSegmentPrefetchEnabled =
this.enabledDirectories.app &&
this.nextConfig.experimental.clientSegmentCache === true
this.normalizers = {
// We should normalize the pathname from the RSC prefix only in minimal
// mode as otherwise that route is not exposed external to the server as
// we instead only rely on the headers.
rsc:
this.enabledDirectories.app && this.minimalMode
? new RSCPathnameNormalizer()
: undefined,
prefetchRSC:
this.isAppPPREnabled && this.minimalMode
? new PrefetchRSCPathnameNormalizer()
: undefined,
segmentPrefetchRSC:
this.isAppSegmentPrefetchEnabled && this.minimalMode
? new SegmentPrefixRSCPathnameNormalizer()
: undefined,
data: this.enabledDirectories.pages
? new NextDataPathnameNormalizer(this.buildId)
: undefined,
}
this.nextFontManifest = this.getNextFontManifest()
if (process.env.NEXT_RUNTIME !== 'edge') {
process.env.NEXT_DEPLOYMENT_ID = this.nextConfig.deploymentId || ''
}
this.renderOpts = {
supportsDynamicResponse: true,
trailingSlash: this.nextConfig.trailingSlash,
deploymentId: this.nextConfig.deploymentId,
strictNextHead: this.nextConfig.experimental.strictNextHead ?? true,
poweredByHeader: this.nextConfig.poweredByHeader,
canonicalBase: this.nextConfig.amp.canonicalBase || '',
generateEtags,
previewProps: this.getPrerenderManifest().preview,
ampOptimizerConfig: this.nextConfig.experimental.amp?.optimizer,
basePath: this.nextConfig.basePath,
images: this.nextConfig.images,
optimizeCss: this.nextConfig.experimental.optimizeCss,
nextConfigOutput: this.nextConfig.output,
nextScriptWorkers: this.nextConfig.experimental.nextScriptWorkers,
disableOptimizedLoading:
this.nextConfig.experimental.disableOptimizedLoading,
domainLocales: this.nextConfig.i18n?.domains,
distDir: this.distDir,
serverComponents: this.enabledDirectories.app,
cacheLifeProfiles: this.nextConfig.experimental.cacheLife,
enableTainting: this.nextConfig.experimental.taint,
crossOrigin: this.nextConfig.crossOrigin
? this.nextConfig.crossOrigin
: undefined,
largePageDataBytes: this.nextConfig.experimental.largePageDataBytes,
// Only the `publicRuntimeConfig` key is exposed to the client side
// It'll be rendered as part of __NEXT_DATA__ on the client side
runtimeConfig:
Object.keys(publicRuntimeConfig).length > 0
? publicRuntimeConfig
: undefined,
// @ts-expect-error internal field not publicly exposed
isExperimentalCompile: this.nextConfig.experimental.isExperimentalCompile,
experimental: {
expireTime: this.nextConfig.expireTime,
clientTraceMetadata: this.nextConfig.experimental.clientTraceMetadata,
dynamicIO: this.nextConfig.experimental.dynamicIO ?? false,
clientSegmentCache:
this.nextConfig.experimental.clientSegmentCache ?? false,
inlineCss: this.nextConfig.experimental.inlineCss ?? false,
authInterrupts: !!this.nextConfig.experimental.authInterrupts,
streamingMetadata: !!this.nextConfig.experimental.streamingMetadata,
htmlLimitedBots: this.nextConfig.experimental.htmlLimitedBots,
},
onInstrumentationRequestError:
this.instrumentationOnRequestError.bind(this),
reactMaxHeadersLength: this.nextConfig.reactMaxHeadersLength,
}
// Initialize next/config with the environment configuration
setConfig({
serverRuntimeConfig,
publicRuntimeConfig,
})
this.pagesManifest = this.getPagesManifest()
this.appPathsManifest = this.getAppPathsManifest()
this.appPathRoutes = this.getAppPathRoutes()
this.interceptionRoutePatterns = this.getinterceptionRoutePatterns()
// Configure the routes.
this.matchers = this.getRouteMatchers()
// Start route compilation. We don't wait for the routes to finish loading
// because we use the `waitTillReady` promise below in `handleRequest` to
// wait. Also we can't `await` in the constructor.
void this.matchers.reload()
this.setAssetPrefix(assetPrefix)
this.responseCache = this.getResponseCache({ dev })
}
protected reloadMatchers() {
return this.matchers.reload()
}
private handleRSCRequest: RouteHandler<ServerRequest, ServerResponse> = (
req,
_res,
parsedUrl
) => {
if (!parsedUrl.pathname) return false
if (this.normalizers.segmentPrefetchRSC?.match(parsedUrl.pathname)) {
const result = this.normalizers.segmentPrefetchRSC.extract(
parsedUrl.pathname
)
if (!result) return false
const { originalPathname, segmentPath } = result
parsedUrl.pathname = originalPathname
// Mark the request as a router prefetch request.
req.headers[RSC_HEADER.toLowerCase()] = '1'
req.headers[NEXT_ROUTER_PREFETCH_HEADER.toLowerCase()] = '1'
req.headers[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER.toLowerCase()] =
segmentPath
addRequestMeta(req, 'isRSCRequest', true)
addRequestMeta(req, 'isPrefetchRSCRequest', true)
addRequestMeta(req, 'segmentPrefetchRSCRequest', segmentPath)
} else if (this.normalizers.prefetchRSC?.match(parsedUrl.pathname)) {
parsedUrl.pathname = this.normalizers.prefetchRSC.normalize(
parsedUrl.pathname,
true
)
// Mark the request as a router prefetch request.
req.headers[RSC_HEADER.toLowerCase()] = '1'
req.headers[NEXT_ROUTER_PREFETCH_HEADER.toLowerCase()] = '1'
addRequestMeta(req, 'isRSCRequest', true)
addRequestMeta(req, 'isPrefetchRSCRequest', true)
} else if (this.normalizers.rsc?.match(parsedUrl.pathname)) {
parsedUrl.pathname = this.normalizers.rsc.normalize(
parsedUrl.pathname,
true
)
// Mark the request as a RSC request.
req.headers[RSC_HEADER.toLowerCase()] = '1'
addRequestMeta(req, 'isRSCRequest', true)
} else if (req.headers['x-now-route-matches']) {
// If we didn't match, return with the flight headers stripped. If in
// minimal mode we didn't match based on the path, this can't be a RSC
// request. This is because Vercel only sends this header during
// revalidation requests and we want the cache to instead depend on the
// request path for flight information.
stripFlightHeaders(req.headers)
return false
} else if (req.headers[RSC_HEADER.toLowerCase()] === '1') {
addRequestMeta(req, 'isRSCRequest', true)
if (req.headers[NEXT_ROUTER_PREFETCH_HEADER.toLowerCase()] === '1') {
addRequestMeta(req, 'isPrefetchRSCRequest', true)
const segmentPrefetchRSCRequest =
req.headers[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER.toLowerCase()]
if (typeof segmentPrefetchRSCRequest === 'string') {
addRequestMeta(
req,
'segmentPrefetchRSCRequest',
segmentPrefetchRSCRequest
)
}
}
} else {
// Otherwise just return without doing anything.
return false
}
if (req.url) {
const parsed = parseUrl(req.url)
parsed.pathname = parsedUrl.pathname
req.url = formatUrl(parsed)
}
return false
}
private handleNextDataRequest: RouteHandler<ServerRequest, ServerResponse> =
async (req, res, parsedUrl) => {
const middleware = this.getMiddleware()
const params = matchNextDataPathname(parsedUrl.pathname)
// ignore for non-next data URLs
if (!params || !params.path) {
return false
}
if (params.path[0] !== this.buildId) {
// Ignore if its a middleware request when we aren't on edge.
if (
process.env.NEXT_RUNTIME !== 'edge' &&
getRequestMeta(req, 'middlewareInvoke')
) {
return false
}
// Make sure to 404 if the buildId isn't correct
await this.render404(req, res, parsedUrl)
return true
}
// remove buildId from URL
params.path.shift()
const lastParam = params.path[params.path.length - 1]
// show 404 if it doesn't end with .json
if (typeof lastParam !== 'string' || !lastParam.endsWith('.json')) {
await this.render404(req, res, parsedUrl)
return true
}
// re-create page's pathname
let pathname = `/${params.path.join('/')}`
pathname = getRouteFromAssetPath(pathname, '.json')
// ensure trailing slash is normalized per config
if (middleware) {
if (this.nextConfig.trailingSlash && !pathname.endsWith('/')) {
pathname += '/'
}
if (
!this.nextConfig.trailingSlash &&
pathname.length > 1 &&
pathname.endsWith('/')
) {
pathname = pathname.substring(0, pathname.length - 1)
}
}
if (this.i18nProvider) {
// Remove the port from the hostname if present.
const hostname = req?.headers.host?.split(':', 1)[0].toLowerCase()
const domainLocale = this.i18nProvider.detectDomainLocale(hostname)
const defaultLocale =
domainLocale?.defaultLocale ?? this.i18nProvider.config.defaultLocale
const localePathResult = this.i18nProvider.analyze(pathname)
// If the locale is detected from the path, we need to remove it
// from the pathname.
if (localePathResult.detectedLocale) {
pathname = localePathResult.pathname
}
// Update the query with the detected locale and default locale.
addRequestMeta(req, 'locale', localePathResult.detectedLocale)
addRequestMeta(req, 'defaultLocale', defaultLocale)
// If the locale is not detected from the path, we need to mark that
// it was not inferred from default.
if (!localePathResult.detectedLocale) {
removeRequestMeta(req, 'localeInferredFromDefault')
}
// If no locale was detected and we don't have middleware, we need
// to render a 404 page.
if (!localePathResult.detectedLocale && !middleware) {
addRequestMeta(req, 'locale', defaultLocale)
await this.render404(req, res, parsedUrl)
return true
}
}
parsedUrl.pathname = pathname
addRequestMeta(req, 'isNextDataReq', true)
return false
}
protected handleNextImageRequest: RouteHandler<
ServerRequest,
ServerResponse
> = () => false
protected handleCatchallRenderRequest: RouteHandler<
ServerRequest,
ServerResponse
> = () => false
protected handleCatchallMiddlewareRequest: RouteHandler<
ServerRequest,
ServerResponse
> = () => false
protected getRouteMatchers(): RouteMatcherManager {
// Create a new manifest loader that get's the manifests from the server.
const manifestLoader = new ServerManifestLoader((name) => {
switch (name) {
case PAGES_MANIFEST:
return this.getPagesManifest() ?? null
case APP_PATHS_MANIFEST:
return this.getAppPathsManifest() ?? null
default:
return null
}
})
// Configure the matchers and handlers.
const matchers: RouteMatcherManager = new DefaultRouteMatcherManager()
// Match pages under `pages/`.
matchers.push(
new PagesRouteMatcherProvider(
this.distDir,
manifestLoader,
this.i18nProvider
)
)
// Match api routes under `pages/api/`.
matchers.push(
new PagesAPIRouteMatcherProvider(
this.distDir,
manifestLoader,
this.i18nProvider
)
)
// If the app directory is enabled, then add the app matchers and handlers.
if (this.enabledDirectories.app) {
// Match app pages under `app/`.
matchers.push(
new AppPageRouteMatcherProvider(this.distDir, manifestLoader)
)
matchers.push(
new AppRouteRouteMatcherProvider(this.distDir, manifestLoader)
)
}
return matchers
}
protected async instrumentationOnRequestError(
...args: Parameters<ServerOnInstrumentationRequestError>
) {
const [err, req, ctx] = args
if (this.instrumentation) {
try {
await this.instrumentation.onRequestError?.(
err,
{
path: req.url || '',
method: req.method || 'GET',
// Normalize middleware headers and other server request headers
headers:
req instanceof NextRequestHint
? Object.fromEntries(req.headers.entries())
: req.headers,
},
ctx
)
} catch (handlerErr) {
// Log the soft error and continue, since errors can thrown from react stream handler
console.error('Error in instrumentation.onRequestError:', handlerErr)
}
}
}
public logError(err: Error): void {
if (this.quiet) return
Log.error(err)
}
public async handleRequest(
req: ServerRequest,
res: ServerResponse,
parsedUrl?: NextUrlWithParsedQuery
): Promise<void> {
await this.prepare()
const method = req.method.toUpperCase()
const tracer = getTracer()
return tracer.withPropagatedContext(req.headers, () => {
return tracer.trace(
BaseServerSpan.handleRequest,
{
spanName: `${method} ${req.url}`,
kind: SpanKind.SERVER,
attributes: {
'http.method': method,
'http.target': req.url,
},
},
async (span) =>
this.handleRequestImpl(req, res, parsedUrl).finally(() => {
if (!span) return
const isRSCRequest = getRequestMeta(req, 'isRSCRequest') ?? false
span.setAttributes({
'http.status_code': res.statusCode,
'next.rsc': isRSCRequest,
})
const rootSpanAttributes = tracer.getRootSpanAttributes()
// We were unable to get attributes, probably OTEL is not enabled
if (!rootSpanAttributes) return
if (
rootSpanAttributes.get('next.span_type') !==
BaseServerSpan.handleRequest
) {
console.warn(
`Unexpected root span type '${rootSpanAttributes.get(
'next.span_type'
)}'. Please report this Next.js issue https://github.com/vercel/next.js`
)
return
}
const route = rootSpanAttributes.get('next.route')
if (route) {
const name = isRSCRequest
? `RSC ${method} ${route}`
: `${method} ${route}`
span.setAttributes({
'next.route': route,
'http.route': route,
'next.span_name': name,
})
span.updateName(name)
} else {
span.updateName(
isRSCRequest
? `RSC ${method} ${req.url}`
: `${method} ${req.url}`
)
}
})
)
})
}
private async handleRequestImpl(
req: ServerRequest,
res: ServerResponse,
parsedUrl?: NextUrlWithParsedQuery
): Promise<void> {
try {
// Wait for the matchers to be ready.
await this.matchers.waitTillReady()
// ensure cookies set in middleware are merged and
// not overridden by API routes/getServerSideProps