-
Notifications
You must be signed in to change notification settings - Fork 27k
/
next-server.ts
690 lines (624 loc) · 18.5 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
import fs from 'fs'
import { IncomingMessage, ServerResponse } from 'http'
import { join, resolve, sep } from 'path'
import { parse as parseQs, ParsedUrlQuery } from 'querystring'
import { parse as parseUrl, UrlWithParsedQuery } from 'url'
import {
BUILD_ID_FILE,
BUILD_MANIFEST,
CLIENT_PUBLIC_FILES_PATH,
CLIENT_STATIC_FILES_PATH,
CLIENT_STATIC_FILES_RUNTIME,
PAGES_MANIFEST,
PHASE_PRODUCTION_SERVER,
SERVER_DIRECTORY,
SERVERLESS_DIRECTORY,
} from '../lib/constants'
import {
getRouteMatcher,
getRouteRegex,
getSortedRoutes,
isDynamicRoute,
} from '../lib/router/utils'
import * as envConfig from '../lib/runtime-config'
import { NextApiRequest, NextApiResponse } from '../lib/utils'
import { apiResolver } from './api-utils'
import loadConfig from './config'
import { recursiveReadDirSync } from './lib/recursive-readdir-sync'
import { loadComponents, LoadComponentsReturnType } from './load-components'
import { renderToHTML } from './render'
import { getPagePath } from './require'
import Router, { route, Route, RouteMatch, Params } from './router'
import { sendHTML } from './send-html'
import { serveStatic } from './serve-static'
import { isBlockedPage, isInternalUrl } from './utils'
type NextConfig = any
export type ServerConstructor = {
/**
* Where the Next project is located - @default '.'
*/
dir?: string
staticMarkup?: boolean
/**
* Hide error messages containing server information - @default false
*/
quiet?: boolean
/**
* Object what you would use in next.config.js - @default {}
*/
conf?: NextConfig
}
export default class Server {
dir: string
quiet: boolean
nextConfig: NextConfig
distDir: string
publicDir: string
pagesManifest: string
buildId: string
renderOpts: {
poweredByHeader: boolean
ampBindInitData: boolean
staticMarkup: boolean
buildId: string
generateEtags: boolean
runtimeConfig?: { [key: string]: any }
assetPrefix?: string
canonicalBase: string
documentMiddlewareEnabled: boolean
dev?: boolean
}
router: Router
private dynamicRoutes?: Array<{ page: string; match: RouteMatch }>
public constructor({
dir = '.',
staticMarkup = false,
quiet = false,
conf = null,
}: ServerConstructor = {}) {
this.dir = resolve(dir)
this.quiet = quiet
const phase = this.currentPhase()
this.nextConfig = loadConfig(phase, this.dir, conf)
this.distDir = join(this.dir, this.nextConfig.distDir)
// this.pagesDir = join(this.dir, 'pages')
this.publicDir = join(this.dir, CLIENT_PUBLIC_FILES_PATH)
this.pagesManifest = join(
this.distDir,
this.nextConfig.target || 'server',
PAGES_MANIFEST
)
// Only serverRuntimeConfig needs the default
// publicRuntimeConfig gets it's default in client/index.js
const {
serverRuntimeConfig = {},
publicRuntimeConfig,
assetPrefix,
generateEtags,
} = this.nextConfig
this.buildId = this.readBuildId()
this.renderOpts = {
ampBindInitData: this.nextConfig.experimental.ampBindInitData,
poweredByHeader: this.nextConfig.poweredByHeader,
canonicalBase: this.nextConfig.amp.canonicalBase,
documentMiddlewareEnabled: this.nextConfig.experimental
.documentMiddleware,
staticMarkup,
buildId: this.buildId,
generateEtags,
}
// Only the `publicRuntimeConfig` key is exposed to the client side
// It'll be rendered as part of __NEXT_DATA__ on the client side
if (Object.keys(publicRuntimeConfig).length > 0) {
this.renderOpts.runtimeConfig = publicRuntimeConfig
}
// Initialize next/config with the environment configuration
envConfig.setConfig({
serverRuntimeConfig,
publicRuntimeConfig,
})
const routes = this.generateRoutes()
this.router = new Router(routes)
this.setAssetPrefix(assetPrefix)
}
private currentPhase(): string {
return PHASE_PRODUCTION_SERVER
}
private logError(...args: any): void {
if (this.quiet) return
// tslint:disable-next-line
console.error(...args)
}
private handleRequest(
req: IncomingMessage,
res: ServerResponse,
parsedUrl?: UrlWithParsedQuery
): Promise<void> {
// Parse url if parsedUrl not provided
if (!parsedUrl || typeof parsedUrl !== 'object') {
const url: any = req.url
parsedUrl = parseUrl(url, true)
}
// Parse the querystring ourselves if the user doesn't handle querystring parsing
if (typeof parsedUrl.query === 'string') {
parsedUrl.query = parseQs(parsedUrl.query)
}
res.statusCode = 200
return this.run(req, res, parsedUrl).catch(err => {
this.logError(err)
res.statusCode = 500
res.end('Internal Server Error')
})
}
public getRequestHandler() {
return this.handleRequest.bind(this)
}
public setAssetPrefix(prefix?: string) {
this.renderOpts.assetPrefix = prefix ? prefix.replace(/\/$/, '') : ''
}
// Backwards compatibility
public async prepare(): Promise<void> {}
// Backwards compatibility
private async close(): Promise<void> {}
private setImmutableAssetCacheControl(res: ServerResponse) {
res.setHeader('Cache-Control', 'public, max-age=31536000, immutable')
}
private generateRoutes(): Route[] {
const routes: Route[] = [
{
match: route('/_next/static/:path*'),
fn: async (req, res, params, parsedUrl) => {
// The commons folder holds commonschunk files
// The chunks folder holds dynamic entries
// The buildId folder holds pages and potentially other assets. As buildId changes per build it can be long-term cached.
if (
params.path[0] === CLIENT_STATIC_FILES_RUNTIME ||
params.path[0] === 'chunks' ||
params.path[0] === this.buildId
) {
this.setImmutableAssetCacheControl(res)
}
const p = join(
this.distDir,
CLIENT_STATIC_FILES_PATH,
...(params.path || [])
)
await this.serveStatic(req, res, p, parsedUrl)
},
},
{
match: route('/_next/:path*'),
// This path is needed because `render()` does a check for `/_next` and the calls the routing again
fn: async (req, res, _params, parsedUrl) => {
await this.render404(req, res, parsedUrl)
},
},
{
// It's very important to keep this route's param optional.
// (but it should support as many params as needed, separated by '/')
// Otherwise this will lead to a pretty simple DOS attack.
// See more: https://github.com/zeit/next.js/issues/2617
match: route('/static/:path*'),
fn: async (req, res, params, parsedUrl) => {
const p = join(this.dir, 'static', ...(params.path || []))
await this.serveStatic(req, res, p, parsedUrl)
},
},
{
match: route('/api/:path*'),
fn: async (req, res, params, parsedUrl) => {
const { pathname } = parsedUrl
await this.handleApiRequest(
req as NextApiRequest,
res as NextApiResponse,
pathname!
)
},
},
]
if (
this.nextConfig.experimental.publicDirectory &&
fs.existsSync(this.publicDir)
) {
routes.push(...this.generatePublicRoutes())
}
if (this.nextConfig.useFileSystemPublicRoutes) {
this.dynamicRoutes = this.getDynamicRoutes()
// It's very important to keep this route's param optional.
// (but it should support as many params as needed, separated by '/')
// Otherwise this will lead to a pretty simple DOS attack.
// See more: https://github.com/zeit/next.js/issues/2617
routes.push({
match: route('/:path*'),
fn: async (req, res, _params, parsedUrl) => {
const { pathname, query } = parsedUrl
if (!pathname) {
throw new Error('pathname is undefined')
}
await this.render(req, res, pathname, query, parsedUrl)
},
})
}
return routes
}
/**
* Resolves `API` request, in development builds on demand
* @param req http request
* @param res http response
* @param pathname path of request
*/
private async handleApiRequest(
req: NextApiRequest,
res: NextApiResponse,
pathname: string
) {
let params: Params | boolean = false
let resolverFunction: any
try {
resolverFunction = await this.resolveApiRequest(pathname)
} catch (err) {}
if (
this.dynamicRoutes &&
this.dynamicRoutes.length > 0 &&
!resolverFunction
) {
for (const dynamicRoute of this.dynamicRoutes) {
params = dynamicRoute.match(pathname)
if (params) {
resolverFunction = await this.resolveApiRequest(dynamicRoute.page)
break
}
}
}
if (!resolverFunction) {
return this.render404(req, res)
}
if (!this.renderOpts.dev && this.nextConfig.target === 'serverless') {
const mod = require(resolverFunction)
if (typeof mod.default === 'function') {
return mod.default(req, res)
}
}
await apiResolver(
req,
res,
params,
resolverFunction ? require(resolverFunction) : undefined
)
}
/**
* Resolves path to resolver function
* @param pathname path of request
*/
private resolveApiRequest(pathname: string) {
return getPagePath(
pathname,
this.distDir,
this.nextConfig.target === 'serverless',
this.renderOpts.dev
)
}
private generatePublicRoutes(): Route[] {
const routes: Route[] = []
const publicFiles = recursiveReadDirSync(this.publicDir)
const serverBuildPath = join(
this.distDir,
this.nextConfig.target === 'serverless'
? SERVERLESS_DIRECTORY
: SERVER_DIRECTORY
)
const pagesManifest = require(join(serverBuildPath, PAGES_MANIFEST))
publicFiles.forEach(path => {
const unixPath = path.replace(/\\/g, '/')
// Only include public files that will not replace a page path
if (!pagesManifest[unixPath]) {
routes.push({
match: route(unixPath),
fn: async (req, res, _params, parsedUrl) => {
const p = join(this.publicDir, unixPath)
await this.serveStatic(req, res, p, parsedUrl)
},
})
}
})
return routes
}
private getDynamicRoutes() {
const manifest = require(this.pagesManifest)
const dynamicRoutedPages = Object.keys(manifest).filter(isDynamicRoute)
return getSortedRoutes(dynamicRoutedPages).map(page => ({
page,
match: getRouteMatcher(getRouteRegex(page)),
}))
}
private async run(
req: IncomingMessage,
res: ServerResponse,
parsedUrl: UrlWithParsedQuery
) {
try {
const fn = this.router.match(req, res, parsedUrl)
if (fn) {
await fn()
return
}
} catch (err) {
if (err.code === 'DECODE_FAILED') {
res.statusCode = 400
return this.renderError(null, req, res, '/_error', {})
}
throw err
}
await this.render404(req, res, parsedUrl)
}
private async sendHTML(
req: IncomingMessage,
res: ServerResponse,
html: string
) {
const { generateEtags, poweredByHeader } = this.renderOpts
return sendHTML(req, res, html, { generateEtags, poweredByHeader })
}
public async render(
req: IncomingMessage,
res: ServerResponse,
pathname: string,
query: ParsedUrlQuery = {},
parsedUrl?: UrlWithParsedQuery
): Promise<void> {
const url: any = req.url
if (isInternalUrl(url)) {
return this.handleRequest(req, res, parsedUrl)
}
if (isBlockedPage(pathname)) {
return this.render404(req, res, parsedUrl)
}
const html = await this.renderToHTML(req, res, pathname, query, {
dataOnly:
(this.renderOpts.ampBindInitData && Boolean(query.dataOnly)) ||
(req.headers &&
(req.headers.accept || '').indexOf('application/amp.bind+json') !==
-1),
})
// Request was ended by the user
if (html === null) {
return
}
return this.sendHTML(req, res, html)
}
private async findPageComponents(
pathname: string,
query: ParsedUrlQuery = {}
) {
const serverless =
!this.renderOpts.dev && this.nextConfig.target === 'serverless'
// try serving a static AMP version first
if (query.amp) {
try {
return await loadComponents(
this.distDir,
this.buildId,
(pathname === '/' ? '/index' : pathname) + '.amp',
serverless
)
} catch (err) {
if (err.code !== 'ENOENT') throw err
}
}
return await loadComponents(
this.distDir,
this.buildId,
pathname,
serverless
)
}
private async renderToHTMLWithComponents(
req: IncomingMessage,
res: ServerResponse,
pathname: string,
query: ParsedUrlQuery = {},
result: LoadComponentsReturnType,
opts: any
) {
// handle static page
if (typeof result.Component === 'string') {
return result.Component
}
// handle serverless
if (
typeof result.Component === 'object' &&
typeof result.Component.renderReqToHTML === 'function'
) {
return result.Component.renderReqToHTML(req, res)
}
return renderToHTML(req, res, pathname, query, {
...result,
...opts,
})
}
public renderToHTML(
req: IncomingMessage,
res: ServerResponse,
pathname: string,
query: ParsedUrlQuery = {},
{
amphtml,
dataOnly,
hasAmp,
}: {
amphtml?: boolean
hasAmp?: boolean
dataOnly?: boolean
} = {}
): Promise<string | null> {
return this.findPageComponents(pathname, query)
.then(
result => {
if (!(req.method === 'GET' || req.method === 'HEAD')) {
res.statusCode = 405
res.setHeader('Allow', ['GET', 'HEAD'])
return this.renderError(null, req, res, pathname, query)
}
return this.renderToHTMLWithComponents(
req,
res,
pathname,
query,
result,
{ ...this.renderOpts, amphtml, hasAmp, dataOnly }
)
},
err => {
if (err.code !== 'ENOENT' || !this.dynamicRoutes) {
return Promise.reject(err)
}
for (const dynamicRoute of this.dynamicRoutes) {
const params = dynamicRoute.match(pathname)
if (!params) {
continue
}
return this.findPageComponents(dynamicRoute.page, query).then(
result => {
if (!(req.method === 'GET' || req.method === 'HEAD')) {
res.statusCode = 405
res.setHeader('Allow', ['GET', 'HEAD'])
return this.renderError(null, req, res, pathname, query)
}
return this.renderToHTMLWithComponents(
req,
res,
dynamicRoute.page,
{ ...query, ...params },
result,
{ ...this.renderOpts, amphtml, hasAmp, dataOnly }
)
}
)
}
return Promise.reject(err)
}
)
.catch(err => {
if (err && err.code === 'ENOENT') {
res.statusCode = 404
return this.renderErrorToHTML(null, req, res, pathname, query)
} else {
this.logError(err)
res.statusCode = 500
return this.renderErrorToHTML(err, req, res, pathname, query)
}
})
}
public async renderError(
err: Error | null,
req: IncomingMessage,
res: ServerResponse,
pathname: string,
query: ParsedUrlQuery = {}
): Promise<void> {
res.setHeader(
'Cache-Control',
'no-cache, no-store, max-age=0, must-revalidate'
)
const html = await this.renderErrorToHTML(err, req, res, pathname, query)
if (html === null) {
return
}
return this.sendHTML(req, res, html)
}
public async renderErrorToHTML(
err: Error | null,
req: IncomingMessage,
res: ServerResponse,
_pathname: string,
query: ParsedUrlQuery = {}
) {
const result = await this.findPageComponents('/_error', query)
let html
try {
html = await this.renderToHTMLWithComponents(
req,
res,
'/_error',
query,
result,
{
...this.renderOpts,
err,
}
)
} catch (err) {
console.error(err)
res.statusCode = 500
html = 'Internal Server Error'
}
return html
}
public async render404(
req: IncomingMessage,
res: ServerResponse,
parsedUrl?: UrlWithParsedQuery
): Promise<void> {
const url: any = req.url
const { pathname, query } = parsedUrl ? parsedUrl : parseUrl(url, true)
if (!pathname) {
throw new Error('pathname is undefined')
}
res.statusCode = 404
return this.renderError(null, req, res, pathname, query)
}
public async serveStatic(
req: IncomingMessage,
res: ServerResponse,
path: string,
parsedUrl?: UrlWithParsedQuery
): Promise<void> {
if (!this.isServeableUrl(path)) {
return this.render404(req, res, parsedUrl)
}
if (!(req.method === 'GET' || req.method === 'HEAD')) {
res.statusCode = 405
res.setHeader('Allow', ['GET', 'HEAD'])
return this.renderError(null, req, res, path)
}
try {
await serveStatic(req, res, path)
} catch (err) {
if (err.code === 'ENOENT' || err.statusCode === 404) {
this.render404(req, res, parsedUrl)
} else if (err.statusCode === 412) {
res.statusCode = 412
return this.renderError(err, req, res, path)
} else {
throw err
}
}
}
private isServeableUrl(path: string): boolean {
const resolved = resolve(path)
if (
resolved.indexOf(join(this.distDir) + sep) !== 0 &&
resolved.indexOf(join(this.dir, 'static') + sep) !== 0 &&
resolved.indexOf(join(this.dir, 'public') + sep) !== 0
) {
// Seems like the user is trying to traverse the filesystem.
return false
}
return true
}
private readBuildId(): string {
const buildIdFile = join(this.distDir, BUILD_ID_FILE)
try {
return fs.readFileSync(buildIdFile, 'utf8').trim()
} catch (err) {
if (!fs.existsSync(buildIdFile)) {
throw new Error(
`Could not find a valid build in the '${
this.distDir
}' directory! Try building your app with 'next build' before starting the server.`
)
}
throw err
}
}
}