-
Notifications
You must be signed in to change notification settings - Fork 26.6k
/
base-server.ts
3453 lines (3036 loc) · 112 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 { FontManifest, FontConfig } from './font-utils'
import type { LoadComponentsReturnType } from './load-components'
import type { MiddlewareRouteMatch } from '../shared/lib/router/utils/middleware-route-matcher'
import type { Params } from '../shared/lib/router/utils/route-matcher'
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 } from './app-render/types'
import type { ResponseCacheBase, ResponseCacheEntry } from './response-cache'
import type { UrlWithParsedQuery } from 'url'
import {
NormalizeError,
DecodeError,
normalizeRepeatedSlashes,
MissingStaticPage,
} from '../shared/lib/utils'
import type { PreviewData } from 'next/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 { AppPageRouteModule } from './future/route-modules/app-page/module'
import type { NodeNextRequest, NodeNextResponse } from './base-http/node'
import type { WebNextRequest, WebNextResponse } from './base-http/web'
import type { PagesAPIRouteMatch } from './future/route-matches/pages-api-route-match'
import type { AppRouteRouteHandlerContext } from './future/route-modules/app-route/module'
import type { Server as HTTPServer } from 'http'
import type { MiddlewareMatcher } from '../build/analysis/get-page-static-info'
import type { TLSSocket } from 'tls'
import type { PathnameNormalizer } from './future/normalizers/request/pathname-normalizer'
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,
} from '../shared/lib/constants'
import { RedirectStatusCode } from '../client/components/redirect-status-code'
import { isDynamicRoute } from '../shared/lib/router/utils'
import { checkIsOnDemandRevalidate } from './api-utils'
import { setConfig } from '../shared/lib/runtime-config.external'
import { formatRevalidate, type Revalidate } from './lib/revalidate'
import { execOnce } from '../shared/lib/utils'
import { isBlockedPage } from './utils'
import { 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 escapePathDelimiters from '../shared/lib/router/utils/escape-path-delimiters'
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_DID_POSTPONE_HEADER,
NEXT_URL,
NEXT_ROUTER_STATE_TREE,
} from '../client/components/app-router-headers'
import type {
MatchOptions,
RouteMatcherManager,
} from './future/route-matcher-managers/route-matcher-manager'
import { LocaleRouteNormalizer } from './future/normalizers/locale-route-normalizer'
import { DefaultRouteMatcherManager } from './future/route-matcher-managers/default-route-matcher-manager'
import { AppPageRouteMatcherProvider } from './future/route-matcher-providers/app-page-route-matcher-provider'
import { AppRouteRouteMatcherProvider } from './future/route-matcher-providers/app-route-route-matcher-provider'
import { PagesAPIRouteMatcherProvider } from './future/route-matcher-providers/pages-api-route-matcher-provider'
import { PagesRouteMatcherProvider } from './future/route-matcher-providers/pages-route-matcher-provider'
import { ServerManifestLoader } from './future/route-matcher-providers/helpers/manifest-loaders/server-manifest-loader'
import { getTracer, SpanKind } from './lib/trace/tracer'
import { BaseServerSpan } from './lib/trace/constants'
import { I18NProvider } from './future/helpers/i18n-provider'
import { sendResponse } from './send-response'
import { handleInternalServerErrorResponse } from './future/route-modules/helpers/response-handlers'
import {
fromNodeOutgoingHttpHeaders,
toNodeOutgoingHttpHeaders,
} from './web/utils'
import {
CACHE_ONE_YEAR,
NEXT_CACHE_TAGS_HEADER,
NEXT_QUERY_PARAM_PREFIX,
} 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 { stripInternalHeaders } from './internal-utils'
import { RSCPathnameNormalizer } from './future/normalizers/request/rsc'
import { PostponedPathnameNormalizer } from './future/normalizers/request/postponed'
import { stripFlightHeaders } from './app-render/strip-flight-headers'
import {
isAppPageRouteModule,
isAppRouteRouteModule,
isPagesRouteModule,
} from './future/route-modules/checks'
import { PrefetchRSCPathnameNormalizer } from './future/normalizers/request/prefetch-rsc'
import { NextDataPathnameNormalizer } from './future/normalizers/request/next-data'
import { getIsServerAction } from './lib/server-action-request-meta'
import { isInterceptionRouteAppPath } from './future/helpers/interception-routes'
export type FindComponentsResult = {
components: LoadComponentsReturnType
query: NextParsedUrlQuery
}
export interface MiddlewareRoutingItem {
page: string
match: MiddlewareRouteMatch
matchers?: MiddlewareMatcher[]
}
export type RouteHandler = (
req: BaseNextRequest,
res: BaseNextResponse,
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
isNodeDebugging?: 'brk' | boolean
}
export type RenderOpts = PagesRenderOptsPartial & AppRenderOptsPartial
export type LoadedRenderOpts = RenderOpts & LoadComponentsReturnType
type BaseRenderOpts = RenderOpts & {
poweredByHeader: boolean
generateEtags: boolean
previewProps: __ApiPreviewProps
}
export interface BaseRequestHandler {
(
req: BaseNextRequest,
res: BaseNextResponse,
parsedUrl?: NextUrlWithParsedQuery | undefined
): Promise<void> | void
}
export type RequestContext = {
req: BaseNextRequest
res: BaseNextResponse
pathname: string
query: NextParsedUrlQuery
renderOpts: RenderOpts
}
export type FallbackMode = false | undefined | 'blocking' | 'static'
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
}
export type NextEnabledDirectories = {
readonly pages: boolean
readonly app: boolean
}
export default abstract class Server<ServerOptions extends Options = Options> {
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?: ClientReferenceManifest
protected interceptionRoutePatterns: RegExp[]
protected nextFontManifest?: NextFontManifest
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 abstract findPageComponents(params: {
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 getFontManifest(): FontManifest | undefined
protected abstract getPrerenderManifest(): PrerenderManifest
protected abstract getNextFontManifest(): NextFontManifest | undefined
protected abstract attachRequestMeta(
req: BaseNextRequest,
parsedUrl: NextUrlWithParsedQuery
): void
protected abstract getFallback(page: string): Promise<string>
protected abstract hasPage(pathname: string): Promise<boolean>
protected abstract sendRenderResult(
req: BaseNextRequest,
res: BaseNextResponse,
options: {
result: RenderResult
type: 'html' | 'json' | 'rsc'
generateEtags: boolean
poweredByHeader: boolean
revalidate?: Revalidate
}
): Promise<void>
protected abstract runApi(
req: BaseNextRequest,
res: BaseNextResponse,
query: ParsedUrlQuery,
match: PagesAPIRouteMatch
): Promise<boolean>
protected abstract renderHTML(
req: BaseNextRequest,
res: BaseNextResponse,
pathname: string,
query: NextParsedUrlQuery,
renderOpts: LoadedRenderOpts
): Promise<RenderResult>
protected abstract getPrefetchRsc(pathname: string): Promise<string | null>
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 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 postponed: PostponedPathnameNormalizer | undefined
readonly rsc: RSCPathnameNormalizer | undefined
readonly prefetchRSC: PrefetchRSCPathnameNormalizer | undefined
readonly data: NextDataPathnameNormalizer | undefined
}
public constructor(options: ServerOptions) {
const {
dir = '.',
quiet = false,
conf,
dev = false,
minimalMode = false,
customServer = true,
hostname,
port,
} = options
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.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.
postponed:
this.enabledDirectories.app &&
this.nextConfig.experimental.ppr &&
this.minimalMode
? new PostponedPathnameNormalizer()
: undefined,
rsc:
this.enabledDirectories.app && this.minimalMode
? new RSCPathnameNormalizer()
: undefined,
prefetchRSC:
this.enabledDirectories.app &&
this.nextConfig.experimental.ppr &&
this.minimalMode
? new PrefetchRSCPathnameNormalizer()
: 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.experimental.deploymentId || ''
}
this.renderOpts = {
supportsDynamicHTML: true,
trailingSlash: this.nextConfig.trailingSlash,
deploymentId: this.nextConfig.experimental.deploymentId,
strictNextHead: !!this.nextConfig.experimental.strictNextHead,
poweredByHeader: this.nextConfig.poweredByHeader,
canonicalBase: this.nextConfig.amp.canonicalBase || '',
buildId: this.buildId,
generateEtags,
previewProps: this.getPrerenderManifest().preview,
customServer: customServer === true ? true : undefined,
ampOptimizerConfig: this.nextConfig.experimental.amp?.optimizer,
basePath: this.nextConfig.basePath,
images: this.nextConfig.images,
optimizeFonts: this.nextConfig.optimizeFonts as FontConfig,
fontManifest:
(this.nextConfig.optimizeFonts as FontConfig) && !dev
? this.getFontManifest()
: undefined,
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,
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: {
ppr:
this.enabledDirectories.app &&
this.nextConfig.experimental.ppr === true,
missingSuspenseWithCSRBailout:
this.nextConfig.experimental.missingSuspenseWithCSRBailout === true,
},
}
// 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 = (req, _res, parsedUrl) => {
if (!parsedUrl.pathname) return false
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 {
// Otherwise just return without doing anything.
return false
}
// If we're here, this is a data request, as it didn't return and it matched
// either a RSC or a prefetch RSC request.
parsedUrl.query.__nextDataReq = '1'
if (req.url) {
const parsed = parseUrl(req.url)
parsed.pathname = parsedUrl.pathname
req.url = formatUrl(parsed)
}
return false
}
private handleNextDataRequest: RouteHandler = 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' &&
req.headers['x-middleware-invoke']
) {
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.
parsedUrl.query.__nextLocale = localePathResult.detectedLocale
parsedUrl.query.__nextDefaultLocale = defaultLocale
// If the locale is not detected from the path, we need to mark that
// it was not inferred from default.
if (!localePathResult.detectedLocale) {
delete parsedUrl.query.__nextInferredLocaleFromDefault
}
// If no locale was detected and we don't have middleware, we need
// to render a 404 page.
if (!localePathResult.detectedLocale && !middleware) {
parsedUrl.query.__nextLocale = defaultLocale
await this.render404(req, res, parsedUrl)
return true
}
}
parsedUrl.pathname = pathname
parsedUrl.query.__nextDataReq = '1'
return false
}
protected handleNextImageRequest: RouteHandler = () => false
protected handleCatchallRenderRequest: RouteHandler = () => false
protected handleCatchallMiddlewareRequest: RouteHandler = () => 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
}
public logError(err: Error): void {
if (this.quiet) return
Log.error(err)
}
public async handleRequest(
req: BaseNextRequest,
res: BaseNextResponse,
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
span.setAttributes({
'http.status_code': res.statusCode,
})
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 newName = `${method} ${route}`
span.setAttributes({
'next.route': route,
'http.route': route,
'next.span_name': newName,
})
span.updateName(newName)
}
})
)
})
}
private async handleRequestImpl(
req: BaseNextRequest,
res: BaseNextResponse,
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
const _res = (res as any).originalResponse || res
const origSetHeader = _res.setHeader.bind(_res)
_res.setHeader = (name: string, val: string | string[]) => {
// When renders /_error after page is failed,
// it could attempt to set headers after headers
if (_res.headersSent) {
return
}
if (name.toLowerCase() === 'set-cookie') {
const middlewareValue = getRequestMeta(req, 'middlewareCookie')
if (
!middlewareValue ||
!Array.isArray(val) ||
!val.every((item, idx) => item === middlewareValue[idx])
) {
val = [
// TODO: (wyattjoh) find out why this is called multiple times resulting in duplicate cookies being added
...new Set([
...(middlewareValue || []),
...(typeof val === 'string'
? [val]
: Array.isArray(val)
? val
: []),
]),
]
}
}
return origSetHeader(name, val)
}
const urlParts = (req.url || '').split('?', 1)
const urlNoQuery = urlParts[0]
// this normalizes repeated slashes in the path e.g. hello//world ->
// hello/world or backslashes to forward slashes, this does not
// handle trailing slash as that is handled the same as a next.config.js
// redirect
if (urlNoQuery?.match(/(\\|\/\/)/)) {
const cleanUrl = normalizeRepeatedSlashes(req.url!)
res.redirect(cleanUrl, 308).body(cleanUrl).send()
return
}
// Parse url if parsedUrl not provided
if (!parsedUrl || typeof parsedUrl !== 'object') {
if (!req.url) {
throw new Error('Invariant: url can not be undefined')
}
parsedUrl = parseUrl(req.url!, true)
}
if (!parsedUrl.pathname) {
throw new Error("Invariant: pathname can't be empty")
}
// Parse the querystring ourselves if the user doesn't handle querystring parsing
if (typeof parsedUrl.query === 'string') {
parsedUrl.query = Object.fromEntries(
new URLSearchParams(parsedUrl.query)
)
}
req.headers['x-forwarded-host'] ??= req.headers['host'] ?? this.hostname
req.headers['x-forwarded-port'] ??= this.port?.toString()
const { originalRequest } = req as NodeNextRequest
req.headers['x-forwarded-proto'] ??= (originalRequest.socket as TLSSocket)
?.encrypted
? 'https'
: 'http'
req.headers['x-forwarded-for'] ??= originalRequest.socket?.remoteAddress
// This should be done before any normalization of the pathname happens as
// it captures the initial URL.
this.attachRequestMeta(req, parsedUrl)
let finished: boolean = false
if (this.minimalMode && this.enabledDirectories.app) {
finished = await this.handleRSCRequest(req, res, parsedUrl)
if (finished) return
}
const domainLocale = this.i18nProvider?.detectDomainLocale(
getHostname(parsedUrl, req.headers)
)
const defaultLocale =
domainLocale?.defaultLocale || this.nextConfig.i18n?.defaultLocale
parsedUrl.query.__nextDefaultLocale = defaultLocale
const url = parseUrlUtil(req.url.replace(/^\/+/, '/'))
const pathnameInfo = getNextPathnameInfo(url.pathname, {
nextConfig: this.nextConfig,
i18nProvider: this.i18nProvider,
})
url.pathname = pathnameInfo.pathname
if (pathnameInfo.basePath) {
req.url = removePathPrefix(req.url!, this.nextConfig.basePath)
}
const useMatchedPathHeader =
this.minimalMode && typeof req.headers['x-matched-path'] === 'string'
// TODO: merge handling with x-invoke-path
if (useMatchedPathHeader) {
try {
if (this.enabledDirectories.app) {
// ensure /index path is normalized for prerender
// in minimal mode
if (req.url.match(/^\/index($|\?)/)) {
req.url = req.url.replace(/^\/index/, '/')
}
parsedUrl.pathname =
parsedUrl.pathname === '/index' ? '/' : parsedUrl.pathname
}
// x-matched-path is the source of truth, it tells what page
// should be rendered because we don't process rewrites in minimalMode
let { pathname: matchedPath } = new URL(
req.headers['x-matched-path'] as string,
'http://localhost'
)
const { pathname: urlPathname } = new URL(req.url, 'http://localhost')
// For ISR the URL is normalized to the prerenderPath so if
// it's a data request the URL path will be the data URL,
// basePath is already stripped by this point
if (this.normalizers.data?.match(urlPathname)) {
parsedUrl.query.__nextDataReq = '1'
}
// In minimal mode, if PPR is enabled, then we should check to see if
// the matched path is a postponed path, and if it is, handle it.
else if (
this.normalizers.postponed?.match(matchedPath) &&
req.method === 'POST'
) {
// Decode the postponed state from the request body, it will come as
// an array of buffers, so collect them and then concat them to form
// the string.
const body: Array<Buffer> = []
for await (const chunk of req.body) {
body.push(chunk)
}
const postponed = Buffer.concat(body).toString('utf8')
addRequestMeta(req, 'postponed', postponed)
}
matchedPath = this.normalize(matchedPath)
const normalizedUrlPath = this.stripNextDataPath(urlPathname)
// Perform locale detection and normalization.
const localeAnalysisResult = this.i18nProvider?.analyze(matchedPath, {
defaultLocale,
})
// The locale result will be defined even if the locale was not
// detected for the request because it will be inferred from the
// default locale.
if (localeAnalysisResult) {
parsedUrl.query.__nextLocale = localeAnalysisResult.detectedLocale
// If the detected locale was inferred from the default locale, we
// need to modify the metadata on the request to indicate that.
if (localeAnalysisResult.inferredFromDefault) {
parsedUrl.query.__nextInferredLocaleFromDefault = '1'
} else {
delete parsedUrl.query.__nextInferredLocaleFromDefault
}
}
// TODO: check if this is needed any more?
matchedPath = denormalizePagePath(matchedPath)
let srcPathname = matchedPath
let pageIsDynamic = isDynamicRoute(srcPathname)
if (!pageIsDynamic) {
const match = await this.matchers.match(srcPathname, {
i18n: localeAnalysisResult,
})
// Update the source pathname to the matched page's pathname.