-
Notifications
You must be signed in to change notification settings - Fork 26.1k
/
next-server.ts
1958 lines (1722 loc) · 57.1 KB
/
next-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 './node-environment'
import './require-hook'
import './node-polyfill-crypto'
import type { CacheFs } from '../shared/lib/utils'
import {
DecodeError,
PageNotFoundError,
MiddlewareNotFoundError,
} from '../shared/lib/utils'
import type { MiddlewareManifest } from '../build/webpack/plugins/middleware-plugin'
import type RenderResult from './render-result'
import type { FetchEventResult } from './web/types'
import type { PrerenderManifest } from '../build'
import type { FetchMetric } from './base-http'
import type { PagesManifest } from '../build/webpack/plugins/pages-manifest-plugin'
import type { NextParsedUrlQuery, NextUrlWithParsedQuery } from './request-meta'
import type { Params } from '../shared/lib/router/utils/route-matcher'
import type { MiddlewareRouteMatch } from '../shared/lib/router/utils/middleware-route-matcher'
import type { RouteMatch } from './future/route-matches/route-match'
import type { IncomingMessage, ServerResponse } from 'http'
import type { PagesAPIRouteModule } from './future/route-modules/pages-api/module'
import type { UrlWithParsedQuery } from 'url'
import type { ParsedUrlQuery } from 'querystring'
import type { ParsedUrl } from '../shared/lib/router/utils/parse-url'
import type { Revalidate, SwrDelta } from './lib/revalidate'
import fs from 'fs'
import { join, resolve } from 'path'
import { getRouteMatcher } from '../shared/lib/router/utils/route-matcher'
import { addRequestMeta, getRequestMeta } from './request-meta'
import {
PAGES_MANIFEST,
BUILD_ID_FILE,
MIDDLEWARE_MANIFEST,
PRERENDER_MANIFEST,
ROUTES_MANIFEST,
CLIENT_PUBLIC_FILES_PATH,
APP_PATHS_MANIFEST,
SERVER_DIRECTORY,
NEXT_FONT_MANIFEST,
PHASE_PRODUCTION_BUILD,
UNDERSCORE_NOT_FOUND_ROUTE_ENTRY,
} from '../shared/lib/constants'
import { findDir } from '../lib/find-pages-dir'
import { NodeNextRequest, NodeNextResponse } from './base-http/node'
import { sendRenderResult } from './send-payload'
import { parseUrl } from '../shared/lib/router/utils/parse-url'
import * as Log from '../build/output/log'
import type {
Options,
FindComponentsResult,
MiddlewareRoutingItem,
RequestContext,
NormalizedRouteManifest,
LoadedRenderOpts,
RouteHandler,
NextEnabledDirectories,
BaseRequestHandler,
} from './base-server'
import BaseServer, { NoFallbackError, isRSCRequestCheck } from './base-server'
import { getMaybePagePath, getPagePath, requireFontManifest } from './require'
import { denormalizePagePath } from '../shared/lib/page-path/denormalize-page-path'
import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'
import { loadComponents } from './load-components'
import type { LoadComponentsReturnType } from './load-components'
import isError, { getProperError } from '../lib/is-error'
import type { FontManifest } from './font-utils'
import { splitCookiesString, toNodeOutgoingHttpHeaders } from './web/utils'
import { getMiddlewareRouteMatcher } from '../shared/lib/router/utils/middleware-route-matcher'
import { loadEnvConfig } from '@next/env'
import { urlQueryToSearchParams } from '../shared/lib/router/utils/querystring'
import { removeTrailingSlash } from '../shared/lib/router/utils/remove-trailing-slash'
import { getNextPathnameInfo } from '../shared/lib/router/utils/get-next-pathname-info'
import { getCloneableBody } from './body-streams'
import { checkIsOnDemandRevalidate } from './api-utils'
import ResponseCache from './response-cache'
import { IncrementalCache } from './lib/incremental-cache'
import { normalizeAppPath } from '../shared/lib/router/utils/app-paths'
import { setHttpClientAndAgentOptions } from './setup-http-agent-env'
import { isPagesAPIRouteMatch } from './future/route-matches/pages-api-route-match'
import type { PagesAPIRouteMatch } from './future/route-matches/pages-api-route-match'
import type { MatchOptions } from './future/route-matcher-managers/route-matcher-manager'
import {
INSTRUMENTATION_HOOK_FILENAME,
RSC_PREFETCH_SUFFIX,
} from '../lib/constants'
import { BubbledError, getTracer } from './lib/trace/tracer'
import { NextNodeServerSpan } from './lib/trace/constants'
import { nodeFs } from './lib/node-fs-methods'
import { getRouteRegex } from '../shared/lib/router/utils/route-regex'
import { pipeToNodeResponse } from './pipe-readable'
import { createRequestResponseMocks } from './lib/mock-request'
import { NEXT_RSC_UNION_QUERY } from '../client/components/app-router-headers'
import { signalFromNodeResponse } from './web/spec-extension/adapters/next-request'
import { RouteModuleLoader } from './future/helpers/module-loader/route-module-loader'
import { loadManifest } from './load-manifest'
import { lazyRenderAppPage } from './future/route-modules/app-page/module.render'
import { lazyRenderPagesPage } from './future/route-modules/pages/module.render'
import { interopDefault } from '../lib/interop-default'
import { formatDynamicImportPath } from '../lib/format-dynamic-import-path'
import type { NextFontManifest } from '../build/webpack/plugins/next-font-manifest-plugin'
import { isInterceptionRouteRewrite } from '../lib/generate-interception-routes-rewrites'
import { stripNextRscUnionQuery } from '../lib/url'
export * from './base-server'
declare const __non_webpack_require__: NodeRequire
// For module that can be both CJS or ESM
const dynamicImportEsmDefault = process.env.NEXT_MINIMAL
? (id: string) =>
import(/* webpackIgnore: true */ id).then((mod) => mod.default || mod)
: (id: string) => import(id).then((mod) => mod.default || mod)
// For module that will be compiled to CJS, e.g. instrument
const dynamicRequire = process.env.NEXT_MINIMAL
? __non_webpack_require__
: require
function writeStdoutLine(text: string) {
process.stdout.write(' ' + text + '\n')
}
function formatRequestUrl(url: string, maxLength: number | undefined) {
return maxLength !== undefined && url.length > maxLength
? url.substring(0, maxLength) + '..'
: url
}
export type NodeRequestHandler = BaseRequestHandler<
IncomingMessage | NodeNextRequest,
ServerResponse | NodeNextResponse
>
type NodeRouteHandler = RouteHandler<NodeNextRequest, NodeNextResponse>
const MiddlewareMatcherCache = new WeakMap<
MiddlewareManifest['middleware'][string],
MiddlewareRouteMatch
>()
function getMiddlewareMatcher(
info: MiddlewareManifest['middleware'][string]
): MiddlewareRouteMatch {
const stored = MiddlewareMatcherCache.get(info)
if (stored) {
return stored
}
if (!Array.isArray(info.matchers)) {
throw new Error(
`Invariant: invalid matchers for middleware ${JSON.stringify(info)}`
)
}
const matcher = getMiddlewareRouteMatcher(info.matchers)
MiddlewareMatcherCache.set(info, matcher)
return matcher
}
export default class NextNodeServer extends BaseServer<
Options,
NodeNextRequest,
NodeNextResponse
> {
protected middlewareManifestPath: string
private _serverDistDir: string | undefined
private imageResponseCache?: ResponseCache
protected renderWorkersPromises?: Promise<void>
protected dynamicRoutes?: {
match: import('../shared/lib/router/utils/route-matcher').RouteMatchFn
page: string
re: RegExp
}[]
private routerServerHandler?: (
req: IncomingMessage,
res: ServerResponse
) => void
constructor(options: Options) {
// Initialize super class
super(options)
/**
* This sets environment variable to be used at the time of SSR by head.tsx.
* Using this from process.env allows targeting SSR by calling
* `process.env.__NEXT_OPTIMIZE_CSS`.
*/
if (this.renderOpts.optimizeFonts) {
process.env.__NEXT_OPTIMIZE_FONTS = JSON.stringify(
this.renderOpts.optimizeFonts
)
}
if (this.renderOpts.optimizeCss) {
process.env.__NEXT_OPTIMIZE_CSS = JSON.stringify(true)
}
if (this.renderOpts.nextScriptWorkers) {
process.env.__NEXT_SCRIPT_WORKERS = JSON.stringify(true)
}
process.env.NEXT_DEPLOYMENT_ID = this.nextConfig.deploymentId || ''
if (!this.minimalMode) {
this.imageResponseCache = new ResponseCache(this.minimalMode)
}
const { appDocumentPreloading } = this.nextConfig.experimental
const isDefaultEnabled = typeof appDocumentPreloading === 'undefined'
if (
!options.dev &&
(appDocumentPreloading === true ||
!(this.minimalMode && isDefaultEnabled))
) {
// pre-warm _document and _app as these will be
// needed for most requests
loadComponents({
distDir: this.distDir,
page: '/_document',
isAppPath: false,
}).catch(() => {})
loadComponents({
distDir: this.distDir,
page: '/_app',
isAppPath: false,
}).catch(() => {})
}
if (!options.dev && this.nextConfig.experimental.preloadEntriesOnStart) {
this.unstable_preloadEntries()
}
if (!options.dev) {
const { dynamicRoutes = [] } = this.getRoutesManifest() ?? {}
this.dynamicRoutes = dynamicRoutes.map((r) => {
// TODO: can we just re-use the regex from the manifest?
const regex = getRouteRegex(r.page)
const match = getRouteMatcher(regex)
return {
match,
page: r.page,
re: regex.re,
}
})
}
// ensure options are set when loadConfig isn't called
setHttpClientAndAgentOptions(this.nextConfig)
// Intercept fetch and other testmode apis.
if (this.serverOptions.experimentalTestProxy) {
process.env.NEXT_PRIVATE_TEST_PROXY = 'true'
const {
interceptTestApis,
} = require('next/dist/experimental/testmode/server')
interceptTestApis()
}
this.middlewareManifestPath = join(this.serverDistDir, MIDDLEWARE_MANIFEST)
// This is just optimization to fire prepare as soon as possible. It will be
// properly awaited later. We add the catch here to ensure that it does not
// cause a unhandled promise rejection. The promise rejection will be
// handled later on via the `await` when the request handler is called.
if (!options.dev) {
this.prepare().catch((err) => {
console.error('Failed to prepare server', err)
})
}
}
public async unstable_preloadEntries(): Promise<void> {
const appPathsManifest = this.getAppPathsManifest()
const pagesManifest = this.getPagesManifest()
for (const page of Object.keys(pagesManifest || {})) {
await loadComponents({
distDir: this.distDir,
page,
isAppPath: false,
}).catch(() => {})
}
for (const page of Object.keys(appPathsManifest || {})) {
await loadComponents({ distDir: this.distDir, page, isAppPath: true })
.then(async ({ ComponentMod }) => {
const webpackRequire = ComponentMod.__next_app__.require
if (webpackRequire?.m) {
for (const id of Object.keys(webpackRequire.m)) {
await webpackRequire(id)
}
}
})
.catch(() => {})
}
}
protected async handleUpgrade(): Promise<void> {
// The web server does not support web sockets, it's only used for HMR in
// development.
}
protected async prepareImpl() {
await super.prepareImpl()
if (
!this.serverOptions.dev &&
this.nextConfig.experimental.instrumentationHook
) {
try {
const instrumentationHook = await dynamicRequire(
resolve(
this.serverOptions.dir || '.',
this.serverOptions.conf.distDir!,
'server',
INSTRUMENTATION_HOOK_FILENAME
)
)
await instrumentationHook.register?.()
} catch (err: any) {
if (err.code !== 'MODULE_NOT_FOUND') {
err.message = `An error occurred while loading instrumentation hook: ${err.message}`
throw err
}
}
}
}
protected loadEnvConfig({
dev,
forceReload,
silent,
}: {
dev: boolean
forceReload?: boolean
silent?: boolean
}) {
loadEnvConfig(
this.dir,
dev,
silent ? { info: () => {}, error: () => {} } : Log,
forceReload
)
}
protected async getIncrementalCache({
requestHeaders,
requestProtocol,
}: {
requestHeaders: IncrementalCache['requestHeaders']
requestProtocol: 'http' | 'https'
}) {
const dev = !!this.renderOpts.dev
let CacheHandler: any
const { cacheHandler } = this.nextConfig
if (cacheHandler) {
CacheHandler = interopDefault(
await dynamicImportEsmDefault(
formatDynamicImportPath(this.distDir, cacheHandler)
)
)
}
// incremental-cache is request specific
// although can have shared caches in module scope
// per-cache handler
return new IncrementalCache({
fs: this.getCacheFilesystem(),
dev,
requestHeaders,
requestProtocol,
pagesDir: this.enabledDirectories.pages,
appDir: this.enabledDirectories.app,
allowedRevalidateHeaderKeys:
this.nextConfig.experimental.allowedRevalidateHeaderKeys,
minimalMode: this.minimalMode,
serverDistDir: this.serverDistDir,
fetchCache: true,
fetchCacheKeyPrefix: this.nextConfig.experimental.fetchCacheKeyPrefix,
maxMemoryCacheSize: this.nextConfig.cacheMaxMemorySize,
flushToDisk:
!this.minimalMode && this.nextConfig.experimental.isrFlushToDisk,
getPrerenderManifest: () => this.getPrerenderManifest(),
CurCacheHandler: CacheHandler,
experimental: this.renderOpts.experimental,
})
}
protected getResponseCache() {
return new ResponseCache(this.minimalMode)
}
protected getPublicDir(): string {
return join(this.dir, CLIENT_PUBLIC_FILES_PATH)
}
protected getHasStaticDir(): boolean {
return fs.existsSync(join(this.dir, 'static'))
}
protected getPagesManifest(): PagesManifest | undefined {
return loadManifest(
join(this.serverDistDir, PAGES_MANIFEST)
) as PagesManifest
}
protected getAppPathsManifest(): PagesManifest | undefined {
if (!this.enabledDirectories.app) return undefined
return loadManifest(
join(this.serverDistDir, APP_PATHS_MANIFEST)
) as PagesManifest
}
protected getinterceptionRoutePatterns(): RegExp[] {
if (!this.enabledDirectories.app) return []
const routesManifest = this.getRoutesManifest()
return (
routesManifest?.rewrites.beforeFiles
.filter(isInterceptionRouteRewrite)
.map((rewrite) => new RegExp(rewrite.regex)) ?? []
)
}
protected async hasPage(pathname: string): Promise<boolean> {
return !!getMaybePagePath(
pathname,
this.distDir,
this.nextConfig.i18n?.locales,
this.enabledDirectories.app
)
}
protected getBuildId(): string {
const buildIdFile = join(this.distDir, BUILD_ID_FILE)
try {
return fs.readFileSync(buildIdFile, 'utf8').trim()
} catch (err: any) {
if (err.code === 'ENOENT') {
throw new Error(
`Could not find a production build in the '${this.distDir}' directory. Try building your app with 'next build' before starting the production server. https://nextjs.org/docs/messages/production-start-no-build-id`
)
}
throw err
}
}
protected getEnabledDirectories(dev: boolean): NextEnabledDirectories {
const dir = dev ? this.dir : this.serverDistDir
return {
app: findDir(dir, 'app') ? true : false,
pages: findDir(dir, 'pages') ? true : false,
}
}
protected sendRenderResult(
req: NodeNextRequest,
res: NodeNextResponse,
options: {
result: RenderResult
type: 'html' | 'json' | 'rsc'
generateEtags: boolean
poweredByHeader: boolean
revalidate?: Revalidate | undefined
swrDelta?: SwrDelta | undefined
}
): Promise<void> {
return sendRenderResult({
req: req.originalRequest,
res: res.originalResponse,
result: options.result,
type: options.type,
generateEtags: options.generateEtags,
poweredByHeader: options.poweredByHeader,
revalidate: options.revalidate,
swrDelta: options.swrDelta,
})
}
protected async runApi(
req: NodeNextRequest,
res: NodeNextResponse,
query: ParsedUrlQuery,
match: PagesAPIRouteMatch
): Promise<boolean> {
const edgeFunctionsPages = this.getEdgeFunctionsPages()
for (const edgeFunctionsPage of edgeFunctionsPages) {
if (edgeFunctionsPage === match.definition.pathname) {
const handledAsEdgeFunction = await this.runEdgeFunction({
req,
res,
query,
params: match.params,
page: match.definition.pathname,
appPaths: null,
})
if (handledAsEdgeFunction) {
return true
}
}
}
// The module supports minimal mode, load the minimal module.
const module = await RouteModuleLoader.load<PagesAPIRouteModule>(
match.definition.filename
)
query = { ...query, ...match.params }
delete query.__nextLocale
delete query.__nextDefaultLocale
delete query.__nextInferredLocaleFromDefault
await module.render(req.originalRequest, res.originalResponse, {
previewProps: this.renderOpts.previewProps,
revalidate: this.revalidate.bind(this),
trustHostHeader: this.nextConfig.experimental.trustHostHeader,
allowedRevalidateHeaderKeys:
this.nextConfig.experimental.allowedRevalidateHeaderKeys,
hostname: this.fetchHostname,
minimalMode: this.minimalMode,
dev: this.renderOpts.dev === true,
query,
params: match.params,
page: match.definition.pathname,
})
return true
}
protected async renderHTML(
req: NodeNextRequest,
res: NodeNextResponse,
pathname: string,
query: NextParsedUrlQuery,
renderOpts: LoadedRenderOpts
): Promise<RenderResult> {
return getTracer().trace(NextNodeServerSpan.renderHTML, async () =>
this.renderHTMLImpl(req, res, pathname, query, renderOpts)
)
}
private async renderHTMLImpl(
req: NodeNextRequest,
res: NodeNextResponse,
pathname: string,
query: NextParsedUrlQuery,
renderOpts: LoadedRenderOpts
): Promise<RenderResult> {
if (process.env.NEXT_MINIMAL) {
throw new Error(
'Invariant: renderHTML should not be called in minimal mode'
)
// the `else` branch is needed for tree-shaking
} else {
// Due to the way we pass data by mutating `renderOpts`, we can't extend the
// object here but only updating its `nextFontManifest` field.
// https://github.com/vercel/next.js/blob/df7cbd904c3bd85f399d1ce90680c0ecf92d2752/packages/next/server/render.tsx#L947-L952
renderOpts.nextFontManifest = this.nextFontManifest
if (this.enabledDirectories.app && renderOpts.isAppPath) {
return lazyRenderAppPage(req, res, pathname, query, renderOpts)
}
// TODO: re-enable this once we've refactored to use implicit matches
// throw new Error('Invariant: render should have used routeModule')
return lazyRenderPagesPage(
req.originalRequest,
res.originalResponse,
pathname,
query,
renderOpts
)
}
}
protected async imageOptimizer(
req: NodeNextRequest,
res: NodeNextResponse,
paramsResult: import('./image-optimizer').ImageParamsResult
): Promise<{ buffer: Buffer; contentType: string; maxAge: number }> {
if (process.env.NEXT_MINIMAL) {
throw new Error(
'invariant: imageOptimizer should not be called in minimal mode'
)
} else {
const { imageOptimizer, fetchExternalImage, fetchInternalImage } =
require('./image-optimizer') as typeof import('./image-optimizer')
const handleInternalReq = async (
newReq: IncomingMessage,
newRes: ServerResponse
) => {
if (newReq.url === req.url) {
throw new Error(`Invariant attempted to optimize _next/image itself`)
}
if (!this.routerServerHandler) {
throw new Error(`Invariant missing routerServerHandler`)
}
await this.routerServerHandler(newReq, newRes)
return
}
const { isAbsolute, href } = paramsResult
const imageUpstream = isAbsolute
? await fetchExternalImage(href)
: await fetchInternalImage(
href,
req.originalRequest,
res.originalResponse,
handleInternalReq
)
return imageOptimizer(
imageUpstream,
paramsResult,
this.nextConfig,
this.renderOpts.dev
)
}
}
protected getPagePath(pathname: string, locales?: string[]): string {
return getPagePath(
pathname,
this.distDir,
locales,
this.enabledDirectories.app
)
}
protected async renderPageComponent(
ctx: RequestContext<NodeNextRequest, NodeNextResponse>,
bubbleNoFallback: boolean
) {
const edgeFunctionsPages = this.getEdgeFunctionsPages() || []
if (edgeFunctionsPages.length) {
const appPaths = this.getOriginalAppPaths(ctx.pathname)
const isAppPath = Array.isArray(appPaths)
let page = ctx.pathname
if (isAppPath) {
// When it's an array, we need to pass all parallel routes to the loader.
page = appPaths[0]
}
for (const edgeFunctionsPage of edgeFunctionsPages) {
if (edgeFunctionsPage === page) {
await this.runEdgeFunction({
req: ctx.req,
res: ctx.res,
query: ctx.query,
params: ctx.renderOpts.params,
page,
appPaths,
})
return null
}
}
}
return super.renderPageComponent(ctx, bubbleNoFallback)
}
protected async findPageComponents({
page,
query,
params,
isAppPath,
url,
}: {
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> {
return getTracer().trace(
NextNodeServerSpan.findPageComponents,
{
spanName: 'resolve page components',
attributes: {
'next.route': isAppPath ? normalizeAppPath(page) : page,
},
},
() =>
this.findPageComponentsImpl({
page,
query,
params,
isAppPath,
url,
})
)
}
private async findPageComponentsImpl({
page,
query,
params,
isAppPath,
url: _url,
}: {
page: string
query: NextParsedUrlQuery
params: Params
isAppPath: boolean
url?: string
}): Promise<FindComponentsResult | null> {
const pagePaths: string[] = [page]
if (query.amp) {
// try serving a static AMP version first
pagePaths.unshift(
(isAppPath ? normalizeAppPath(page) : normalizePagePath(page)) + '.amp'
)
}
if (query.__nextLocale) {
pagePaths.unshift(
...pagePaths.map(
(path) => `/${query.__nextLocale}${path === '/' ? '' : path}`
)
)
}
for (const pagePath of pagePaths) {
try {
const components = await loadComponents({
distDir: this.distDir,
page: pagePath,
isAppPath,
})
if (
query.__nextLocale &&
typeof components.Component === 'string' &&
!pagePath.startsWith(`/${query.__nextLocale}`)
) {
// if loading an static HTML file the locale is required
// to be present since all HTML files are output under their locale
continue
}
return {
components,
query: {
...(!this.renderOpts.isExperimentalCompile &&
components.getStaticProps
? ({
amp: query.amp,
__nextDataReq: query.__nextDataReq,
__nextLocale: query.__nextLocale,
__nextDefaultLocale: query.__nextDefaultLocale,
} as NextParsedUrlQuery)
: query),
// For appDir params is excluded.
...((isAppPath ? {} : params) || {}),
},
}
} catch (err) {
// we should only not throw if we failed to find the page
// in the pages-manifest
if (!(err instanceof PageNotFoundError)) {
throw err
}
}
}
return null
}
protected getFontManifest(): FontManifest {
return requireFontManifest(this.distDir)
}
protected getNextFontManifest(): NextFontManifest | undefined {
return loadManifest(
join(this.distDir, 'server', NEXT_FONT_MANIFEST + '.json')
) as NextFontManifest
}
protected getFallback(page: string): Promise<string> {
page = normalizePagePath(page)
const cacheFs = this.getCacheFilesystem()
return cacheFs.readFile(
join(this.serverDistDir, 'pages', `${page}.html`),
'utf8'
)
}
protected handleNextImageRequest: NodeRouteHandler = async (
req,
res,
parsedUrl
) => {
if (!parsedUrl.pathname || !parsedUrl.pathname.startsWith('/_next/image')) {
return false
}
if (
this.minimalMode ||
this.nextConfig.output === 'export' ||
process.env.NEXT_MINIMAL
) {
res.statusCode = 400
res.body('Bad Request').send()
return true
// the `else` branch is needed for tree-shaking
} else {
const { ImageOptimizerCache } =
require('./image-optimizer') as typeof import('./image-optimizer')
const imageOptimizerCache = new ImageOptimizerCache({
distDir: this.distDir,
nextConfig: this.nextConfig,
})
const { getHash, sendResponse, ImageError } =
require('./image-optimizer') as typeof import('./image-optimizer')
if (!this.imageResponseCache) {
throw new Error('invariant image optimizer cache was not initialized')
}
const imagesConfig = this.nextConfig.images
if (imagesConfig.loader !== 'default' || imagesConfig.unoptimized) {
await this.render404(req, res)
return true
}
const paramsResult = ImageOptimizerCache.validateParams(
req.originalRequest,
parsedUrl.query,
this.nextConfig,
!!this.renderOpts.dev
)
if ('errorMessage' in paramsResult) {
res.statusCode = 400
res.body(paramsResult.errorMessage).send()
return true
}
const cacheKey = ImageOptimizerCache.getCacheKey(paramsResult)
try {
const { getExtension } =
require('./serve-static') as typeof import('./serve-static')
const cacheEntry = await this.imageResponseCache.get(
cacheKey,
async () => {
const { buffer, contentType, maxAge } = await this.imageOptimizer(
req,
res,
paramsResult
)
const etag = getHash([buffer])
return {
value: {
kind: 'IMAGE',
buffer,
etag,
extension: getExtension(contentType) as string,
},
revalidate: maxAge,
}
},
{
incrementalCache: imageOptimizerCache,
}
)
if (cacheEntry?.value?.kind !== 'IMAGE') {
throw new Error(
'invariant did not get entry from image response cache'
)
}
sendResponse(
req.originalRequest,
res.originalResponse,
paramsResult.href,
cacheEntry.value.extension,
cacheEntry.value.buffer,
paramsResult.isStatic,
cacheEntry.isMiss ? 'MISS' : cacheEntry.isStale ? 'STALE' : 'HIT',
imagesConfig,
cacheEntry.revalidate || 0,
Boolean(this.renderOpts.dev)
)
return true
} catch (err) {
if (err instanceof ImageError) {
res.statusCode = err.statusCode
res.body(err.message).send()
return true
}
throw err
}
}
}
protected handleCatchallRenderRequest: NodeRouteHandler = async (
req,
res,
parsedUrl
) => {
let { pathname, query } = parsedUrl
if (!pathname) {
throw new Error('Invariant: pathname is undefined')
}
// This is a catch-all route, there should be no fallbacks so mark it as
// such.
query._nextBubbleNoFallback = '1'
try {
// next.js core assumes page path without trailing slash
pathname = removeTrailingSlash(pathname)
const options: MatchOptions = {
i18n: this.i18nProvider?.fromQuery(pathname, query),
}
const match = await this.matchers.match(pathname, options)
// If we don't have a match, try to render it anyways.
if (!match) {
await this.render(req, res, pathname, query, parsedUrl, true)
return true
}
// Add the match to the request so we don't have to re-run the matcher
// for the same request.
addRequestMeta(req, 'match', match)
// TODO-APP: move this to a route handler
const edgeFunctionsPages = this.getEdgeFunctionsPages()
for (const edgeFunctionsPage of edgeFunctionsPages) {
// If the page doesn't match the edge function page, skip it.
if (edgeFunctionsPage !== match.definition.page) continue
if (this.nextConfig.output === 'export') {
await this.render404(req, res, parsedUrl)
return true
}
delete query._nextBubbleNoFallback
delete query[NEXT_RSC_UNION_QUERY]
const handled = await this.runEdgeFunction({
req,
res,
query,
params: match.params,
page: match.definition.page,
match,
appPaths: null,
})
// If we handled the request, we can return early.
if (handled) return true
}
// If the route was detected as being a Pages API route, then handle
// it.
// TODO: move this behavior into a route handler.
if (isPagesAPIRouteMatch(match)) {
if (this.nextConfig.output === 'export') {
await this.render404(req, res, parsedUrl)
return true
}
delete query._nextBubbleNoFallback
const handled = await this.handleApiRequest(req, res, query, match)
if (handled) return true
}
await this.render(req, res, pathname, query, parsedUrl, true)
return true