-
Notifications
You must be signed in to change notification settings - Fork 26.7k
/
page-handler.ts
496 lines (444 loc) · 14.7 KB
/
page-handler.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
import { IncomingMessage, ServerResponse } from 'http'
import { parse as parseUrl, format as formatUrl, UrlWithParsedQuery } from 'url'
import { DecodeError, isResSent } from '../../../../shared/lib/utils'
import { sendRenderResult } from '../../../../server/send-payload'
import { getUtils, vercelHeader, ServerlessHandlerCtx } from './utils'
import { renderToHTML } from '../../../../server/render'
import { tryGetPreviewData } from '../../../../server/api-utils/node'
import { denormalizePagePath } from '../../../../shared/lib/page-path/denormalize-page-path'
import { setLazyProp, getCookieParser } from '../../../../server/api-utils'
import { getRedirectStatus } from '../../../../lib/load-custom-routes'
import getRouteNoAssetPath from '../../../../shared/lib/router/utils/get-route-from-asset-path'
import { PERMANENT_REDIRECT_STATUS } from '../../../../shared/lib/constants'
import RenderResult from '../../../../server/render-result'
import isError from '../../../../lib/is-error'
export function getPageHandler(ctx: ServerlessHandlerCtx) {
const {
page,
pageComponent,
pageConfig,
pageGetStaticProps,
pageGetStaticPaths,
pageGetServerSideProps,
appModule,
documentModule,
errorModule,
notFoundModule,
encodedPreviewProps,
pageIsDynamic,
generateEtags,
poweredByHeader,
runtimeConfig,
buildManifest,
reactLoadableManifest,
i18n,
buildId,
basePath,
assetPrefix,
canonicalBase,
escapedBuildId,
} = ctx
const {
handleLocale,
handleRewrites,
handleBasePath,
defaultRouteRegex,
dynamicRouteMatcher,
interpolateDynamicPath,
getParamsFromRouteMatches,
normalizeDynamicRouteParams,
normalizeVercelUrl,
} = getUtils(ctx)
async function renderReqToHTML(
req: IncomingMessage,
res: ServerResponse,
renderMode?: 'export' | 'passthrough' | true,
_renderOpts?: any,
_params?: any
) {
let Component
let App
let config
let Document
let Error
let notFoundMod
let getStaticProps
let getStaticPaths
let getServerSideProps
;[
getStaticProps,
getServerSideProps,
getStaticPaths,
Component,
App,
config,
{ default: Document },
{ default: Error },
notFoundMod,
] = await Promise.all([
pageGetStaticProps,
pageGetServerSideProps,
pageGetStaticPaths,
pageComponent,
appModule,
pageConfig,
documentModule,
errorModule,
notFoundModule,
])
const fromExport = renderMode === 'export' || renderMode === true
const nextStartMode = renderMode === 'passthrough'
let hasValidParams = true
setLazyProp({ req: req as any }, 'cookies', getCookieParser(req.headers))
const options = {
App,
Document,
ComponentMod: { default: Component },
buildManifest,
getStaticProps,
getServerSideProps,
getStaticPaths,
reactLoadableManifest,
canonicalBase,
buildId,
assetPrefix,
runtimeConfig: (runtimeConfig || {}).publicRuntimeConfig || {},
previewProps: encodedPreviewProps,
env: process.env,
basePath,
supportsDynamicHTML: false, // Serverless target doesn't support streaming
..._renderOpts,
}
let _nextData = false
let defaultLocale = i18n?.defaultLocale
let detectedLocale = i18n?.defaultLocale
let parsedUrl: UrlWithParsedQuery
try {
// We need to trust the dynamic route params from the proxy
// to ensure we are using the correct values
const trustQuery = !getStaticProps && req.headers[vercelHeader]
parsedUrl = parseUrl(req.url!, true)
let routeNoAssetPath = parsedUrl.pathname!
if (basePath) {
routeNoAssetPath =
routeNoAssetPath.replace(new RegExp(`^${basePath}`), '') || '/'
}
const origQuery = Object.assign({}, parsedUrl.query)
handleRewrites(req, parsedUrl)
handleBasePath(req, parsedUrl)
// remove ?amp=1 from request URL if rendering for export
if (fromExport && parsedUrl.query.amp) {
const queryNoAmp = Object.assign({}, origQuery)
delete queryNoAmp.amp
req.url = formatUrl({
...parsedUrl,
search: undefined,
query: queryNoAmp,
})
}
if (parsedUrl.pathname!.match(/_next\/data/)) {
_nextData = page !== '/_error'
parsedUrl.pathname = getRouteNoAssetPath(
parsedUrl.pathname!.replace(
new RegExp(`/_next/data/${escapedBuildId}/`),
'/'
),
'.json'
)
routeNoAssetPath = parsedUrl.pathname
}
const localeResult = handleLocale(
req,
res,
parsedUrl,
routeNoAssetPath,
fromExport || nextStartMode
)
defaultLocale = localeResult?.defaultLocale || defaultLocale
detectedLocale = localeResult?.detectedLocale || detectedLocale
routeNoAssetPath = localeResult?.routeNoAssetPath || routeNoAssetPath
if (parsedUrl.query.nextInternalLocale) {
detectedLocale = parsedUrl.query.nextInternalLocale as string
delete parsedUrl.query.nextInternalLocale
}
const renderOpts = Object.assign(
{
Component,
pageConfig: config,
nextExport: fromExport,
isDataReq: _nextData,
locales: i18n?.locales,
locale: detectedLocale,
defaultLocale,
domainLocales: i18n?.domains,
optimizeCss: process.env.__NEXT_OPTIMIZE_CSS,
nextScriptWorkers: process.env.__NEXT_SCRIPT_WORKERS,
crossOrigin: process.env.__NEXT_CROSS_ORIGIN,
},
options
)
if (page === '/_error' && !res.statusCode) {
res.statusCode = 404
}
let params = {}
if (!fromExport && pageIsDynamic) {
const result = normalizeDynamicRouteParams(
trustQuery
? parsedUrl.query
: (dynamicRouteMatcher!(parsedUrl.pathname) as Record<
string,
string | string[]
>)
)
hasValidParams = result.hasValidParams
params = result.params
}
let nowParams = null
if (
pageIsDynamic &&
!hasValidParams &&
req.headers?.['x-now-route-matches']
) {
nowParams = getParamsFromRouteMatches(req, renderOpts, detectedLocale)
}
// make sure to set renderOpts to the correct params e.g. _params
// if provided from worker or params if we're parsing them here
renderOpts.params = _params || params
normalizeVercelUrl(req, !!trustQuery)
// normalize request URL/asPath for fallback/revalidate pages since the
// proxy sets the request URL to the output's path for fallback pages
if (pageIsDynamic && nowParams && defaultRouteRegex) {
const _parsedUrl = parseUrl(req.url!)
_parsedUrl.pathname = interpolateDynamicPath(
_parsedUrl.pathname!,
nowParams
)
parsedUrl.pathname = _parsedUrl.pathname
req.url = formatUrl(_parsedUrl)
}
// make sure to normalize asPath for revalidate and _next/data requests
// since the asPath should match what is shown on the client
if (!fromExport && (getStaticProps || getServerSideProps)) {
// don't include dynamic route params in query while normalizing
// asPath
if (pageIsDynamic && defaultRouteRegex) {
delete (parsedUrl as any).search
for (const param of Object.keys(defaultRouteRegex.groups)) {
delete origQuery[param]
}
}
parsedUrl.pathname = denormalizePagePath(parsedUrl.pathname!)
renderOpts.resolvedUrl = formatUrl({
...parsedUrl,
query: origQuery,
})
// For getServerSideProps we need to ensure we use the original URL
// and not the resolved URL to prevent a hydration mismatch on asPath
renderOpts.resolvedAsPath = getServerSideProps
? formatUrl({
...parsedUrl,
pathname: routeNoAssetPath,
query: origQuery,
})
: renderOpts.resolvedUrl
}
const isFallback = parsedUrl.query.__nextFallback
const previewData = tryGetPreviewData(req, res, options.previewProps)
const isPreviewMode = previewData !== false
if (process.env.__NEXT_OPTIMIZE_FONTS) {
renderOpts.optimizeFonts = true
/**
* __webpack_require__.__NEXT_FONT_MANIFEST__ is added by
* font-stylesheet-gathering-plugin
*/
// @ts-ignore
renderOpts.fontManifest = __webpack_require__.__NEXT_FONT_MANIFEST__
}
let result = await renderToHTML(
req,
res,
page,
Object.assign(
{},
getStaticProps
? { ...(parsedUrl.query.amp ? { amp: '1' } : {}) }
: parsedUrl.query,
nowParams ? nowParams : params,
_params,
isFallback ? { __nextFallback: 'true' } : {}
),
renderOpts
)
if (!renderMode) {
if (_nextData || getStaticProps || getServerSideProps) {
if (renderOpts.isNotFound) {
res.statusCode = 404
if (_nextData) {
res.end('{"notFound":true}')
return null
}
const NotFoundComponent = notFoundMod ? notFoundMod.default : Error
const errPathname = notFoundMod ? '/404' : '/_error'
const result2 = await renderToHTML(
req,
res,
errPathname,
parsedUrl.query,
Object.assign({}, options, {
getStaticProps: notFoundMod
? notFoundMod.getStaticProps
: undefined,
getStaticPaths: undefined,
getServerSideProps: undefined,
Component: NotFoundComponent,
err: undefined,
locale: detectedLocale,
locales: i18n?.locales,
defaultLocale: i18n?.defaultLocale,
})
)
sendRenderResult({
req,
res,
result: result2 ?? RenderResult.empty,
type: 'html',
generateEtags,
poweredByHeader,
options: {
private: isPreviewMode || page === '/404',
stateful: !!getServerSideProps,
revalidate: renderOpts.revalidate,
},
})
return null
} else if (renderOpts.isRedirect && !_nextData) {
const redirect = {
destination: renderOpts.pageData.pageProps.__N_REDIRECT,
statusCode: renderOpts.pageData.pageProps.__N_REDIRECT_STATUS,
basePath: renderOpts.pageData.pageProps.__N_REDIRECT_BASE_PATH,
}
const statusCode = getRedirectStatus(redirect)
if (
basePath &&
redirect.basePath !== false &&
redirect.destination.startsWith('/')
) {
redirect.destination = `${basePath}${redirect.destination}`
}
if (statusCode === PERMANENT_REDIRECT_STATUS) {
res.setHeader('Refresh', `0;url=${redirect.destination}`)
}
res.statusCode = statusCode
res.setHeader('Location', redirect.destination)
res.end(redirect.destination)
return null
} else {
sendRenderResult({
req,
res,
result: _nextData
? RenderResult.fromStatic(JSON.stringify(renderOpts.pageData))
: result ?? RenderResult.empty,
type: _nextData ? 'json' : 'html',
generateEtags,
poweredByHeader,
options: {
private: isPreviewMode || renderOpts.is404Page,
stateful: !!getServerSideProps,
revalidate: renderOpts.revalidate,
},
})
return null
}
}
} else if (isPreviewMode) {
res.setHeader(
'Cache-Control',
'private, no-cache, no-store, max-age=0, must-revalidate'
)
}
if (renderMode) return { html: result, renderOpts }
return result ? result.toUnchunkedString() : null
} catch (err) {
if (!parsedUrl!) {
parsedUrl = parseUrl(req.url!, true)
}
if (isError(err) && err.code === 'ENOENT') {
res.statusCode = 404
} else if (err instanceof DecodeError) {
res.statusCode = 400
} else {
console.error('Unhandled error during request:', err)
// Backwards compat (call getInitialProps in custom error):
try {
await renderToHTML(
req,
res,
'/_error',
parsedUrl!.query,
Object.assign({}, options, {
getStaticProps: undefined,
getStaticPaths: undefined,
getServerSideProps: undefined,
Component: Error,
err: err,
// Short-circuit rendering:
isDataReq: true,
})
)
} catch (underErrorErr) {
console.error(
'Failed call /_error subroutine, continuing to crash function:',
underErrorErr
)
}
// Throw the error to crash the serverless function
if (isResSent(res)) {
console.error('!!! WARNING !!!')
console.error(
'Your function crashed, but closed the response before allowing the function to exit.\\n' +
'This may cause unexpected behavior for the next request.'
)
console.error('!!! WARNING !!!')
}
throw err
}
const result2 = await renderToHTML(
req,
res,
'/_error',
parsedUrl!.query,
Object.assign({}, options, {
getStaticProps: undefined,
getStaticPaths: undefined,
getServerSideProps: undefined,
Component: Error,
err: res.statusCode === 404 ? undefined : err,
})
)
return result2 ? result2.toUnchunkedString() : null
}
}
return {
renderReqToHTML,
render: async function render(req: IncomingMessage, res: ServerResponse) {
try {
const html = await renderReqToHTML(req, res)
if (html) {
sendRenderResult({
req,
res,
result: RenderResult.fromStatic(html as any),
type: 'html',
generateEtags,
poweredByHeader,
})
}
} catch (err) {
console.error(err)
// Throw the error to crash the serverless function
throw err
}
},
}
}