next-server.ts 43.8 KB
Newer Older
G
Guy Bedford 已提交
1
import compression from 'next/dist/compiled/compression'
J
Joe Haddad 已提交
2
import fs from 'fs'
3
import chalk from 'next/dist/compiled/chalk'
J
Joe Haddad 已提交
4
import { IncomingMessage, ServerResponse } from 'http'
G
Guy Bedford 已提交
5
import Proxy from 'next/dist/compiled/http-proxy'
6
import { join, relative, resolve, sep } from 'path'
7
import { parse as parseQs, ParsedUrlQuery } from 'querystring'
8
import { format as formatUrl, parse as parseUrl, UrlWithParsedQuery } from 'url'
9
import { PrerenderManifest } from '../../build'
J
Joe Haddad 已提交
10 11 12 13 14 15
import {
  getRedirectStatus,
  Header,
  Redirect,
  Rewrite,
  RouteType,
16 17
  CustomRoutes,
} from '../../lib/load-custom-routes'
J
JJ Kasper 已提交
18
import { withCoalescedInvoke } from '../../lib/coalesced-function'
J
Joe Haddad 已提交
19 20
import {
  BUILD_ID_FILE,
21
  CLIENT_PUBLIC_FILES_PATH,
J
Joe Haddad 已提交
22 23
  CLIENT_STATIC_FILES_PATH,
  CLIENT_STATIC_FILES_RUNTIME,
24
  PAGES_MANIFEST,
J
Joe Haddad 已提交
25
  PHASE_PRODUCTION_SERVER,
J
Joe Haddad 已提交
26
  PRERENDER_MANIFEST,
27
  ROUTES_MANIFEST,
28
  SERVERLESS_DIRECTORY,
J
Joe Haddad 已提交
29
  SERVER_DIRECTORY,
T
Tim Neutkens 已提交
30
} from '../lib/constants'
J
Joe Haddad 已提交
31 32 33 34
import {
  getRouteMatcher,
  getRouteRegex,
  getSortedRoutes,
35
  isDynamicRoute,
J
Joe Haddad 已提交
36
} from '../lib/router/utils'
37
import * as envConfig from '../lib/runtime-config'
J
Joe Haddad 已提交
38
import { isResSent, NextApiRequest, NextApiResponse } from '../lib/utils'
J
Joe Haddad 已提交
39
import { apiResolver, tryGetPreviewData, __ApiPreviewProps } from './api-utils'
40
import loadConfig, { isTargetLikeServerless } from './config'
41
import pathMatch from '../lib/router/utils/path-match'
J
Joe Haddad 已提交
42
import { recursiveReadDirSync } from './lib/recursive-readdir-sync'
43
import { loadComponents, LoadComponentsReturnType } from './load-components'
J
Joe Haddad 已提交
44
import { normalizePagePath } from './normalize-page-path'
45
import { RenderOpts, RenderOptsPartial, renderToHTML } from './render'
P
Prateek Bhatnagar 已提交
46
import { getPagePath, requireFontManifest } from './require'
47 48 49
import Router, {
  DynamicRoutes,
  PageChecker,
J
Joe Haddad 已提交
50 51 52
  Params,
  route,
  Route,
53
} from './router'
54
import prepareDestination from '../lib/router/utils/prepare-destination'
55
import { sendPayload } from './send-payload'
J
Joe Haddad 已提交
56
import { serveStatic } from './serve-static'
57
import { IncrementalCache } from './incremental-cache'
58
import { execOnce } from '../lib/utils'
59
import { isBlockedPage } from './utils'
60
import { compile as compilePathToRegex } from 'next/dist/compiled/path-to-regexp'
61
import { loadEnvConfig } from '../../lib/load-env-config'
62
import './node-polyfill-fetch'
J
Jan Potoms 已提交
63
import { PagesManifest } from '../../build/webpack/plugins/pages-manifest-plugin'
64
import { removePathTrailingSlash } from '../../client/normalize-trailing-slash'
65
import getRouteFromAssetPath from '../lib/router/utils/get-route-from-asset-path'
P
Prateek Bhatnagar 已提交
66
import { FontManifest } from './font-utils'
J
JJ Kasper 已提交
67 68

const getCustomRouteMatcher = pathMatch(true)
69 70 71

type NextConfig = any

72 73 74 75 76 77
type Middleware = (
  req: IncomingMessage,
  res: ServerResponse,
  next: (err?: Error) => void
) => void

78 79 80 81 82
type FindComponentsResult = {
  components: LoadComponentsReturnType
  query: ParsedUrlQuery
}

T
Tim Neutkens 已提交
83
export type ServerConstructor = {
84 85 86
  /**
   * Where the Next project is located - @default '.'
   */
J
Joe Haddad 已提交
87
  dir?: string
88 89 90
  /**
   * Hide error messages containing server information - @default false
   */
J
Joe Haddad 已提交
91
  quiet?: boolean
92 93 94
  /**
   * Object what you would use in next.config.js - @default {}
   */
95
  conf?: NextConfig
J
JJ Kasper 已提交
96
  dev?: boolean
97
  customServer?: boolean
98
}
99

N
nkzawa 已提交
100
export default class Server {
101 102 103 104
  dir: string
  quiet: boolean
  nextConfig: NextConfig
  distDir: string
105
  pagesDir?: string
106
  publicDir: string
107
  hasStaticDir: boolean
108
  serverBuildDir: string
J
Jan Potoms 已提交
109
  pagesManifest?: PagesManifest
110 111
  buildId: string
  renderOpts: {
T
Tim Neutkens 已提交
112
    poweredByHeader: boolean
J
Joe Haddad 已提交
113 114 115
    buildId: string
    generateEtags: boolean
    runtimeConfig?: { [key: string]: any }
116 117 118
    assetPrefix?: string
    canonicalBase: string
    dev?: boolean
119
    previewProps: __ApiPreviewProps
120
    customServer?: boolean
121
    ampOptimizerConfig?: { [key: string]: any }
122
    basePath: string
P
Prateek Bhatnagar 已提交
123 124
    optimizeFonts: boolean
    fontManifest: FontManifest
125
    optimizeImages: boolean
126
  }
127
  private compression?: Middleware
J
JJ Kasper 已提交
128
  private onErrorMiddleware?: ({ err }: { err: Error }) => Promise<void>
129
  private incrementalCache: IncrementalCache
130
  router: Router
131
  protected dynamicRoutes?: DynamicRoutes
132
  protected customRoutes: CustomRoutes
133

J
Joe Haddad 已提交
134 135 136 137
  public constructor({
    dir = '.',
    quiet = false,
    conf = null,
J
JJ Kasper 已提交
138
    dev = false,
139
    customServer = true,
J
Joe Haddad 已提交
140
  }: ServerConstructor = {}) {
N
nkzawa 已提交
141
    this.dir = resolve(dir)
N
Naoyuki Kanezawa 已提交
142
    this.quiet = quiet
T
Tim Neutkens 已提交
143
    const phase = this.currentPhase()
144
    loadEnvConfig(this.dir, dev)
145

146
    this.nextConfig = loadConfig(phase, this.dir, conf)
147
    this.distDir = join(this.dir, this.nextConfig.distDir)
148
    this.publicDir = join(this.dir, CLIENT_PUBLIC_FILES_PATH)
149
    this.hasStaticDir = fs.existsSync(join(this.dir, 'static'))
T
Tim Neutkens 已提交
150

151 152
    // Only serverRuntimeConfig needs the default
    // publicRuntimeConfig gets it's default in client/index.js
J
Joe Haddad 已提交
153 154 155 156 157
    const {
      serverRuntimeConfig = {},
      publicRuntimeConfig,
      assetPrefix,
      generateEtags,
158
      compress,
J
Joe Haddad 已提交
159
    } = this.nextConfig
160

T
Tim Neutkens 已提交
161
    this.buildId = this.readBuildId()
162

163
    this.renderOpts = {
T
Tim Neutkens 已提交
164
      poweredByHeader: this.nextConfig.poweredByHeader,
165
      canonicalBase: this.nextConfig.amp.canonicalBase,
166
      buildId: this.buildId,
167
      generateEtags,
168
      previewProps: this.getPreviewProps(),
169
      customServer: customServer === true ? true : undefined,
170
      ampOptimizerConfig: this.nextConfig.experimental.amp?.optimizer,
171
      basePath: this.nextConfig.basePath,
172 173 174 175 176
      optimizeFonts: this.nextConfig.experimental.optimizeFonts && !dev,
      fontManifest:
        this.nextConfig.experimental.optimizeFonts && !dev
          ? requireFontManifest(this.distDir, this._isLikeServerless)
          : null,
177
      optimizeImages: this.nextConfig.experimental.optimizeImages,
178
    }
N
Naoyuki Kanezawa 已提交
179

180 181
    // Only the `publicRuntimeConfig` key is exposed to the client side
    // It'll be rendered as part of __NEXT_DATA__ on the client side
182
    if (Object.keys(publicRuntimeConfig).length > 0) {
183
      this.renderOpts.runtimeConfig = publicRuntimeConfig
184 185
    }

186
    if (compress && this.nextConfig.target === 'server') {
187 188 189
      this.compression = compression() as Middleware
    }

190
    // Initialize next/config with the environment configuration
191 192 193 194
    envConfig.setConfig({
      serverRuntimeConfig,
      publicRuntimeConfig,
    })
195

196 197 198 199 200 201 202 203 204 205
    this.serverBuildDir = join(
      this.distDir,
      this._isLikeServerless ? SERVERLESS_DIRECTORY : SERVER_DIRECTORY
    )
    const pagesManifestPath = join(this.serverBuildDir, PAGES_MANIFEST)

    if (!dev) {
      this.pagesManifest = require(pagesManifestPath)
    }

206
    this.customRoutes = this.getCustomRoutes()
J
JJ Kasper 已提交
207
    this.router = new Router(this.generateRoutes())
208
    this.setAssetPrefix(assetPrefix)
J
JJ Kasper 已提交
209

210 211 212
    // call init-server middleware, this is also handled
    // individually in serverless bundles when deployed
    if (!dev && this.nextConfig.experimental.plugins) {
213 214
      const initServer = require(join(this.serverBuildDir, 'init-server.js'))
        .default
215
      this.onErrorMiddleware = require(join(
216
        this.serverBuildDir,
217 218 219 220 221
        'on-error-server.js'
      )).default
      initServer()
    }

222
    this.incrementalCache = new IncrementalCache({
J
JJ Kasper 已提交
223 224 225 226
      dev,
      distDir: this.distDir,
      pagesDir: join(
        this.distDir,
227
        this._isLikeServerless ? SERVERLESS_DIRECTORY : SERVER_DIRECTORY,
J
JJ Kasper 已提交
228 229 230 231
        'pages'
      ),
      flushToDisk: this.nextConfig.experimental.sprFlushToDisk,
    })
P
Prateek Bhatnagar 已提交
232 233 234 235 236 237 238 239 240 241

    /**
     * This sets environment variable to be used at the time of SSR by head.tsx.
     * Using this from process.env allows targetting both serverless and SSR by calling
     * `process.env.__NEXT_OPTIMIZE_FONTS`.
     * TODO(prateekbh@): Remove this when experimental.optimizeFonts are being clened up.
     */
    if (this.renderOpts.optimizeFonts) {
      process.env.__NEXT_OPTIMIZE_FONTS = JSON.stringify(true)
    }
242 243 244
    if (this.renderOpts.optimizeImages) {
      process.env.__NEXT_OPTIMIZE_IMAGES = JSON.stringify(true)
    }
N
Naoyuki Kanezawa 已提交
245
  }
N
nkzawa 已提交
246

247
  protected currentPhase(): string {
248
    return PHASE_PRODUCTION_SERVER
249 250
  }

251 252 253 254
  private logError(err: Error): void {
    if (this.onErrorMiddleware) {
      this.onErrorMiddleware({ err })
    }
255
    if (this.quiet) return
256
    console.error(err)
257 258
  }

259
  private async handleRequest(
J
Joe Haddad 已提交
260 261
    req: IncomingMessage,
    res: ServerResponse,
262
    parsedUrl?: UrlWithParsedQuery
J
Joe Haddad 已提交
263
  ): Promise<void> {
264
    // Parse url if parsedUrl not provided
265
    if (!parsedUrl || typeof parsedUrl !== 'object') {
266 267
      const url: any = req.url
      parsedUrl = parseUrl(url, true)
268
    }
269

270 271 272
    // Parse the querystring ourselves if the user doesn't handle querystring parsing
    if (typeof parsedUrl.query === 'string') {
      parsedUrl.query = parseQs(parsedUrl.query)
N
Naoyuki Kanezawa 已提交
273
    }
274

275
    const { basePath } = this.nextConfig
276

277 278 279 280 281
    if (basePath && req.url?.startsWith(basePath)) {
      // store original URL to allow checking if basePath was
      // provided or not
      ;(req as any)._nextHadBasePath = true
      req.url = req.url!.replace(basePath, '') || '/'
T
Tim Neutkens 已提交
282 283
    }

284
    res.statusCode = 200
285 286 287
    try {
      return await this.run(req, res, parsedUrl)
    } catch (err) {
J
Joe Haddad 已提交
288 289 290
      this.logError(err)
      res.statusCode = 500
      res.end('Internal Server Error')
291
    }
292 293
  }

294
  public getRequestHandler() {
295
    return this.handleRequest.bind(this)
N
nkzawa 已提交
296 297
  }

298
  public setAssetPrefix(prefix?: string): void {
299
    this.renderOpts.assetPrefix = prefix ? prefix.replace(/\/$/, '') : ''
300 301
  }

302
  // Backwards compatibility
303
  public async prepare(): Promise<void> {}
N
nkzawa 已提交
304

T
Tim Neutkens 已提交
305
  // Backwards compatibility
306
  protected async close(): Promise<void> {}
T
Tim Neutkens 已提交
307

308
  protected setImmutableAssetCacheControl(res: ServerResponse): void {
T
Tim Neutkens 已提交
309
    res.setHeader('Cache-Control', 'public, max-age=31536000, immutable')
N
nkzawa 已提交
310 311
  }

312
  protected getCustomRoutes(): CustomRoutes {
J
JJ Kasper 已提交
313 314 315
    return require(join(this.distDir, ROUTES_MANIFEST))
  }

316 317 318 319
  private _cachedPreviewManifest: PrerenderManifest | undefined
  protected getPrerenderManifest(): PrerenderManifest {
    if (this._cachedPreviewManifest) {
      return this._cachedPreviewManifest
J
Joe Haddad 已提交
320
    }
321 322 323 324 325 326
    const manifest = require(join(this.distDir, PRERENDER_MANIFEST))
    return (this._cachedPreviewManifest = manifest)
  }

  protected getPreviewProps(): __ApiPreviewProps {
    return this.getPrerenderManifest().preview
J
Joe Haddad 已提交
327 328
  }

329
  protected generateRoutes(): {
330
    basePath: string
331 332
    headers: Route[]
    rewrites: Route[]
333
    fsRoutes: Route[]
334
    redirects: Route[]
335 336
    catchAllRoute: Route
    pageChecker: PageChecker
337
    useFileSystemPublicRoutes: boolean
338 339
    dynamicRoutes: DynamicRoutes | undefined
  } {
340 341 342
    const publicRoutes = fs.existsSync(this.publicDir)
      ? this.generatePublicRoutes()
      : []
J
JJ Kasper 已提交
343

344
    const staticFilesRoute = this.hasStaticDir
345 346 347 348 349
      ? [
          {
            // 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.
350
            // See more: https://github.com/vercel/next.js/issues/2617
351
            match: route('/static/:path*'),
352
            name: 'static catchall',
353
            fn: async (req, res, params, parsedUrl) => {
354 355 356 357 358
              const p = join(
                this.dir,
                'static',
                ...(params.path || []).map(encodeURIComponent)
              )
359
              await this.serveStatic(req, res, p, parsedUrl)
360 361 362
              return {
                finished: true,
              }
363 364 365 366
            },
          } as Route,
        ]
      : []
367

368
    const fsRoutes: Route[] = [
T
Tim Neutkens 已提交
369
      {
370
        match: route('/_next/static/:path*'),
371 372
        type: 'route',
        name: '_next/static catchall',
373
        fn: async (req, res, params, parsedUrl) => {
374
          // make sure to 404 for /_next/static itself
375 376 377 378 379 380
          if (!params.path) {
            await this.render404(req, res, parsedUrl)
            return {
              finished: true,
            }
          }
381

J
Joe Haddad 已提交
382 383 384
          if (
            params.path[0] === CLIENT_STATIC_FILES_RUNTIME ||
            params.path[0] === 'chunks' ||
385 386
            params.path[0] === 'css' ||
            params.path[0] === 'media' ||
387
            params.path[0] === this.buildId ||
388
            params.path[0] === 'pages' ||
389
            params.path[1] === 'pages'
J
Joe Haddad 已提交
390
          ) {
T
Tim Neutkens 已提交
391
            this.setImmutableAssetCacheControl(res)
392
          }
J
Joe Haddad 已提交
393 394 395
          const p = join(
            this.distDir,
            CLIENT_STATIC_FILES_PATH,
396
            ...(params.path || [])
J
Joe Haddad 已提交
397
          )
398
          await this.serveStatic(req, res, p, parsedUrl)
399 400 401
          return {
            finished: true,
          }
402
        },
403
      },
J
JJ Kasper 已提交
404 405
      {
        match: route('/_next/data/:path*'),
406 407
        type: 'route',
        name: '_next/data catchall',
J
JJ Kasper 已提交
408
        fn: async (req, res, params, _parsedUrl) => {
J
JJ Kasper 已提交
409 410 411
          // Make sure to 404 for /_next/data/ itself and
          // we also want to 404 if the buildId isn't correct
          if (!params.path || params.path[0] !== this.buildId) {
412 413 414 415
            await this.render404(req, res, _parsedUrl)
            return {
              finished: true,
            }
J
JJ Kasper 已提交
416 417 418 419 420 421
          }
          // remove buildId from URL
          params.path.shift()

          // show 404 if it doesn't end with .json
          if (!params.path[params.path.length - 1].endsWith('.json')) {
422 423 424 425
            await this.render404(req, res, _parsedUrl)
            return {
              finished: true,
            }
J
JJ Kasper 已提交
426 427 428
          }

          // re-create page's pathname
429 430 431 432 433 434 435 436
          const pathname = getRouteFromAssetPath(
            `/${params.path
              // we need to re-encode the params since they are decoded
              // by path-match and we are re-building the URL
              .map((param: string) => encodeURIComponent(param))
              .join('/')}`,
            '.json'
          )
J
JJ Kasper 已提交
437

J
JJ Kasper 已提交
438
          const parsedUrl = parseUrl(pathname, true)
439

J
JJ Kasper 已提交
440 441 442 443
          await this.render(
            req,
            res,
            pathname,
444
            { ..._parsedUrl.query, _nextDataReq: '1' },
J
JJ Kasper 已提交
445 446
            parsedUrl
          )
447 448 449
          return {
            finished: true,
          }
J
JJ Kasper 已提交
450 451
        },
      },
T
Tim Neutkens 已提交
452
      {
453
        match: route('/_next/:path*'),
454 455
        type: 'route',
        name: '_next catchall',
T
Tim Neutkens 已提交
456
        // This path is needed because `render()` does a check for `/_next` and the calls the routing again
457
        fn: async (req, res, _params, parsedUrl) => {
T
Tim Neutkens 已提交
458
          await this.render404(req, res, parsedUrl)
459 460 461
          return {
            finished: true,
          }
L
Lukáš Huvar 已提交
462 463
        },
      },
464 465
      ...publicRoutes,
      ...staticFilesRoute,
T
Tim Neutkens 已提交
466
    ]
467

468 469 470 471 472 473
    const getCustomRouteBasePath = (r: { basePath?: false }) => {
      return r.basePath !== false && this.renderOpts.dev
        ? this.nextConfig.basePath
        : ''
    }

474 475 476 477
    const getCustomRoute = (r: Rewrite | Redirect | Header, type: RouteType) =>
      ({
        ...r,
        type,
478
        match: getCustomRouteMatcher(`${getCustomRouteBasePath(r)}${r.source}`),
479 480 481 482 483 484 485
        name: type,
        fn: async (_req, _res, _params, _parsedUrl) => ({ finished: false }),
      } as Route & Rewrite & Header)

    const updateHeaderValue = (value: string, params: Params): string => {
      if (!value.includes(':')) {
        return value
486
      }
487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507

      for (const key of Object.keys(params)) {
        if (value.includes(`:${key}`)) {
          value = value
            .replace(
              new RegExp(`:${key}\\*`, 'g'),
              `:${key}--ESCAPED_PARAM_ASTERISKS`
            )
            .replace(
              new RegExp(`:${key}\\?`, 'g'),
              `:${key}--ESCAPED_PARAM_QUESTION`
            )
            .replace(
              new RegExp(`:${key}\\+`, 'g'),
              `:${key}--ESCAPED_PARAM_PLUS`
            )
            .replace(
              new RegExp(`:${key}(?!\\w)`, 'g'),
              `--ESCAPED_PARAM_COLON${key}`
            )
        }
508
      }
509 510 511 512 513 514 515 516 517 518 519 520
      value = value
        .replace(/(:|\*|\?|\+|\(|\)|\{|\})/g, '\\$1')
        .replace(/--ESCAPED_PARAM_PLUS/g, '+')
        .replace(/--ESCAPED_PARAM_COLON/g, ':')
        .replace(/--ESCAPED_PARAM_QUESTION/g, '?')
        .replace(/--ESCAPED_PARAM_ASTERISKS/g, '*')

      // the value needs to start with a forward-slash to be compiled
      // correctly
      return compilePathToRegex(`/${value}`, { validate: false })(
        params
      ).substr(1)
521
    }
522

523 524 525 526 527 528 529 530 531 532 533 534 535 536 537
    // Headers come very first
    const headers = this.customRoutes.headers.map((r) => {
      const headerRoute = getCustomRoute(r, 'header')
      return {
        match: headerRoute.match,
        type: headerRoute.type,
        name: `${headerRoute.type} ${headerRoute.source} header route`,
        fn: async (_req, res, params, _parsedUrl) => {
          const hasParams = Object.keys(params).length > 0

          for (const header of (headerRoute as Header).headers) {
            let { key, value } = header
            if (hasParams) {
              key = updateHeaderValue(key, params)
              value = updateHeaderValue(value, params)
538
            }
539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556
            res.setHeader(key, value)
          }
          return { finished: false }
        },
      } as Route
    })

    const redirects = this.customRoutes.redirects.map((redirect) => {
      const redirectRoute = getCustomRoute(redirect, 'redirect')
      return {
        type: redirectRoute.type,
        match: redirectRoute.match,
        statusCode: redirectRoute.statusCode,
        name: `Redirect route`,
        fn: async (_req, res, params, parsedUrl) => {
          const { parsedDestination } = prepareDestination(
            redirectRoute.destination,
            params,
557 558 559
            parsedUrl.query,
            false,
            getCustomRouteBasePath(redirectRoute)
560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582
          )
          const updatedDestination = formatUrl(parsedDestination)

          res.setHeader('Location', updatedDestination)
          res.statusCode = getRedirectStatus(redirectRoute as Redirect)

          // Since IE11 doesn't support the 308 header add backwards
          // compatibility using refresh header
          if (res.statusCode === 308) {
            res.setHeader('Refresh', `0;url=${updatedDestination}`)
          }

          res.end()
          return {
            finished: true,
          }
        },
      } as Route
    })

    const rewrites = this.customRoutes.rewrites.map((rewrite) => {
      const rewriteRoute = getCustomRoute(rewrite, 'rewrite')
      return {
583
        ...rewriteRoute,
584 585 586 587 588 589 590 591 592
        check: true,
        type: rewriteRoute.type,
        name: `Rewrite route`,
        match: rewriteRoute.match,
        fn: async (req, res, params, parsedUrl) => {
          const { newUrl, parsedDestination } = prepareDestination(
            rewriteRoute.destination,
            params,
            parsedUrl.query,
593 594
            true,
            getCustomRouteBasePath(rewriteRoute)
595
          )
596

597 598 599 600 601 602 603 604 605 606 607 608 609
          // external rewrite, proxy it
          if (parsedDestination.protocol) {
            const target = formatUrl(parsedDestination)
            const proxy = new Proxy({
              target,
              changeOrigin: true,
              ignorePath: true,
            })
            proxy.web(req, res)

            proxy.on('error', (err: Error) => {
              console.error(`Error occurred proxying ${target}`, err)
            })
610 611 612
            return {
              finished: true,
            }
613 614
          }
          ;(req as any)._nextRewroteUrl = newUrl
615 616
          ;(req as any)._nextDidRewrite =
            (req as any)._nextRewroteUrl !== req.url
617

618 619 620 621 622 623 624 625
          return {
            finished: false,
            pathname: newUrl,
            query: parsedDestination.query,
          }
        },
      } as Route
    })
626 627 628 629 630 631

    const catchAllRoute: Route = {
      match: route('/:path*'),
      type: 'route',
      name: 'Catchall render',
      fn: async (req, res, params, parsedUrl) => {
J
Jan Potoms 已提交
632
        let { pathname, query } = parsedUrl
633 634 635 636
        if (!pathname) {
          throw new Error('pathname is undefined')
        }

J
Jan Potoms 已提交
637
        // next.js core assumes page path without trailing slash
638
        pathname = removePathTrailingSlash(pathname)
J
Jan Potoms 已提交
639

640
        if (params?.path?.[0] === 'api') {
641 642 643
          const handled = await this.handleApiRequest(
            req as NextApiRequest,
            res as NextApiResponse,
644
            pathname,
645
            query
646 647 648 649 650 651 652
          )
          if (handled) {
            return { finished: true }
          }
        }

        await this.render(req, res, pathname, query, parsedUrl)
653 654 655 656
        return {
          finished: true,
        }
      },
657
    }
658

659
    const { useFileSystemPublicRoutes } = this.nextConfig
J
Joe Haddad 已提交
660

661 662
    if (useFileSystemPublicRoutes) {
      this.dynamicRoutes = this.getDynamicRoutes()
663
    }
N
nkzawa 已提交
664

665
    return {
666
      headers,
667
      fsRoutes,
668 669
      rewrites,
      redirects,
670
      catchAllRoute,
671
      useFileSystemPublicRoutes,
672
      dynamicRoutes: this.dynamicRoutes,
673
      basePath: this.nextConfig.basePath,
674 675
      pageChecker: this.hasPage.bind(this),
    }
T
Tim Neutkens 已提交
676 677
  }

678
  private async getPagePath(pathname: string): Promise<string> {
679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695
    return getPagePath(
      pathname,
      this.distDir,
      this._isLikeServerless,
      this.renderOpts.dev
    )
  }

  protected async hasPage(pathname: string): Promise<boolean> {
    let found = false
    try {
      found = !!(await this.getPagePath(pathname))
    } catch (_) {}

    return found
  }

696 697 698 699 700
  protected async _beforeCatchAllRender(
    _req: IncomingMessage,
    _res: ServerResponse,
    _params: Params,
    _parsedUrl: UrlWithParsedQuery
701
  ): Promise<boolean> {
702 703 704
    return false
  }

705
  // Used to build API page in development
T
Tim Neutkens 已提交
706
  protected async ensureApiPage(_pathname: string): Promise<void> {}
707

L
Lukáš Huvar 已提交
708 709 710 711 712 713
  /**
   * Resolves `API` request, in development builds on demand
   * @param req http request
   * @param res http response
   * @param pathname path of request
   */
J
Joe Haddad 已提交
714
  private async handleApiRequest(
715 716
    req: IncomingMessage,
    res: ServerResponse,
717 718
    pathname: string,
    query: ParsedUrlQuery
719
  ): Promise<boolean> {
720
    let page = pathname
L
Lukáš Huvar 已提交
721
    let params: Params | boolean = false
722
    let pageFound = await this.hasPage(page)
J
JJ Kasper 已提交
723

724
    if (!pageFound && this.dynamicRoutes) {
L
Lukáš Huvar 已提交
725 726
      for (const dynamicRoute of this.dynamicRoutes) {
        params = dynamicRoute.match(pathname)
727
        if (dynamicRoute.page.startsWith('/api') && params) {
728 729
          page = dynamicRoute.page
          pageFound = true
L
Lukáš Huvar 已提交
730 731 732 733 734
          break
        }
      }
    }

735
    if (!pageFound) {
736
      return false
J
JJ Kasper 已提交
737
    }
738 739 740 741
    // Make sure the page is built before getting the path
    // or else it won't be in the manifest yet
    await this.ensureApiPage(page)

742 743 744 745 746 747 748 749 750 751
    let builtPagePath
    try {
      builtPagePath = await this.getPagePath(page)
    } catch (err) {
      if (err.code === 'ENOENT') {
        return false
      }
      throw err
    }

752
    const pageModule = require(builtPagePath)
753
    query = { ...query, ...params }
J
JJ Kasper 已提交
754

755
    if (!this.renderOpts.dev && this._isLikeServerless) {
756
      if (typeof pageModule.default === 'function') {
757
        prepareServerlessUrl(req, query)
758 759
        await pageModule.default(req, res)
        return true
J
JJ Kasper 已提交
760 761 762
      }
    }

J
Joe Haddad 已提交
763 764 765 766 767
    await apiResolver(
      req,
      res,
      query,
      pageModule,
768
      this.renderOpts.previewProps,
769
      false,
J
Joe Haddad 已提交
770 771
      this.onErrorMiddleware
    )
772
    return true
L
Lukáš Huvar 已提交
773 774
  }

775
  protected generatePublicRoutes(): Route[] {
776
    const publicFiles = new Set(
J
Joe Haddad 已提交
777
      recursiveReadDirSync(this.publicDir).map((p) => p.replace(/\\/g, '/'))
778 779 780 781 782 783 784
    )

    return [
      {
        match: route('/:path*'),
        name: 'public folder catchall',
        fn: async (req, res, params, parsedUrl) => {
785
          const pathParts: string[] = params.path || []
786 787 788 789 790 791 792 793
          const { basePath } = this.nextConfig

          // if basePath is defined require it be present
          if (basePath) {
            if (pathParts[0] !== basePath.substr(1)) return { finished: false }
            pathParts.shift()
          }

794
          const path = `/${pathParts.join('/')}`
795 796 797 798 799 800

          if (publicFiles.has(path)) {
            await this.serveStatic(
              req,
              res,
              // we need to re-encode it since send decodes it
801
              join(this.publicDir, ...pathParts.map(encodeURIComponent)),
802 803
              parsedUrl
            )
804 805 806
            return {
              finished: true,
            }
807 808 809 810 811 812 813
          }
          return {
            finished: false,
          }
        },
      } as Route,
    ]
814 815
  }

816
  protected getDynamicRoutes() {
817 818
    return getSortedRoutes(Object.keys(this.pagesManifest!))
      .filter(isDynamicRoute)
J
Joe Haddad 已提交
819
      .map((page) => ({
820 821 822
        page,
        match: getRouteMatcher(getRouteRegex(page)),
      }))
J
Joe Haddad 已提交
823 824
  }

825
  private handleCompression(req: IncomingMessage, res: ServerResponse): void {
826 827 828 829 830
    if (this.compression) {
      this.compression(req, res, () => {})
    }
  }

831
  protected async run(
J
Joe Haddad 已提交
832 833
    req: IncomingMessage,
    res: ServerResponse,
834
    parsedUrl: UrlWithParsedQuery
835
  ): Promise<void> {
836 837
    this.handleCompression(req, res)

838
    try {
839 840
      const matched = await this.router.execute(req, res, parsedUrl)
      if (matched) {
841 842 843 844 845 846 847 848
        return
      }
    } catch (err) {
      if (err.code === 'DECODE_FAILED') {
        res.statusCode = 400
        return this.renderError(null, req, res, '/_error', {})
      }
      throw err
849 850
    }

851
    await this.render404(req, res, parsedUrl)
N
nkzawa 已提交
852 853
  }

854
  protected async sendHTML(
J
Joe Haddad 已提交
855 856
    req: IncomingMessage,
    res: ServerResponse,
857
    html: string
858
  ): Promise<void> {
T
Tim Neutkens 已提交
859
    const { generateEtags, poweredByHeader } = this.renderOpts
860 861 862 863
    return sendPayload(req, res, html, 'html', {
      generateEtags,
      poweredByHeader,
    })
864 865
  }

J
Joe Haddad 已提交
866 867 868 869 870
  public async render(
    req: IncomingMessage,
    res: ServerResponse,
    pathname: string,
    query: ParsedUrlQuery = {},
871
    parsedUrl?: UrlWithParsedQuery
J
Joe Haddad 已提交
872
  ): Promise<void> {
873 874 875 876 877 878
    if (!pathname.startsWith('/')) {
      console.warn(
        `Cannot render page with path "${pathname}", did you mean "/${pathname}"?. See more info here: https://err.sh/next.js/render-no-starting-slash`
      )
    }

879 880 881 882 883 884 885 886 887 888
    if (
      this.renderOpts.customServer &&
      pathname === '/index' &&
      !(await this.hasPage('/index'))
    ) {
      // maintain backwards compatibility for custom server
      // (see custom-server integration tests)
      pathname = '/'
    }

889
    const url: any = req.url
890

891 892 893 894
    // we allow custom servers to call render for all URLs
    // so check if we need to serve a static _next file or not.
    // we don't modify the URL for _next/data request but still
    // call render so we special case this to prevent an infinite loop
895
    if (
896 897 898
      !query._nextDataReq &&
      (url.match(/^\/_next\//) ||
        (this.hasStaticDir && url.match(/^\/static\//)))
899
    ) {
900 901 902
      return this.handleRequest(req, res, parsedUrl)
    }

903
    if (isBlockedPage(pathname)) {
904
      return this.render404(req, res, parsedUrl)
905 906
    }

907
    const html = await this.renderToHTML(req, res, pathname, query)
908 909
    // Request was ended by the user
    if (html === null) {
910 911 912
      return
    }

913
    return this.sendHTML(req, res, html)
N
Naoyuki Kanezawa 已提交
914
  }
N
nkzawa 已提交
915

J
Joe Haddad 已提交
916
  private async findPageComponents(
J
Joe Haddad 已提交
917
    pathname: string,
918 919 920 921 922 923 924 925 926
    query: ParsedUrlQuery = {},
    params: Params | null = null
  ): Promise<FindComponentsResult | null> {
    const paths = [
      // try serving a static AMP version first
      query.amp ? normalizePagePath(pathname) + '.amp' : null,
      pathname,
    ].filter(Boolean)
    for (const pagePath of paths) {
J
JJ Kasper 已提交
927
      try {
928
        const components = await loadComponents(
J
Joe Haddad 已提交
929
          this.distDir,
930 931
          pagePath!,
          !this.renderOpts.dev && this._isLikeServerless
J
Joe Haddad 已提交
932
        )
933 934 935
        return {
          components,
          query: {
936
            ...(components.getStaticProps
937
              ? { _nextDataReq: query._nextDataReq, amp: query.amp }
938 939 940 941
              : query),
            ...(params || {}),
          },
        }
J
JJ Kasper 已提交
942 943 944 945
      } catch (err) {
        if (err.code !== 'ENOENT') throw err
      }
    }
946
    return null
J
Joe Haddad 已提交
947 948
  }

949
  protected async getStaticPaths(
950 951 952
    pathname: string
  ): Promise<{
    staticPaths: string[] | undefined
953
    fallbackMode: 'static' | 'blocking' | false
954
  }> {
955 956 957 958 959
    // `staticPaths` is intentionally set to `undefined` as it should've
    // been caught when checking disk data.
    const staticPaths = undefined

    // Read whether or not fallback should exist from the manifest.
960 961
    const fallbackField = this.getPrerenderManifest().dynamicRoutes[pathname]
      .fallback
962

963 964 965 966 967 968 969 970 971
    return {
      staticPaths,
      fallbackMode:
        typeof fallbackField === 'string'
          ? 'static'
          : fallbackField === null
          ? 'blocking'
          : false,
    }
972 973
  }

J
Joe Haddad 已提交
974 975 976 977
  private async renderToHTMLWithComponents(
    req: IncomingMessage,
    res: ServerResponse,
    pathname: string,
978
    { components, query }: FindComponentsResult,
979
    opts: RenderOptsPartial
980
  ): Promise<string | null> {
981
    // we need to ensure the status code if /404 is visited directly
982
    if (pathname === '/404') {
983 984 985
      res.statusCode = 404
    }

J
JJ Kasper 已提交
986
    // handle static page
987 988
    if (typeof components.Component === 'string') {
      return components.Component
J
Joe Haddad 已提交
989 990
    }

J
JJ Kasper 已提交
991 992
    // check request state
    const isLikeServerless =
993 994
      typeof components.Component === 'object' &&
      typeof (components.Component as any).renderReqToHTML === 'function'
995 996 997
    const isSSG = !!components.getStaticProps
    const isServerProps = !!components.getServerSideProps
    const hasStaticPaths = !!components.getStaticPaths
998

999 1000 1001 1002
    if (!query.amp) {
      delete query.amp
    }

1003
    // Toggle whether or not this is a Data request
1004
    const isDataReq = !!query._nextDataReq && (isSSG || isServerProps)
1005 1006
    delete query._nextDataReq

1007 1008 1009 1010 1011 1012 1013 1014
    let previewData: string | false | object | undefined
    let isPreviewMode = false

    if (isServerProps || isSSG) {
      previewData = tryGetPreviewData(req, res, this.renderOpts.previewProps)
      isPreviewMode = previewData !== false
    }

1015 1016 1017 1018 1019 1020
    // Compute the iSSG cache key. We use the rewroteUrl since
    // pages with fallback: false are allowed to be rewritten to
    // and we need to look up the path by the rewritten path
    let urlPathname = (req as any)._nextRewroteUrl
      ? (req as any)._nextRewroteUrl
      : `${parseUrl(req.url || '').pathname!}`
1021

1022 1023 1024
    // remove trailing slash
    urlPathname = urlPathname.replace(/(?!^)\/$/, '')

1025 1026 1027 1028 1029 1030 1031 1032
    // remove /_next/data prefix from urlPathname so it matches
    // for direct page visit and /_next/data visit
    if (isDataReq && urlPathname.includes(this.buildId)) {
      urlPathname = (urlPathname.split(this.buildId).pop() || '/')
        .replace(/\.json$/, '')
        .replace(/\/index$/, '/')
    }

1033 1034 1035 1036
    const ssgCacheKey =
      isPreviewMode || !isSSG
        ? undefined // Preview mode bypasses the cache
        : `${urlPathname}${query.amp ? '.amp' : ''}`
J
JJ Kasper 已提交
1037 1038

    // Complete the response with cached data if its present
1039 1040 1041
    const cachedData = ssgCacheKey
      ? await this.incrementalCache.get(ssgCacheKey)
      : undefined
1042

J
JJ Kasper 已提交
1043
    if (cachedData) {
1044
      const data = isDataReq
J
JJ Kasper 已提交
1045 1046 1047
        ? JSON.stringify(cachedData.pageData)
        : cachedData.html

1048
      sendPayload(
1049
        req,
J
JJ Kasper 已提交
1050 1051
        res,
        data,
1052
        isDataReq ? 'json' : 'html',
1053 1054 1055 1056
        {
          generateEtags: this.renderOpts.generateEtags,
          poweredByHeader: this.renderOpts.poweredByHeader,
        },
1057 1058 1059 1060 1061 1062 1063 1064 1065
        !this.renderOpts.dev
          ? {
              private: isPreviewMode,
              stateful: false, // GSP response
              revalidate:
                cachedData.curRevalidate !== undefined
                  ? cachedData.curRevalidate
                  : /* default to minimum revalidate (this should be an invariant) */ 1,
            }
1066
          : undefined
J
JJ Kasper 已提交
1067 1068 1069 1070 1071 1072
      )

      // Stop the request chain here if the data we sent was up-to-date
      if (!cachedData.isStale) {
        return null
      }
J
JJ Kasper 已提交
1073
    }
J
Joe Haddad 已提交
1074

J
JJ Kasper 已提交
1075
    // If we're here, that means data is missing or it's stale.
1076 1077 1078 1079 1080 1081
    const maybeCoalesceInvoke = ssgCacheKey
      ? (fn: any) => withCoalescedInvoke(fn).bind(null, ssgCacheKey, [])
      : (fn: any) => async () => {
          const value = await fn()
          return { isOrigin: true, value }
        }
J
JJ Kasper 已提交
1082

1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098
    const doRender = maybeCoalesceInvoke(
      async (): Promise<{
        html: string | null
        pageData: any
        sprRevalidate: number | false
      }> => {
        let pageData: any
        let html: string | null
        let sprRevalidate: number | false

        let renderResult
        // handle serverless
        if (isLikeServerless) {
          renderResult = await (components.Component as any).renderReqToHTML(
            req,
            res,
P
Prateek Bhatnagar 已提交
1099 1100 1101 1102
            'passthrough',
            {
              fontManifest: this.renderOpts.fontManifest,
            }
1103
          )
J
JJ Kasper 已提交
1104

1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125
          html = renderResult.html
          pageData = renderResult.renderOpts.pageData
          sprRevalidate = renderResult.renderOpts.revalidate
        } else {
          const renderOpts: RenderOpts = {
            ...components,
            ...opts,
            isDataReq,
          }
          renderResult = await renderToHTML(
            req,
            res,
            pathname,
            query,
            renderOpts
          )

          html = renderResult
          // TODO: change this to a different passing mechanism
          pageData = (renderOpts as any).pageData
          sprRevalidate = (renderOpts as any).revalidate
J
JJ Kasper 已提交
1126 1127
        }

1128
        return { html, pageData, sprRevalidate }
J
JJ Kasper 已提交
1129
      }
1130
    )
J
JJ Kasper 已提交
1131

1132
    const isProduction = !this.renderOpts.dev
J
Joe Haddad 已提交
1133
    const isDynamicPathname = isDynamicRoute(pathname)
1134
    const didRespond = isResSent(res)
1135

1136
    const { staticPaths, fallbackMode } = hasStaticPaths
1137
      ? await this.getStaticPaths(pathname)
1138
      : { staticPaths: undefined, fallbackMode: false }
1139

1140 1141 1142 1143 1144
    // When we did not respond from cache, we need to choose to block on
    // rendering or return a skeleton.
    //
    // * Data requests always block.
    //
1145 1146
    // * Blocking mode fallback always blocks.
    //
1147 1148
    // * Preview mode toggles all pages to be resolved in a blocking manner.
    //
1149
    // * Non-dynamic pages should block (though this is an impossible
1150 1151
    //   case in production).
    //
1152 1153
    // * Dynamic pages should return their skeleton if not defined in
    //   getStaticPaths, then finish the data request on the client-side.
1154
    //
J
Joe Haddad 已提交
1155
    if (
1156
      fallbackMode !== 'blocking' &&
1157
      ssgCacheKey &&
1158 1159 1160
      !didRespond &&
      !isPreviewMode &&
      isDynamicPathname &&
1161 1162 1163
      // Development should trigger fallback when the path is not in
      // `getStaticPaths`
      (isProduction || !staticPaths || !staticPaths.includes(urlPathname))
J
Joe Haddad 已提交
1164
    ) {
1165 1166 1167 1168 1169
      if (
        // In development, fall through to render to handle missing
        // getStaticPaths.
        (isProduction || staticPaths) &&
        // When fallback isn't present, abort this render so we 404
1170
        fallbackMode !== 'static'
1171
      ) {
1172
        throw new NoFallbackError()
1173 1174
      }

1175 1176
      if (!isDataReq) {
        let html: string
1177

1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189
        // Production already emitted the fallback as static HTML.
        if (isProduction) {
          html = await this.incrementalCache.getFallback(pathname)
        }
        // We need to generate the fallback on-demand for development.
        else {
          query.__nextFallback = 'true'
          if (isLikeServerless) {
            prepareServerlessUrl(req, query)
          }
          const { value: renderResult } = await doRender()
          html = renderResult.html
1190 1191
        }

1192 1193 1194 1195 1196 1197
        sendPayload(req, res, html, 'html', {
          generateEtags: this.renderOpts.generateEtags,
          poweredByHeader: this.renderOpts.poweredByHeader,
        })
        return null
      }
1198 1199
    }

1200 1201 1202
    const {
      isOrigin,
      value: { html, pageData, sprRevalidate },
1203
    } = await doRender()
1204 1205
    let resHtml = html
    if (!isResSent(res) && (isSSG || isDataReq || isServerProps)) {
1206
      sendPayload(
1207
        req,
1208 1209
        res,
        isDataReq ? JSON.stringify(pageData) : html,
1210
        isDataReq ? 'json' : 'html',
1211 1212 1213 1214
        {
          generateEtags: this.renderOpts.generateEtags,
          poweredByHeader: this.renderOpts.poweredByHeader,
        },
1215
        !this.renderOpts.dev || (isServerProps && !isDataReq)
1216 1217
          ? {
              private: isPreviewMode,
1218
              stateful: !isSSG,
1219 1220
              revalidate: sprRevalidate,
            }
1221
          : undefined
1222
      )
1223
      resHtml = null
1224
    }
J
JJ Kasper 已提交
1225

1226
    // Update the cache if the head request and cacheable
1227
    if (isOrigin && ssgCacheKey) {
1228 1229 1230 1231 1232
      await this.incrementalCache.set(
        ssgCacheKey,
        { html: html!, pageData },
        sprRevalidate
      )
1233 1234
    }

1235
    return resHtml
1236 1237
  }

1238
  public async renderToHTML(
J
Joe Haddad 已提交
1239 1240 1241
    req: IncomingMessage,
    res: ServerResponse,
    pathname: string,
1242
    query: ParsedUrlQuery = {}
J
Joe Haddad 已提交
1243
  ): Promise<string | null> {
1244 1245 1246
    try {
      const result = await this.findPageComponents(pathname, query)
      if (result) {
1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258
        try {
          return await this.renderToHTMLWithComponents(
            req,
            res,
            pathname,
            result,
            { ...this.renderOpts }
          )
        } catch (err) {
          if (!(err instanceof NoFallbackError)) {
            throw err
          }
1259
        }
1260
      }
J
Joe Haddad 已提交
1261

1262 1263 1264 1265 1266 1267
      if (this.dynamicRoutes) {
        for (const dynamicRoute of this.dynamicRoutes) {
          const params = dynamicRoute.match(pathname)
          if (!params) {
            continue
          }
J
Joe Haddad 已提交
1268

1269
          const dynamicRouteResult = await this.findPageComponents(
1270 1271 1272 1273
            dynamicRoute.page,
            query,
            params
          )
1274
          if (dynamicRouteResult) {
1275 1276 1277 1278 1279
            try {
              return await this.renderToHTMLWithComponents(
                req,
                res,
                dynamicRoute.page,
1280
                dynamicRouteResult,
1281 1282 1283 1284 1285 1286
                { ...this.renderOpts, params }
              )
            } catch (err) {
              if (!(err instanceof NoFallbackError)) {
                throw err
              }
1287
            }
J
Joe Haddad 已提交
1288 1289
          }
        }
1290 1291 1292 1293 1294 1295 1296 1297 1298
      }
    } catch (err) {
      this.logError(err)
      res.statusCode = 500
      return await this.renderErrorToHTML(err, req, res, pathname, query)
    }

    res.statusCode = 404
    return await this.renderErrorToHTML(null, req, res, pathname, query)
N
Naoyuki Kanezawa 已提交
1299 1300
  }

J
Joe Haddad 已提交
1301 1302 1303 1304 1305
  public async renderError(
    err: Error | null,
    req: IncomingMessage,
    res: ServerResponse,
    pathname: string,
1306
    query: ParsedUrlQuery = {}
J
Joe Haddad 已提交
1307 1308 1309
  ): Promise<void> {
    res.setHeader(
      'Cache-Control',
1310
      'no-cache, no-store, max-age=0, must-revalidate'
J
Joe Haddad 已提交
1311
    )
N
Naoyuki Kanezawa 已提交
1312
    const html = await this.renderErrorToHTML(err, req, res, pathname, query)
1313
    if (html === null) {
1314 1315
      return
    }
1316
    return this.sendHTML(req, res, html)
N
nkzawa 已提交
1317 1318
  }

1319 1320 1321 1322 1323 1324 1325 1326 1327
  private customErrorNo404Warn = execOnce(() => {
    console.warn(
      chalk.bold.yellow(`Warning: `) +
        chalk.yellow(
          `You have added a custom /_error page without a custom /404 page. This prevents the 404 page from being auto statically optimized.\nSee here for info: https://err.sh/next.js/custom-error-no-custom-404`
        )
    )
  })

J
Joe Haddad 已提交
1328 1329 1330 1331 1332
  public async renderErrorToHTML(
    err: Error | null,
    req: IncomingMessage,
    res: ServerResponse,
    _pathname: string,
1333
    query: ParsedUrlQuery = {}
J
Joe Haddad 已提交
1334
  ) {
1335
    let result: null | FindComponentsResult = null
1336

1337 1338 1339
    const is404 = res.statusCode === 404
    let using404Page = false

1340
    // use static 404 page if available and is 404 response
1341
    if (is404) {
1342 1343
      result = await this.findPageComponents('/404')
      using404Page = result !== null
1344 1345 1346 1347 1348 1349
    }

    if (!result) {
      result = await this.findPageComponents('/_error', query)
    }

1350 1351 1352
    if (
      process.env.NODE_ENV !== 'production' &&
      !using404Page &&
1353 1354
      (await this.hasPage('/_error')) &&
      !(await this.hasPage('/404'))
1355 1356 1357 1358
    ) {
      this.customErrorNo404Warn()
    }

1359
    let html: string | null
1360
    try {
1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371
      try {
        html = await this.renderToHTMLWithComponents(
          req,
          res,
          using404Page ? '/404' : '/_error',
          result!,
          {
            ...this.renderOpts,
            err,
          }
        )
1372 1373
      } catch (maybeFallbackError) {
        if (maybeFallbackError instanceof NoFallbackError) {
1374
          throw new Error('invariant: failed to render error page')
1375
        }
1376
        throw maybeFallbackError
1377
      }
1378 1379
    } catch (renderToHtmlError) {
      console.error(renderToHtmlError)
1380 1381 1382 1383
      res.statusCode = 500
      html = 'Internal Server Error'
    }
    return html
N
Naoyuki Kanezawa 已提交
1384 1385
  }

J
Joe Haddad 已提交
1386 1387 1388
  public async render404(
    req: IncomingMessage,
    res: ServerResponse,
1389
    parsedUrl?: UrlWithParsedQuery
J
Joe Haddad 已提交
1390
  ): Promise<void> {
1391 1392
    const url: any = req.url
    const { pathname, query } = parsedUrl ? parsedUrl : parseUrl(url, true)
N
Naoyuki Kanezawa 已提交
1393
    res.statusCode = 404
1394
    return this.renderError(null, req, res, pathname!, query)
N
Naoyuki Kanezawa 已提交
1395
  }
N
Naoyuki Kanezawa 已提交
1396

J
Joe Haddad 已提交
1397 1398 1399 1400
  public async serveStatic(
    req: IncomingMessage,
    res: ServerResponse,
    path: string,
1401
    parsedUrl?: UrlWithParsedQuery
J
Joe Haddad 已提交
1402
  ): Promise<void> {
A
Arunoda Susiripala 已提交
1403
    if (!this.isServeableUrl(path)) {
1404
      return this.render404(req, res, parsedUrl)
A
Arunoda Susiripala 已提交
1405 1406
    }

1407 1408 1409 1410 1411 1412
    if (!(req.method === 'GET' || req.method === 'HEAD')) {
      res.statusCode = 405
      res.setHeader('Allow', ['GET', 'HEAD'])
      return this.renderError(null, req, res, path)
    }

N
Naoyuki Kanezawa 已提交
1413
    try {
1414
      await serveStatic(req, res, path)
N
Naoyuki Kanezawa 已提交
1415
    } catch (err) {
T
Tim Neutkens 已提交
1416
      if (err.code === 'ENOENT' || err.statusCode === 404) {
1417
        this.render404(req, res, parsedUrl)
1418 1419 1420
      } else if (err.statusCode === 412) {
        res.statusCode = 412
        return this.renderError(err, req, res, path)
N
Naoyuki Kanezawa 已提交
1421 1422 1423 1424 1425 1426
      } else {
        throw err
      }
    }
  }

1427 1428 1429 1430 1431 1432 1433 1434 1435
  private _validFilesystemPathSet: Set<string> | null = null
  private getFilesystemPaths(): Set<string> {
    if (this._validFilesystemPathSet) {
      return this._validFilesystemPathSet
    }

    const pathUserFilesStatic = join(this.dir, 'static')
    let userFilesStatic: string[] = []
    if (this.hasStaticDir && fs.existsSync(pathUserFilesStatic)) {
J
Joe Haddad 已提交
1436
      userFilesStatic = recursiveReadDirSync(pathUserFilesStatic).map((f) =>
1437 1438 1439 1440 1441 1442
        join('.', 'static', f)
      )
    }

    let userFilesPublic: string[] = []
    if (this.publicDir && fs.existsSync(this.publicDir)) {
J
Joe Haddad 已提交
1443
      userFilesPublic = recursiveReadDirSync(this.publicDir).map((f) =>
1444 1445 1446 1447 1448 1449 1450
        join('.', 'public', f)
      )
    }

    let nextFilesStatic: string[] = []
    nextFilesStatic = recursiveReadDirSync(
      join(this.distDir, 'static')
J
Joe Haddad 已提交
1451
    ).map((f) => join('.', relative(this.dir, this.distDir), 'static', f))
1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485

    return (this._validFilesystemPathSet = new Set<string>([
      ...nextFilesStatic,
      ...userFilesPublic,
      ...userFilesStatic,
    ]))
  }

  protected isServeableUrl(untrustedFileUrl: string): boolean {
    // This method mimics what the version of `send` we use does:
    // 1. decodeURIComponent:
    //    https://github.com/pillarjs/send/blob/0.17.1/index.js#L989
    //    https://github.com/pillarjs/send/blob/0.17.1/index.js#L518-L522
    // 2. resolve:
    //    https://github.com/pillarjs/send/blob/de073ed3237ade9ff71c61673a34474b30e5d45b/index.js#L561

    let decodedUntrustedFilePath: string
    try {
      // (1) Decode the URL so we have the proper file name
      decodedUntrustedFilePath = decodeURIComponent(untrustedFileUrl)
    } catch {
      return false
    }

    // (2) Resolve "up paths" to determine real request
    const untrustedFilePath = resolve(decodedUntrustedFilePath)

    // don't allow null bytes anywhere in the file path
    if (untrustedFilePath.indexOf('\0') !== -1) {
      return false
    }

    // Check if .next/static, static and public are in the path.
    // If not the path is not available.
A
Arunoda Susiripala 已提交
1486
    if (
1487 1488 1489
      (untrustedFilePath.startsWith(join(this.distDir, 'static') + sep) ||
        untrustedFilePath.startsWith(join(this.dir, 'static') + sep) ||
        untrustedFilePath.startsWith(join(this.dir, 'public') + sep)) === false
A
Arunoda Susiripala 已提交
1490 1491 1492 1493
    ) {
      return false
    }

1494 1495 1496 1497
    // Check against the real filesystem paths
    const filesystemUrls = this.getFilesystemPaths()
    const resolved = relative(this.dir, untrustedFilePath)
    return filesystemUrls.has(resolved)
A
Arunoda Susiripala 已提交
1498 1499
  }

1500
  protected readBuildId(): string {
1501 1502 1503 1504 1505
    const buildIdFile = join(this.distDir, BUILD_ID_FILE)
    try {
      return fs.readFileSync(buildIdFile, 'utf8').trim()
    } catch (err) {
      if (!fs.existsSync(buildIdFile)) {
J
Joe Haddad 已提交
1506
        throw new Error(
1507
          `Could not find a valid build in the '${this.distDir}' directory! Try building your app with 'next build' before starting the server.`
J
Joe Haddad 已提交
1508
        )
1509 1510 1511
      }

      throw err
1512
    }
1513
  }
1514

1515
  protected get _isLikeServerless(): boolean {
1516 1517
    return isTargetLikeServerless(this.nextConfig.target)
  }
1518
}
1519

1520 1521 1522 1523
function prepareServerlessUrl(
  req: IncomingMessage,
  query: ParsedUrlQuery
): void {
1524 1525 1526 1527 1528 1529 1530 1531 1532 1533
  const curUrl = parseUrl(req.url!, true)
  req.url = formatUrl({
    ...curUrl,
    search: undefined,
    query: {
      ...curUrl.query,
      ...query,
    },
  })
}
1534 1535

class NoFallbackError extends Error {}