forked from vercel/next.js
/
base-server.ts
2851 lines (2536 loc) · 90.5 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 { DomainLocale } from './config'
import type { FontManifest, FontConfig } from './font-utils'
import type { LoadComponentsReturnType } from './load-components'
import type { RouteMatchFn } from '../shared/lib/router/utils/route-matcher'
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 } from './request-meta'
import type { ParsedUrlQuery } from 'querystring'
import type { RenderOpts, RenderOptsPartial } from './render'
import type { ResponseCacheBase, ResponseCacheEntry } from './response-cache'
import type { UrlWithParsedQuery } from 'url'
import {
NormalizeError,
DecodeError,
normalizeRepeatedSlashes,
MissingStaticPage,
} from '../shared/lib/utils'
import type { PreviewData, ServerRuntime, SizeLimit } from 'next/types'
import type { PagesManifest } from '../build/webpack/plugins/pages-manifest-plugin'
import type { OutgoingHttpHeaders } from 'http2'
import type { BaseNextRequest, BaseNextResponse } from './base-http'
import type { PayloadOptions } from './send-payload'
import type { 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 { PagesRouteModule } from './future/route-modules/pages/module'
import type { AppPageRouteModule } from './future/route-modules/app-page/module'
import type { NodeNextRequest, NodeNextResponse } from './base-http/node'
import type { AppRouteRouteMatch } from './future/route-matches/app-route-route-match'
import type { RouteDefinition } from './future/route-definitions/route-definition'
import type { WebNextRequest, WebNextResponse } from './base-http/web'
import type { PagesAPIRouteMatch } from './future/route-matches/pages-api-route-match'
import { format as formatUrl, parse as parseUrl } from 'url'
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,
TEMPORARY_REDIRECT_STATUS,
} from '../shared/lib/constants'
import { isDynamicRoute } from '../shared/lib/router/utils'
import {
setLazyProp,
getCookieParser,
checkIsOnDemandRevalidate,
} from './api-utils'
import { setConfig } from '../shared/lib/runtime-config'
import { setRevalidateHeaders } from './send-payload/revalidate-headers'
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,
} from './request-meta'
import { ImageConfigComplete } from '../shared/lib/image-config'
import { removePathPrefix } from '../shared/lib/router/utils/remove-path-prefix'
import {
normalizeAppPath,
normalizeRscPath,
} 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 { MiddlewareMatcher } from '../build/analysis/get-page-static-info'
import {
RSC,
RSC_VARY_HEADER,
FLIGHT_PARAMETERS,
NEXT_RSC_UNION_QUERY,
} from '../client/components/app-router-headers'
import {
MatchOptions,
RouteMatcherManager,
} from './future/route-matcher-managers/route-matcher-manager'
import {
RouteHandlerManager,
type RouteHandlerManagerContext,
} from './future/route-handler-managers/route-handler-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 { RouteKind } from './future/route-kind'
import { handleInternalServerErrorResponse } from './future/route-modules/helpers/response-handlers'
import {
fromNodeOutgoingHttpHeaders,
toNodeOutgoingHttpHeaders,
} from './web/utils'
import { NEXT_QUERY_PARAM_PREFIX } from '../lib/constants'
import {
isRouteMatch,
parsedUrlQueryToParams,
type RouteMatch,
} from './future/route-matches/route-match'
import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path'
import { signalFromNodeResponse } from './web/spec-extension/adapters/next-request'
export type FindComponentsResult = {
components: LoadComponentsReturnType
query: NextParsedUrlQuery
}
export interface RoutingItem {
page: string
match: RouteMatchFn
re?: RegExp
}
export interface MiddlewareRoutingItem {
page: string
match: MiddlewareRouteMatch
matchers?: MiddlewareMatcher[]
}
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
/**
* 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?: import('http').Server
_routerWorker?: boolean
_renderWorker?: boolean
isNodeDebugging?: 'brk' | boolean
}
export interface BaseRequestHandler {
(
req: BaseNextRequest,
res: BaseNextResponse,
parsedUrl?: NextUrlWithParsedQuery | undefined
): Promise<void>
}
export type RequestContext = {
req: BaseNextRequest
res: BaseNextResponse
pathname: string
query: NextParsedUrlQuery
renderOpts: RenderOptsPartial
}
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
revalidateOptions?: any
}
export default abstract class Server<ServerOptions extends Options = Options> {
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 hasAppDir: boolean
protected readonly pagesManifest?: PagesManifest
protected readonly appPathsManifest?: PagesManifest
protected readonly buildId: string
protected readonly minimalMode: boolean
protected readonly renderOpts: {
deploymentId?: string
poweredByHeader: boolean
buildId: string
generateEtags: boolean
runtimeConfig?: { [key: string]: any }
assetPrefix?: string
canonicalBase: string
dev?: boolean
previewProps: __ApiPreviewProps
customServer?: boolean
ampOptimizerConfig?: { [key: string]: any }
basePath: string
optimizeFonts: FontConfig
images: ImageConfigComplete
fontManifest?: FontManifest
disableOptimizedLoading?: boolean
optimizeCss: any
nextConfigOutput: 'standalone' | 'export'
nextScriptWorkers: any
locale?: string
locales?: string[]
defaultLocale?: string
domainLocales?: DomainLocale[]
distDir: string
runtime?: ServerRuntime
serverComponents?: boolean
crossOrigin?: 'anonymous' | 'use-credentials' | '' | undefined
supportsDynamicHTML?: boolean
isBot?: boolean
clientReferenceManifest?: ClientReferenceManifest
serverActionsBodySizeLimit?: SizeLimit
serverActionsManifest?: any
nextFontManifest?: NextFontManifest
renderServerComponentData?: boolean
serverComponentProps?: any
largePageDataBytes?: number
appDirDevErrorLogger?: (err: any) => Promise<void>
strictNextHead: boolean
}
protected serverOptions: ServerOptions
private responseCache: ResponseCacheBase
protected appPathRoutes?: Record<string, string[]>
protected clientReferenceManifest?: ClientReferenceManifest
protected nextFontManifest?: NextFontManifest
public readonly hostname?: string
public readonly port?: number
protected abstract getPublicDir(): string
protected abstract getHasStaticDir(): boolean
protected abstract getHasAppDir(dev: boolean): boolean
protected abstract getPagesManifest(): PagesManifest | undefined
protected abstract getAppPathsManifest(): PagesManifest | undefined
protected abstract getBuildId(): string
protected abstract findPageComponents(params: {
pathname: string
query: NextParsedUrlQuery
params: Params
isAppPath: boolean
sriEnabled?: boolean
appPaths?: string[] | null
shouldEnsure: boolean
}): 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
options?: PayloadOptions
}
): 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: RenderOpts
): Promise<RenderResult>
protected abstract getIncrementalCache(options: {
requestHeaders: Record<string, undefined | string | string[]>
requestProtocol: 'http' | 'https'
}): 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 handlers: RouteHandlerManager
protected readonly i18nProvider?: I18NProvider
protected readonly localeNormalizer?: LocaleRouteNormalizer
protected readonly isRenderWorker?: boolean
public constructor(options: ServerOptions) {
const {
dir = '.',
quiet = false,
conf,
dev = false,
minimalMode = false,
customServer = true,
hostname,
port,
} = options
this.serverOptions = options
this.isRenderWorker = options._renderWorker
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
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.minimalMode = minimalMode || !!process.env.NEXT_PRIVATE_MINIMAL_MODE
this.hasAppDir =
!!this.nextConfig.experimental.appDir && this.getHasAppDir(dev)
const serverComponents = this.hasAppDir
this.nextFontManifest = this.getNextFontManifest()
if (process.env.NEXT_RUNTIME !== 'edge') {
if (this.nextConfig.experimental.deploymentId) {
process.env.NEXT_DEPLOYMENT_ID =
this.nextConfig.experimental.deploymentId
}
}
this.renderOpts = {
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,
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,
}
// Initialize next/config with the environment configuration
setConfig({
serverRuntimeConfig,
publicRuntimeConfig,
})
this.pagesManifest = this.getPagesManifest()
this.appPathsManifest = this.getAppPathsManifest()
this.appPathRoutes = this.getAppPathRoutes()
// Configure the routes.
const { matchers, handlers } = this.getRoutes()
this.matchers = matchers
this.handlers = handlers
// 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.
matchers.reload()
this.setAssetPrefix(assetPrefix)
this.responseCache = this.getResponseCache({ dev })
}
protected async normalizeNextData(
_req: BaseNextRequest,
_res: BaseNextResponse,
_parsedUrl: NextUrlWithParsedQuery
): Promise<{ finished: boolean }> {
return { finished: false }
}
protected async handleNextImageRequest(
_req: BaseNextRequest,
_res: BaseNextResponse,
_parsedUrl: NextUrlWithParsedQuery
): Promise<{ finished: boolean }> {
return { finished: false }
}
protected async handleCatchallRenderRequest(
_req: BaseNextRequest,
_res: BaseNextResponse,
_parsedUrl: NextUrlWithParsedQuery
): Promise<{ finished: boolean }> {
return { finished: false }
}
protected async handleCatchallMiddlewareRequest(
_req: BaseNextRequest,
_res: BaseNextResponse,
_parsedUrl: NextUrlWithParsedQuery
): Promise<{ finished: boolean }> {
return { finished: false }
}
protected getRoutes(): {
matchers: RouteMatcherManager
handlers: RouteHandlerManager
} {
// 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()
const handlers = new RouteHandlerManager()
// 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.hasAppDir) {
// Match app pages under `app/`.
matchers.push(
new AppPageRouteMatcherProvider(this.distDir, manifestLoader)
)
matchers.push(
new AppRouteRouteMatcherProvider(this.distDir, manifestLoader)
)
}
return { matchers, handlers }
}
public logError(err: Error): void {
if (this.quiet) return
console.error(err)
}
public async handleRequest(
req: BaseNextRequest,
res: BaseNextResponse,
parsedUrl?: NextUrlWithParsedQuery
): Promise<void> {
await this.prepare()
const method = req.method.toUpperCase()
return getTracer().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 = getTracer().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[]) => {
if (name.toLowerCase() === 'set-cookie') {
const middlewareValue = getRequestMeta(req, '_nextMiddlewareCookie')
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('?')
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
}
setLazyProp({ req: req as any }, 'cookies', getCookieParser(req.headers))
// Parse url if parsedUrl not provided
if (!parsedUrl || typeof parsedUrl !== 'object') {
parsedUrl = parseUrl(req.url!, true)
}
// 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)
)
}
// in minimal mode we detect RSC revalidate if the .rsc
// path is requested
if (this.minimalMode) {
if (req.url.endsWith('.rsc')) {
parsedUrl.query.__nextDataReq = '1'
} else if (req.headers['x-now-route-matches']) {
for (const param of FLIGHT_PARAMETERS) {
delete req.headers[param.toString().toLowerCase()]
}
}
}
req.url = normalizeRscPath(req.url, this.hasAppDir)
parsedUrl.pathname = normalizeRscPath(
parsedUrl.pathname || '',
this.hasAppDir
)
this.attachRequestMeta(req, parsedUrl)
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)
addRequestMeta(req, '_nextHadBasePath', true)
}
const useMatchedPathHeader =
this.minimalMode && typeof req.headers['x-matched-path'] === 'string'
// TODO: merge handling with x-invoke-path
if (useMatchedPathHeader) {
try {
if (this.hasAppDir) {
// 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 matchedPath = normalizeRscPath(
new URL(req.headers['x-matched-path'] as string, 'http://localhost')
.pathname,
this.hasAppDir
)
let urlPathname = new URL(req.url, 'http://localhost').pathname
// 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 (urlPathname.startsWith(`/_next/data/`)) {
parsedUrl.query.__nextDataReq = '1'
}
const normalizedUrlPath = this.stripNextDataPath(urlPathname)
matchedPath = this.stripNextDataPath(matchedPath, false)
// 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
const match = await this.matchers.match(matchedPath, {
i18n: localeAnalysisResult,
})
// Update the source pathname to the matched page's pathname.
if (match) srcPathname = match.definition.pathname
// The page is dynamic if the params are defined.
const pageIsDynamic = typeof match?.params !== 'undefined'
// The rest of this function can't handle i18n properly, so ensure we
// restore the pathname with the locale information stripped from it
// now that we're done matching if we're using i18n.
if (localeAnalysisResult) {
matchedPath = localeAnalysisResult.pathname
}
const utils = getUtils({
pageIsDynamic,
page: srcPathname,
i18n: this.nextConfig.i18n,
basePath: this.nextConfig.basePath,
rewrites: this.getRoutesManifest()?.rewrites || {
beforeFiles: [],
afterFiles: [],
fallback: [],
},
caseSensitive: !!this.nextConfig.experimental.caseSensitiveRoutes,
})
// Ensure parsedUrl.pathname includes locale before processing
// rewrites or they won't match correctly.
if (defaultLocale && !pathnameInfo.locale) {
parsedUrl.pathname = `/${defaultLocale}${parsedUrl.pathname}`
}
const pathnameBeforeRewrite = parsedUrl.pathname
const rewriteParams = utils.handleRewrites(req, parsedUrl)
const rewriteParamKeys = Object.keys(rewriteParams)
const didRewrite = pathnameBeforeRewrite !== parsedUrl.pathname
if (didRewrite) {
addRequestMeta(req, '_nextRewroteUrl', parsedUrl.pathname!)
addRequestMeta(req, '_nextDidRewrite', true)
}
const routeParamKeys = new Set<string>()
for (const key of Object.keys(parsedUrl.query)) {
const value = parsedUrl.query[key]
if (
key !== NEXT_QUERY_PARAM_PREFIX &&
key.startsWith(NEXT_QUERY_PARAM_PREFIX)
) {
const normalizedKey = key.substring(
NEXT_QUERY_PARAM_PREFIX.length
)
parsedUrl.query[normalizedKey] = value
routeParamKeys.add(normalizedKey)
delete parsedUrl.query[key]
}
}
// interpolate dynamic params and normalize URL if needed
if (pageIsDynamic) {
let params: ParsedUrlQuery | false = {}
let paramsResult = utils.normalizeDynamicRouteParams(
parsedUrl.query
)
// for prerendered ISR paths we attempt parsing the route
// params from the URL directly as route-matches may not
// contain the correct values due to the filesystem path
// matching before the dynamic route has been matched
if (
!paramsResult.hasValidParams &&
pageIsDynamic &&
!isDynamicRoute(normalizedUrlPath)
) {
let matcherParams = utils.dynamicRouteMatcher?.(normalizedUrlPath)
if (matcherParams) {
utils.normalizeDynamicRouteParams(matcherParams)
Object.assign(paramsResult.params, matcherParams)
paramsResult.hasValidParams = true
}
}
if (paramsResult.hasValidParams) {
params = paramsResult.params
}
if (
req.headers['x-now-route-matches'] &&
isDynamicRoute(matchedPath) &&
!paramsResult.hasValidParams
) {
const opts: Record<string, string> = {}
const routeParams = utils.getParamsFromRouteMatches(
req,
opts,
parsedUrl.query.__nextLocale || ''
)
// If this returns a locale, it means that the locale was detected
// from the pathname.
if (opts.locale) {
parsedUrl.query.__nextLocale = opts.locale
// As the locale was parsed from the pathname, we should mark
// that the locale was not inferred as the default.
delete parsedUrl.query.__nextInferredLocaleFromDefault
}
paramsResult = utils.normalizeDynamicRouteParams(
routeParams,
true
)
if (paramsResult.hasValidParams) {
params = paramsResult.params
}
}
// handle the actual dynamic route name being requested
if (
pageIsDynamic &&
utils.defaultRouteMatches &&
normalizedUrlPath === srcPathname &&
!paramsResult.hasValidParams &&
!utils.normalizeDynamicRouteParams({ ...params }, true)
.hasValidParams
) {
params = utils.defaultRouteMatches
}
if (params) {
matchedPath = utils.interpolateDynamicPath(srcPathname, params)
req.url = utils.interpolateDynamicPath(req.url!, params)
}
}
if (pageIsDynamic || didRewrite) {
utils.normalizeVercelUrl(req, true, [
...rewriteParamKeys,
...Object.keys(utils.defaultRouteRegex?.groups || {}),
])
}
for (const key of routeParamKeys) {
delete parsedUrl.query[key]
}
parsedUrl.pathname = matchedPath
url.pathname = parsedUrl.pathname
} catch (err) {
if (err instanceof DecodeError || err instanceof NormalizeError) {
res.statusCode = 400
return this.renderError(null, req, res, '/_error', {})
}
throw err
}
}
if (
// Edge runtime always has minimal mode enabled.
process.env.NEXT_RUNTIME !== 'edge' &&
!this.minimalMode &&
defaultLocale
) {
const { getLocaleRedirect } =
require('../shared/lib/i18n/get-locale-redirect') as typeof import('../shared/lib/i18n/get-locale-redirect')
const redirect = getLocaleRedirect({
defaultLocale,
domainLocale,
headers: req.headers,
nextConfig: this.nextConfig,
pathLocale: pathnameInfo.locale,
urlParsed: {
...url,
pathname: pathnameInfo.locale
? `/${pathnameInfo.locale}${url.pathname}`
: url.pathname,
},
})
if (redirect) {
return res
.redirect(redirect, TEMPORARY_REDIRECT_STATUS)
.body(redirect)
.send()
}
}
addRequestMeta(req, '__nextIsLocaleDomain', Boolean(domainLocale))
if (pathnameInfo.locale) {
req.url = formatUrl(url)
addRequestMeta(req, '__nextStrippedLocale', true)
}
// If we aren't in minimal mode or there is no locale in the query
// string, add the locale to the query string.
if (!this.minimalMode || !parsedUrl.query.__nextLocale) {
// If the locale is in the pathname, add it to the query string.
if (pathnameInfo.locale) {
parsedUrl.query.__nextLocale = pathnameInfo.locale
}
// If the default locale is available, add it to the query string and
// mark it as inferred rather than implicit.
else if (defaultLocale) {
parsedUrl.query.__nextLocale = defaultLocale
parsedUrl.query.__nextInferredLocaleFromDefault = '1'
}
}
// set incremental cache to request meta so it can
// be passed down for edge functions and the fetch disk
// cache can be leveraged locally