next-server.ts 48.1 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 8 9 10 11
import {
  parse as parseQs,
  stringify as stringifyQs,
  ParsedUrlQuery,
} from 'querystring'
12
import { format as formatUrl, parse as parseUrl, UrlWithParsedQuery } from 'url'
13
import { PrerenderManifest } from '../../build'
J
Joe Haddad 已提交
14 15 16 17 18 19
import {
  getRedirectStatus,
  Header,
  Redirect,
  Rewrite,
  RouteType,
20 21
  CustomRoutes,
} from '../../lib/load-custom-routes'
J
JJ Kasper 已提交
22
import { withCoalescedInvoke } from '../../lib/coalesced-function'
J
Joe Haddad 已提交
23 24
import {
  BUILD_ID_FILE,
25
  CLIENT_PUBLIC_FILES_PATH,
J
Joe Haddad 已提交
26 27
  CLIENT_STATIC_FILES_PATH,
  CLIENT_STATIC_FILES_RUNTIME,
28
  PAGES_MANIFEST,
J
Joe Haddad 已提交
29
  PHASE_PRODUCTION_SERVER,
J
Joe Haddad 已提交
30
  PRERENDER_MANIFEST,
31
  ROUTES_MANIFEST,
32
  SERVERLESS_DIRECTORY,
J
Joe Haddad 已提交
33
  SERVER_DIRECTORY,
T
Tim Neutkens 已提交
34
} from '../lib/constants'
J
Joe Haddad 已提交
35 36 37 38
import {
  getRouteMatcher,
  getRouteRegex,
  getSortedRoutes,
39
  isDynamicRoute,
J
Joe Haddad 已提交
40
} from '../lib/router/utils'
41
import * as envConfig from '../lib/runtime-config'
J
Joe Haddad 已提交
42
import { isResSent, NextApiRequest, NextApiResponse } from '../lib/utils'
43 44 45 46 47 48 49
import {
  apiResolver,
  setLazyProp,
  getCookieParser,
  tryGetPreviewData,
  __ApiPreviewProps,
} from './api-utils'
50
import loadConfig, { isTargetLikeServerless } from './config'
51
import pathMatch from '../lib/router/utils/path-match'
J
Joe Haddad 已提交
52
import { recursiveReadDirSync } from './lib/recursive-readdir-sync'
53
import { loadComponents, LoadComponentsReturnType } from './load-components'
J
Joe Haddad 已提交
54
import { normalizePagePath } from './normalize-page-path'
55
import { RenderOpts, RenderOptsPartial, renderToHTML } from './render'
P
Prateek Bhatnagar 已提交
56
import { getPagePath, requireFontManifest } from './require'
57 58 59
import Router, {
  DynamicRoutes,
  PageChecker,
J
Joe Haddad 已提交
60 61 62
  Params,
  route,
  Route,
63
} from './router'
64
import prepareDestination from '../lib/router/utils/prepare-destination'
65
import { sendPayload } from './send-payload'
J
Joe Haddad 已提交
66
import { serveStatic } from './serve-static'
67
import { IncrementalCache } from './incremental-cache'
68
import { execOnce } from '../lib/utils'
69
import { isBlockedPage } from './utils'
70
import { compile as compilePathToRegex } from 'next/dist/compiled/path-to-regexp'
71
import { loadEnvConfig } from '@next/env'
72
import './node-polyfill-fetch'
J
Jan Potoms 已提交
73
import { PagesManifest } from '../../build/webpack/plugins/pages-manifest-plugin'
74
import { removePathTrailingSlash } from '../../client/normalize-trailing-slash'
75
import getRouteFromAssetPath from '../lib/router/utils/get-route-from-asset-path'
P
Prateek Bhatnagar 已提交
76
import { FontManifest } from './font-utils'
77
import { denormalizePagePath } from './denormalize-page-path'
78 79 80
import accept from '@hapi/accept'
import { normalizeLocalePath } from '../lib/i18n/normalize-locale-path'
import { detectLocaleCookie } from '../lib/i18n/detect-locale-cookie'
81
import * as Log from '../../build/output/log'
J
JJ Kasper 已提交
82 83

const getCustomRouteMatcher = pathMatch(true)
84 85 86

type NextConfig = any

87 88 89 90 91 92
type Middleware = (
  req: IncomingMessage,
  res: ServerResponse,
  next: (err?: Error) => void
) => void

93 94 95 96 97
type FindComponentsResult = {
  components: LoadComponentsReturnType
  query: ParsedUrlQuery
}

T
Tim Neutkens 已提交
98
export type ServerConstructor = {
99 100 101
  /**
   * Where the Next project is located - @default '.'
   */
J
Joe Haddad 已提交
102
  dir?: string
103 104 105
  /**
   * Hide error messages containing server information - @default false
   */
J
Joe Haddad 已提交
106
  quiet?: boolean
107 108 109
  /**
   * Object what you would use in next.config.js - @default {}
   */
110
  conf?: NextConfig
J
JJ Kasper 已提交
111
  dev?: boolean
112
  customServer?: boolean
113
}
114

N
nkzawa 已提交
115
export default class Server {
116 117 118 119
  dir: string
  quiet: boolean
  nextConfig: NextConfig
  distDir: string
120
  pagesDir?: string
121
  publicDir: string
122
  hasStaticDir: boolean
123
  serverBuildDir: string
J
Jan Potoms 已提交
124
  pagesManifest?: PagesManifest
125 126
  buildId: string
  renderOpts: {
T
Tim Neutkens 已提交
127
    poweredByHeader: boolean
J
Joe Haddad 已提交
128 129 130
    buildId: string
    generateEtags: boolean
    runtimeConfig?: { [key: string]: any }
131 132 133
    assetPrefix?: string
    canonicalBase: string
    dev?: boolean
134
    previewProps: __ApiPreviewProps
135
    customServer?: boolean
136
    ampOptimizerConfig?: { [key: string]: any }
137
    basePath: string
P
Prateek Bhatnagar 已提交
138 139
    optimizeFonts: boolean
    fontManifest: FontManifest
140
    optimizeImages: boolean
141 142
    locale?: string
    locales?: string[]
143
  }
144
  private compression?: Middleware
J
JJ Kasper 已提交
145
  private onErrorMiddleware?: ({ err }: { err: Error }) => Promise<void>
146
  private incrementalCache: IncrementalCache
147
  router: Router
148
  protected dynamicRoutes?: DynamicRoutes
149
  protected customRoutes: CustomRoutes
150

J
Joe Haddad 已提交
151 152 153 154
  public constructor({
    dir = '.',
    quiet = false,
    conf = null,
J
JJ Kasper 已提交
155
    dev = false,
156
    customServer = true,
J
Joe Haddad 已提交
157
  }: ServerConstructor = {}) {
N
nkzawa 已提交
158
    this.dir = resolve(dir)
N
Naoyuki Kanezawa 已提交
159
    this.quiet = quiet
T
Tim Neutkens 已提交
160
    const phase = this.currentPhase()
161
    loadEnvConfig(this.dir, dev, Log)
162

163
    this.nextConfig = loadConfig(phase, this.dir, conf)
164
    this.distDir = join(this.dir, this.nextConfig.distDir)
165
    this.publicDir = join(this.dir, CLIENT_PUBLIC_FILES_PATH)
166
    this.hasStaticDir = fs.existsSync(join(this.dir, 'static'))
T
Tim Neutkens 已提交
167

168 169
    // Only serverRuntimeConfig needs the default
    // publicRuntimeConfig gets it's default in client/index.js
J
Joe Haddad 已提交
170 171 172 173 174
    const {
      serverRuntimeConfig = {},
      publicRuntimeConfig,
      assetPrefix,
      generateEtags,
175
      compress,
J
Joe Haddad 已提交
176
    } = this.nextConfig
177

T
Tim Neutkens 已提交
178
    this.buildId = this.readBuildId()
179

180
    this.renderOpts = {
T
Tim Neutkens 已提交
181
      poweredByHeader: this.nextConfig.poweredByHeader,
182
      canonicalBase: this.nextConfig.amp.canonicalBase,
183
      buildId: this.buildId,
184
      generateEtags,
185
      previewProps: this.getPreviewProps(),
186
      customServer: customServer === true ? true : undefined,
187
      ampOptimizerConfig: this.nextConfig.experimental.amp?.optimizer,
188
      basePath: this.nextConfig.basePath,
189 190 191 192 193
      optimizeFonts: this.nextConfig.experimental.optimizeFonts && !dev,
      fontManifest:
        this.nextConfig.experimental.optimizeFonts && !dev
          ? requireFontManifest(this.distDir, this._isLikeServerless)
          : null,
194
      optimizeImages: this.nextConfig.experimental.optimizeImages,
195
      locales: this.nextConfig.experimental.i18n?.locales,
196
    }
N
Naoyuki Kanezawa 已提交
197

198 199
    // Only the `publicRuntimeConfig` key is exposed to the client side
    // It'll be rendered as part of __NEXT_DATA__ on the client side
200
    if (Object.keys(publicRuntimeConfig).length > 0) {
201
      this.renderOpts.runtimeConfig = publicRuntimeConfig
202 203
    }

204
    if (compress && this.nextConfig.target === 'server') {
205 206 207
      this.compression = compression() as Middleware
    }

208
    // Initialize next/config with the environment configuration
209 210 211 212
    envConfig.setConfig({
      serverRuntimeConfig,
      publicRuntimeConfig,
    })
213

214 215 216 217 218 219 220 221 222 223
    this.serverBuildDir = join(
      this.distDir,
      this._isLikeServerless ? SERVERLESS_DIRECTORY : SERVER_DIRECTORY
    )
    const pagesManifestPath = join(this.serverBuildDir, PAGES_MANIFEST)

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

224
    this.customRoutes = this.getCustomRoutes()
J
JJ Kasper 已提交
225
    this.router = new Router(this.generateRoutes())
226
    this.setAssetPrefix(assetPrefix)
J
JJ Kasper 已提交
227

228 229 230
    // call init-server middleware, this is also handled
    // individually in serverless bundles when deployed
    if (!dev && this.nextConfig.experimental.plugins) {
231 232
      const initServer = require(join(this.serverBuildDir, 'init-server.js'))
        .default
233
      this.onErrorMiddleware = require(join(
234
        this.serverBuildDir,
235 236 237 238 239
        'on-error-server.js'
      )).default
      initServer()
    }

240
    this.incrementalCache = new IncrementalCache({
J
JJ Kasper 已提交
241 242 243 244
      dev,
      distDir: this.distDir,
      pagesDir: join(
        this.distDir,
245
        this._isLikeServerless ? SERVERLESS_DIRECTORY : SERVER_DIRECTORY,
J
JJ Kasper 已提交
246 247 248 249
        'pages'
      ),
      flushToDisk: this.nextConfig.experimental.sprFlushToDisk,
    })
P
Prateek Bhatnagar 已提交
250 251 252 253 254 255 256 257 258 259

    /**
     * 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)
    }
260 261 262
    if (this.renderOpts.optimizeImages) {
      process.env.__NEXT_OPTIMIZE_IMAGES = JSON.stringify(true)
    }
N
Naoyuki Kanezawa 已提交
263
  }
N
nkzawa 已提交
264

265
  protected currentPhase(): string {
266
    return PHASE_PRODUCTION_SERVER
267 268
  }

269 270 271 272
  private logError(err: Error): void {
    if (this.onErrorMiddleware) {
      this.onErrorMiddleware({ err })
    }
273
    if (this.quiet) return
274
    console.error(err)
275 276
  }

277
  private async handleRequest(
J
Joe Haddad 已提交
278 279
    req: IncomingMessage,
    res: ServerResponse,
280
    parsedUrl?: UrlWithParsedQuery
J
Joe Haddad 已提交
281
  ): Promise<void> {
282 283
    setLazyProp({ req: req as any }, 'cookies', getCookieParser(req))

284
    // Parse url if parsedUrl not provided
285
    if (!parsedUrl || typeof parsedUrl !== 'object') {
286 287
      const url: any = req.url
      parsedUrl = parseUrl(url, true)
288
    }
289

290 291 292
    // 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 已提交
293
    }
294

295
    const { basePath } = this.nextConfig
296
    const { i18n } = this.nextConfig.experimental
297

298 299 300 301 302
    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 已提交
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
    if (i18n) {
      // get pathname from URL with basePath stripped for locale detection
      const { pathname, ...parsed } = parseUrl(req.url || '/')
      let detectedLocale = detectLocaleCookie(req, i18n.locales)

      if (!detectedLocale) {
        detectedLocale =
          accept.language(req.headers['accept-language'], i18n.locales) ||
          i18n.defaultLocale
      }

      if (
        i18n.localeDetection !== false &&
        denormalizePagePath(pathname || '/') === '/'
      ) {
        res.setHeader(
          'Location',
          formatUrl({
            // make sure to include any query values when redirecting
            ...parsed,
            pathname: `/${detectedLocale}`,
          })
        )
        res.statusCode = 307
        res.end()
      }

      // TODO: domain based locales (domain to locale mapping needs to be provided in next.config.js)
      const localePathResult = normalizeLocalePath(pathname!, i18n.locales)

      if (localePathResult.detectedLocale) {
        detectedLocale = localePathResult.detectedLocale
        req.url = formatUrl({
          ...parsed,
          pathname: localePathResult.pathname,
        })
        parsedUrl.pathname = localePathResult.pathname
      }

      ;(req as any)._nextLocale = detectedLocale || i18n.defaultLocale
    }

347
    res.statusCode = 200
348 349 350
    try {
      return await this.run(req, res, parsedUrl)
    } catch (err) {
J
Joe Haddad 已提交
351 352 353
      this.logError(err)
      res.statusCode = 500
      res.end('Internal Server Error')
354
    }
355 356
  }

357
  public getRequestHandler() {
358
    return this.handleRequest.bind(this)
N
nkzawa 已提交
359 360
  }

361
  public setAssetPrefix(prefix?: string): void {
362
    this.renderOpts.assetPrefix = prefix ? prefix.replace(/\/$/, '') : ''
363 364
  }

365
  // Backwards compatibility
366
  public async prepare(): Promise<void> {}
N
nkzawa 已提交
367

T
Tim Neutkens 已提交
368
  // Backwards compatibility
369
  protected async close(): Promise<void> {}
T
Tim Neutkens 已提交
370

371
  protected setImmutableAssetCacheControl(res: ServerResponse): void {
T
Tim Neutkens 已提交
372
    res.setHeader('Cache-Control', 'public, max-age=31536000, immutable')
N
nkzawa 已提交
373 374
  }

375
  protected getCustomRoutes(): CustomRoutes {
J
JJ Kasper 已提交
376 377 378
    return require(join(this.distDir, ROUTES_MANIFEST))
  }

379 380 381 382
  private _cachedPreviewManifest: PrerenderManifest | undefined
  protected getPrerenderManifest(): PrerenderManifest {
    if (this._cachedPreviewManifest) {
      return this._cachedPreviewManifest
J
Joe Haddad 已提交
383
    }
384 385 386 387 388 389
    const manifest = require(join(this.distDir, PRERENDER_MANIFEST))
    return (this._cachedPreviewManifest = manifest)
  }

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

392
  protected generateRoutes(): {
393
    basePath: string
394 395
    headers: Route[]
    rewrites: Route[]
396
    fsRoutes: Route[]
397
    redirects: Route[]
398 399
    catchAllRoute: Route
    pageChecker: PageChecker
400
    useFileSystemPublicRoutes: boolean
401 402
    dynamicRoutes: DynamicRoutes | undefined
  } {
403 404 405
    const publicRoutes = fs.existsSync(this.publicDir)
      ? this.generatePublicRoutes()
      : []
J
JJ Kasper 已提交
406

407
    const staticFilesRoute = this.hasStaticDir
408 409 410 411 412
      ? [
          {
            // 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.
413
            // See more: https://github.com/vercel/next.js/issues/2617
414
            match: route('/static/:path*'),
415
            name: 'static catchall',
416
            fn: async (req, res, params, parsedUrl) => {
417
              const p = join(this.dir, 'static', ...params.path)
418
              await this.serveStatic(req, res, p, parsedUrl)
419 420 421
              return {
                finished: true,
              }
422 423 424 425
            },
          } as Route,
        ]
      : []
426

427
    const fsRoutes: Route[] = [
T
Tim Neutkens 已提交
428
      {
429
        match: route('/_next/static/:path*'),
430 431
        type: 'route',
        name: '_next/static catchall',
432
        fn: async (req, res, params, parsedUrl) => {
433
          // make sure to 404 for /_next/static itself
434 435 436 437 438 439
          if (!params.path) {
            await this.render404(req, res, parsedUrl)
            return {
              finished: true,
            }
          }
440

J
Joe Haddad 已提交
441 442 443
          if (
            params.path[0] === CLIENT_STATIC_FILES_RUNTIME ||
            params.path[0] === 'chunks' ||
444 445
            params.path[0] === 'css' ||
            params.path[0] === 'media' ||
446
            params.path[0] === this.buildId ||
447
            params.path[0] === 'pages' ||
448
            params.path[1] === 'pages'
J
Joe Haddad 已提交
449
          ) {
T
Tim Neutkens 已提交
450
            this.setImmutableAssetCacheControl(res)
451
          }
J
Joe Haddad 已提交
452 453 454
          const p = join(
            this.distDir,
            CLIENT_STATIC_FILES_PATH,
455
            ...(params.path || [])
J
Joe Haddad 已提交
456
          )
457
          await this.serveStatic(req, res, p, parsedUrl)
458 459 460
          return {
            finished: true,
          }
461
        },
462
      },
J
JJ Kasper 已提交
463 464
      {
        match: route('/_next/data/:path*'),
465 466
        type: 'route',
        name: '_next/data catchall',
J
JJ Kasper 已提交
467
        fn: async (req, res, params, _parsedUrl) => {
J
JJ Kasper 已提交
468 469 470
          // 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) {
471 472 473 474
            await this.render404(req, res, _parsedUrl)
            return {
              finished: true,
            }
J
JJ Kasper 已提交
475 476 477 478 479 480
          }
          // 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')) {
481 482 483 484
            await this.render404(req, res, _parsedUrl)
            return {
              finished: true,
            }
J
JJ Kasper 已提交
485 486 487
          }

          // re-create page's pathname
488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506
          let pathname = `/${params.path.join('/')}`

          if (this.nextConfig.experimental.i18n) {
            const localePathResult = normalizeLocalePath(
              pathname,
              this.renderOpts.locales
            )
            let detectedLocale = detectLocaleCookie(
              req,
              this.renderOpts.locales!
            )

            if (localePathResult.detectedLocale) {
              pathname = localePathResult.pathname
              detectedLocale = localePathResult.detectedLocale
            }
            ;(req as any)._nextLocale = detectedLocale
          }
          pathname = getRouteFromAssetPath(pathname, '.json')
J
JJ Kasper 已提交
507

J
JJ Kasper 已提交
508
          const parsedUrl = parseUrl(pathname, true)
509

J
JJ Kasper 已提交
510 511 512 513
          await this.render(
            req,
            res,
            pathname,
514
            { ..._parsedUrl.query, _nextDataReq: '1' },
J
JJ Kasper 已提交
515 516
            parsedUrl
          )
517 518 519
          return {
            finished: true,
          }
J
JJ Kasper 已提交
520 521
        },
      },
T
Tim Neutkens 已提交
522
      {
523
        match: route('/_next/:path*'),
524 525
        type: 'route',
        name: '_next catchall',
T
Tim Neutkens 已提交
526
        // This path is needed because `render()` does a check for `/_next` and the calls the routing again
527
        fn: async (req, res, _params, parsedUrl) => {
T
Tim Neutkens 已提交
528
          await this.render404(req, res, parsedUrl)
529 530 531
          return {
            finished: true,
          }
L
Lukáš Huvar 已提交
532 533
        },
      },
534 535
      ...publicRoutes,
      ...staticFilesRoute,
T
Tim Neutkens 已提交
536
    ]
537

538 539 540 541 542 543
    const getCustomRouteBasePath = (r: { basePath?: false }) => {
      return r.basePath !== false && this.renderOpts.dev
        ? this.nextConfig.basePath
        : ''
    }

544 545 546 547
    const getCustomRoute = (r: Rewrite | Redirect | Header, type: RouteType) =>
      ({
        ...r,
        type,
548
        match: getCustomRouteMatcher(`${getCustomRouteBasePath(r)}${r.source}`),
549 550 551 552 553 554 555
        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
556
      }
557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577

      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}`
            )
        }
578
      }
579 580 581 582 583 584 585 586 587 588 589 590
      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)
591
    }
592

593 594 595 596 597 598 599 600 601 602 603 604 605 606 607
    // 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)
608
            }
609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626
            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,
627 628 629
            parsedUrl.query,
            false,
            getCustomRouteBasePath(redirectRoute)
630
          )
631 632 633 634 635 636 637 638

          const { query } = parsedDestination
          delete parsedDestination.query

          parsedDestination.search = stringifyQs(query, undefined, undefined, {
            encodeURIComponent: (str: string) => str,
          } as any)

639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660
          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 {
661
        ...rewriteRoute,
662 663 664 665 666 667 668 669 670
        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,
671 672
            true,
            getCustomRouteBasePath(rewriteRoute)
673
          )
674

675 676
          // external rewrite, proxy it
          if (parsedDestination.protocol) {
677 678 679 680 681 682 683 684 685
            const { query } = parsedDestination
            delete parsedDestination.query
            parsedDestination.search = stringifyQs(
              query,
              undefined,
              undefined,
              { encodeURIComponent: (str) => str }
            )

686 687 688 689 690 691 692 693 694 695 696
            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)
            })
697 698 699
            return {
              finished: true,
            }
700 701
          }
          ;(req as any)._nextRewroteUrl = newUrl
702 703
          ;(req as any)._nextDidRewrite =
            (req as any)._nextRewroteUrl !== req.url
704

705 706 707 708 709 710 711 712
          return {
            finished: false,
            pathname: newUrl,
            query: parsedDestination.query,
          }
        },
      } as Route
    })
713 714 715 716 717 718

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

J
Jan Potoms 已提交
724
        // next.js core assumes page path without trailing slash
725
        pathname = removePathTrailingSlash(pathname)
J
Jan Potoms 已提交
726

727
        if (params?.path?.[0] === 'api') {
728 729 730
          const handled = await this.handleApiRequest(
            req as NextApiRequest,
            res as NextApiResponse,
731
            pathname,
732
            query
733 734 735 736 737 738 739
          )
          if (handled) {
            return { finished: true }
          }
        }

        await this.render(req, res, pathname, query, parsedUrl)
740 741 742 743
        return {
          finished: true,
        }
      },
744
    }
745

746
    const { useFileSystemPublicRoutes } = this.nextConfig
J
Joe Haddad 已提交
747

748 749
    if (useFileSystemPublicRoutes) {
      this.dynamicRoutes = this.getDynamicRoutes()
750
    }
N
nkzawa 已提交
751

752
    return {
753
      headers,
754
      fsRoutes,
755 756
      rewrites,
      redirects,
757
      catchAllRoute,
758
      useFileSystemPublicRoutes,
759
      dynamicRoutes: this.dynamicRoutes,
760
      basePath: this.nextConfig.basePath,
761 762
      pageChecker: this.hasPage.bind(this),
    }
T
Tim Neutkens 已提交
763 764
  }

765
  private async getPagePath(pathname: string): Promise<string> {
766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782
    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
  }

783 784 785 786 787
  protected async _beforeCatchAllRender(
    _req: IncomingMessage,
    _res: ServerResponse,
    _params: Params,
    _parsedUrl: UrlWithParsedQuery
788
  ): Promise<boolean> {
789 790 791
    return false
  }

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

L
Lukáš Huvar 已提交
795 796 797 798 799 800
  /**
   * Resolves `API` request, in development builds on demand
   * @param req http request
   * @param res http response
   * @param pathname path of request
   */
J
Joe Haddad 已提交
801
  private async handleApiRequest(
802 803
    req: IncomingMessage,
    res: ServerResponse,
804 805
    pathname: string,
    query: ParsedUrlQuery
806
  ): Promise<boolean> {
807
    let page = pathname
L
Lukáš Huvar 已提交
808
    let params: Params | boolean = false
809
    let pageFound = await this.hasPage(page)
J
JJ Kasper 已提交
810

811
    if (!pageFound && this.dynamicRoutes) {
L
Lukáš Huvar 已提交
812 813
      for (const dynamicRoute of this.dynamicRoutes) {
        params = dynamicRoute.match(pathname)
814
        if (dynamicRoute.page.startsWith('/api') && params) {
815 816
          page = dynamicRoute.page
          pageFound = true
L
Lukáš Huvar 已提交
817 818 819 820 821
          break
        }
      }
    }

822
    if (!pageFound) {
823
      return false
J
JJ Kasper 已提交
824
    }
825 826 827 828
    // Make sure the page is built before getting the path
    // or else it won't be in the manifest yet
    await this.ensureApiPage(page)

829 830 831 832 833 834 835 836 837 838
    let builtPagePath
    try {
      builtPagePath = await this.getPagePath(page)
    } catch (err) {
      if (err.code === 'ENOENT') {
        return false
      }
      throw err
    }

839
    const pageModule = require(builtPagePath)
840
    query = { ...query, ...params }
J
JJ Kasper 已提交
841

842
    if (!this.renderOpts.dev && this._isLikeServerless) {
843
      if (typeof pageModule.default === 'function') {
844
        prepareServerlessUrl(req, query)
845 846
        await pageModule.default(req, res)
        return true
J
JJ Kasper 已提交
847 848 849
      }
    }

J
Joe Haddad 已提交
850 851 852 853 854
    await apiResolver(
      req,
      res,
      query,
      pageModule,
855
      this.renderOpts.previewProps,
856
      false,
J
Joe Haddad 已提交
857 858
      this.onErrorMiddleware
    )
859
    return true
L
Lukáš Huvar 已提交
860 861
  }

862
  protected generatePublicRoutes(): Route[] {
863
    const publicFiles = new Set(
864 865 866
      recursiveReadDirSync(this.publicDir).map((p) =>
        encodeURI(p.replace(/\\/g, '/'))
      )
867 868 869 870 871 872 873
    )

    return [
      {
        match: route('/:path*'),
        name: 'public folder catchall',
        fn: async (req, res, params, parsedUrl) => {
874
          const pathParts: string[] = params.path || []
875 876 877 878 879 880 881 882
          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()
          }

883
          const path = `/${pathParts.join('/')}`
884 885 886 887 888

          if (publicFiles.has(path)) {
            await this.serveStatic(
              req,
              res,
889
              join(this.publicDir, ...pathParts),
890 891
              parsedUrl
            )
892 893 894
            return {
              finished: true,
            }
895 896 897 898 899 900 901
          }
          return {
            finished: false,
          }
        },
      } as Route,
    ]
902 903
  }

904
  protected getDynamicRoutes() {
905 906
    return getSortedRoutes(Object.keys(this.pagesManifest!))
      .filter(isDynamicRoute)
J
Joe Haddad 已提交
907
      .map((page) => ({
908 909 910
        page,
        match: getRouteMatcher(getRouteRegex(page)),
      }))
J
Joe Haddad 已提交
911 912
  }

913
  private handleCompression(req: IncomingMessage, res: ServerResponse): void {
914 915 916 917 918
    if (this.compression) {
      this.compression(req, res, () => {})
    }
  }

919
  protected async run(
J
Joe Haddad 已提交
920 921
    req: IncomingMessage,
    res: ServerResponse,
922
    parsedUrl: UrlWithParsedQuery
923
  ): Promise<void> {
924 925
    this.handleCompression(req, res)

926
    try {
927 928
      const matched = await this.router.execute(req, res, parsedUrl)
      if (matched) {
929 930 931 932 933 934 935 936
        return
      }
    } catch (err) {
      if (err.code === 'DECODE_FAILED') {
        res.statusCode = 400
        return this.renderError(null, req, res, '/_error', {})
      }
      throw err
937 938
    }

939
    await this.render404(req, res, parsedUrl)
N
nkzawa 已提交
940 941
  }

942
  protected async sendHTML(
J
Joe Haddad 已提交
943 944
    req: IncomingMessage,
    res: ServerResponse,
945
    html: string
946
  ): Promise<void> {
T
Tim Neutkens 已提交
947
    const { generateEtags, poweredByHeader } = this.renderOpts
948 949 950 951
    return sendPayload(req, res, html, 'html', {
      generateEtags,
      poweredByHeader,
    })
952 953
  }

J
Joe Haddad 已提交
954 955 956 957 958
  public async render(
    req: IncomingMessage,
    res: ServerResponse,
    pathname: string,
    query: ParsedUrlQuery = {},
959
    parsedUrl?: UrlWithParsedQuery
J
Joe Haddad 已提交
960
  ): Promise<void> {
961 962 963 964 965 966
    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`
      )
    }

967 968 969 970 971 972 973 974 975 976
    if (
      this.renderOpts.customServer &&
      pathname === '/index' &&
      !(await this.hasPage('/index'))
    ) {
      // maintain backwards compatibility for custom server
      // (see custom-server integration tests)
      pathname = '/'
    }

977
    const url: any = req.url
978

979 980 981 982
    // 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
983
    if (
984 985 986
      !query._nextDataReq &&
      (url.match(/^\/_next\//) ||
        (this.hasStaticDir && url.match(/^\/static\//)))
987
    ) {
988 989 990
      return this.handleRequest(req, res, parsedUrl)
    }

991
    if (isBlockedPage(pathname)) {
992
      return this.render404(req, res, parsedUrl)
993 994
    }

995
    const html = await this.renderToHTML(req, res, pathname, query)
996 997
    // Request was ended by the user
    if (html === null) {
998 999 1000
      return
    }

1001
    return this.sendHTML(req, res, html)
N
Naoyuki Kanezawa 已提交
1002
  }
N
nkzawa 已提交
1003

J
Joe Haddad 已提交
1004
  private async findPageComponents(
J
Joe Haddad 已提交
1005
    pathname: string,
1006 1007 1008 1009 1010 1011 1012 1013 1014
    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 已提交
1015
      try {
1016
        const components = await loadComponents(
J
Joe Haddad 已提交
1017
          this.distDir,
1018 1019
          pagePath!,
          !this.renderOpts.dev && this._isLikeServerless
J
Joe Haddad 已提交
1020
        )
1021 1022 1023
        return {
          components,
          query: {
1024
            ...(components.getStaticProps
1025
              ? { _nextDataReq: query._nextDataReq, amp: query.amp }
1026 1027 1028 1029
              : query),
            ...(params || {}),
          },
        }
J
JJ Kasper 已提交
1030 1031 1032 1033
      } catch (err) {
        if (err.code !== 'ENOENT') throw err
      }
    }
1034
    return null
J
Joe Haddad 已提交
1035 1036
  }

1037
  protected async getStaticPaths(
1038 1039 1040
    pathname: string
  ): Promise<{
    staticPaths: string[] | undefined
1041
    fallbackMode: 'static' | 'blocking' | false
1042
  }> {
1043 1044 1045 1046 1047
    // `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.
1048 1049
    const fallbackField = this.getPrerenderManifest().dynamicRoutes[pathname]
      .fallback
1050

1051 1052 1053 1054 1055 1056 1057 1058 1059
    return {
      staticPaths,
      fallbackMode:
        typeof fallbackField === 'string'
          ? 'static'
          : fallbackField === null
          ? 'blocking'
          : false,
    }
1060 1061
  }

J
Joe Haddad 已提交
1062 1063 1064 1065
  private async renderToHTMLWithComponents(
    req: IncomingMessage,
    res: ServerResponse,
    pathname: string,
1066
    { components, query }: FindComponentsResult,
1067
    opts: RenderOptsPartial
1068
  ): Promise<string | null> {
1069
    // we need to ensure the status code if /404 is visited directly
1070
    if (pathname === '/404') {
1071 1072 1073
      res.statusCode = 404
    }

J
JJ Kasper 已提交
1074
    // handle static page
1075 1076
    if (typeof components.Component === 'string') {
      return components.Component
J
Joe Haddad 已提交
1077 1078
    }

J
JJ Kasper 已提交
1079 1080
    // check request state
    const isLikeServerless =
1081 1082
      typeof components.Component === 'object' &&
      typeof (components.Component as any).renderReqToHTML === 'function'
1083 1084 1085
    const isSSG = !!components.getStaticProps
    const isServerProps = !!components.getServerSideProps
    const hasStaticPaths = !!components.getStaticPaths
1086

1087 1088 1089 1090
    if (!query.amp) {
      delete query.amp
    }

1091
    // Toggle whether or not this is a Data request
1092
    const isDataReq = !!query._nextDataReq && (isSSG || isServerProps)
1093 1094
    delete query._nextDataReq

1095 1096 1097 1098 1099 1100 1101 1102
    let previewData: string | false | object | undefined
    let isPreviewMode = false

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

1103 1104 1105
    // 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
1106 1107 1108
    let urlPathname = parseUrl(req.url || '').pathname || '/'

    let resolvedUrlPathname = (req as any)._nextRewroteUrl
1109
      ? (req as any)._nextRewroteUrl
1110
      : urlPathname
1111

1112 1113 1114 1115 1116 1117 1118 1119 1120
    resolvedUrlPathname = removePathTrailingSlash(resolvedUrlPathname)
    urlPathname = removePathTrailingSlash(urlPathname)

    const stripNextDataPath = (path: string) => {
      if (path.includes(this.buildId)) {
        path = denormalizePagePath(
          (path.split(this.buildId).pop() || '/').replace(/\.json$/, '')
        )
      }
1121 1122 1123 1124

      if (this.nextConfig.experimental.i18n) {
        return normalizeLocalePath(path, this.renderOpts.locales).pathname
      }
1125 1126
      return path
    }
1127

1128 1129
    // remove /_next/data prefix from urlPathname so it matches
    // for direct page visit and /_next/data visit
1130 1131 1132
    if (isDataReq) {
      resolvedUrlPathname = stripNextDataPath(resolvedUrlPathname)
      urlPathname = stripNextDataPath(urlPathname)
1133 1134
    }

1135 1136
    const locale = (req as any)._nextLocale

1137 1138 1139
    const ssgCacheKey =
      isPreviewMode || !isSSG
        ? undefined // Preview mode bypasses the cache
1140 1141 1142
        : `${locale ? `/${locale}` : ''}${resolvedUrlPathname}${
            query.amp ? '.amp' : ''
          }`
J
JJ Kasper 已提交
1143 1144

    // Complete the response with cached data if its present
1145 1146 1147
    const cachedData = ssgCacheKey
      ? await this.incrementalCache.get(ssgCacheKey)
      : undefined
1148

J
JJ Kasper 已提交
1149
    if (cachedData) {
1150
      const data = isDataReq
J
JJ Kasper 已提交
1151 1152 1153
        ? JSON.stringify(cachedData.pageData)
        : cachedData.html

1154
      sendPayload(
1155
        req,
J
JJ Kasper 已提交
1156 1157
        res,
        data,
1158
        isDataReq ? 'json' : 'html',
1159 1160 1161 1162
        {
          generateEtags: this.renderOpts.generateEtags,
          poweredByHeader: this.renderOpts.poweredByHeader,
        },
1163 1164 1165 1166 1167 1168 1169 1170 1171
        !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,
            }
1172
          : undefined
J
JJ Kasper 已提交
1173 1174 1175 1176 1177 1178
      )

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

J
JJ Kasper 已提交
1181
    // If we're here, that means data is missing or it's stale.
1182 1183 1184 1185 1186 1187
    const maybeCoalesceInvoke = ssgCacheKey
      ? (fn: any) => withCoalescedInvoke(fn).bind(null, ssgCacheKey, [])
      : (fn: any) => async () => {
          const value = await fn()
          return { isOrigin: true, value }
        }
J
JJ Kasper 已提交
1188

1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204
    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 已提交
1205 1206 1207
            'passthrough',
            {
              fontManifest: this.renderOpts.fontManifest,
1208 1209
              locale: (req as any)._nextLocale,
              locales: this.renderOpts.locales,
P
Prateek Bhatnagar 已提交
1210
            }
1211
          )
J
JJ Kasper 已提交
1212

1213 1214 1215 1216
          html = renderResult.html
          pageData = renderResult.renderOpts.pageData
          sprRevalidate = renderResult.renderOpts.revalidate
        } else {
1217 1218 1219 1220 1221 1222 1223
          const origQuery = parseUrl(req.url || '', true).query
          const resolvedUrl = formatUrl({
            pathname: resolvedUrlPathname,
            // make sure to only add query values from original URL
            query: origQuery,
          })

1224 1225 1226 1227
          const renderOpts: RenderOpts = {
            ...components,
            ...opts,
            isDataReq,
1228
            resolvedUrl,
1229
            locale: (req as any)._nextLocale,
1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240
            // For getServerSideProps we need to ensure we use the original URL
            // and not the resolved URL to prevent a hydration mismatch on
            // asPath
            resolvedAsPath: isServerProps
              ? formatUrl({
                  // we use the original URL pathname less the _next/data prefix if
                  // present
                  pathname: urlPathname,
                  query: origQuery,
                })
              : resolvedUrl,
1241
          }
1242

1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254
          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 已提交
1255 1256
        }

1257
        return { html, pageData, sprRevalidate }
J
JJ Kasper 已提交
1258
      }
1259
    )
J
JJ Kasper 已提交
1260

1261
    const isProduction = !this.renderOpts.dev
J
Joe Haddad 已提交
1262
    const isDynamicPathname = isDynamicRoute(pathname)
1263
    const didRespond = isResSent(res)
1264

1265
    const { staticPaths, fallbackMode } = hasStaticPaths
1266
      ? await this.getStaticPaths(pathname)
1267
      : { staticPaths: undefined, fallbackMode: false }
1268

1269 1270 1271 1272 1273
    // When we did not respond from cache, we need to choose to block on
    // rendering or return a skeleton.
    //
    // * Data requests always block.
    //
1274 1275
    // * Blocking mode fallback always blocks.
    //
1276 1277
    // * Preview mode toggles all pages to be resolved in a blocking manner.
    //
1278
    // * Non-dynamic pages should block (though this is an impossible
1279 1280
    //   case in production).
    //
1281 1282
    // * Dynamic pages should return their skeleton if not defined in
    //   getStaticPaths, then finish the data request on the client-side.
1283
    //
J
Joe Haddad 已提交
1284
    if (
1285
      fallbackMode !== 'blocking' &&
1286
      ssgCacheKey &&
1287 1288 1289
      !didRespond &&
      !isPreviewMode &&
      isDynamicPathname &&
1290 1291
      // Development should trigger fallback when the path is not in
      // `getStaticPaths`
1292 1293
      (isProduction ||
        !staticPaths ||
1294 1295 1296 1297 1298
        // static paths always includes locale so make sure it's prefixed
        // with it
        !staticPaths.includes(
          `${locale ? '/' + locale : ''}${resolvedUrlPathname}`
        ))
J
Joe Haddad 已提交
1299
    ) {
1300 1301 1302 1303 1304
      if (
        // In development, fall through to render to handle missing
        // getStaticPaths.
        (isProduction || staticPaths) &&
        // When fallback isn't present, abort this render so we 404
1305
        fallbackMode !== 'static'
1306
      ) {
1307
        throw new NoFallbackError()
1308 1309
      }

1310 1311
      if (!isDataReq) {
        let html: string
1312

1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324
        // 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
1325 1326
        }

1327 1328 1329 1330 1331 1332
        sendPayload(req, res, html, 'html', {
          generateEtags: this.renderOpts.generateEtags,
          poweredByHeader: this.renderOpts.poweredByHeader,
        })
        return null
      }
1333 1334
    }

1335 1336 1337
    const {
      isOrigin,
      value: { html, pageData, sprRevalidate },
1338
    } = await doRender()
1339 1340
    let resHtml = html
    if (!isResSent(res) && (isSSG || isDataReq || isServerProps)) {
1341
      sendPayload(
1342
        req,
1343 1344
        res,
        isDataReq ? JSON.stringify(pageData) : html,
1345
        isDataReq ? 'json' : 'html',
1346 1347 1348 1349
        {
          generateEtags: this.renderOpts.generateEtags,
          poweredByHeader: this.renderOpts.poweredByHeader,
        },
1350
        !this.renderOpts.dev || (isServerProps && !isDataReq)
1351 1352
          ? {
              private: isPreviewMode,
1353
              stateful: !isSSG,
1354 1355
              revalidate: sprRevalidate,
            }
1356
          : undefined
1357
      )
1358
      resHtml = null
1359
    }
J
JJ Kasper 已提交
1360

1361
    // Update the cache if the head request and cacheable
1362
    if (isOrigin && ssgCacheKey) {
1363 1364 1365 1366 1367
      await this.incrementalCache.set(
        ssgCacheKey,
        { html: html!, pageData },
        sprRevalidate
      )
1368 1369
    }

1370
    return resHtml
1371 1372
  }

1373
  public async renderToHTML(
J
Joe Haddad 已提交
1374 1375 1376
    req: IncomingMessage,
    res: ServerResponse,
    pathname: string,
1377
    query: ParsedUrlQuery = {}
J
Joe Haddad 已提交
1378
  ): Promise<string | null> {
1379 1380 1381
    try {
      const result = await this.findPageComponents(pathname, query)
      if (result) {
1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393
        try {
          return await this.renderToHTMLWithComponents(
            req,
            res,
            pathname,
            result,
            { ...this.renderOpts }
          )
        } catch (err) {
          if (!(err instanceof NoFallbackError)) {
            throw err
          }
1394
        }
1395
      }
J
Joe Haddad 已提交
1396

1397 1398 1399 1400 1401 1402
      if (this.dynamicRoutes) {
        for (const dynamicRoute of this.dynamicRoutes) {
          const params = dynamicRoute.match(pathname)
          if (!params) {
            continue
          }
J
Joe Haddad 已提交
1403

1404
          const dynamicRouteResult = await this.findPageComponents(
1405 1406 1407 1408
            dynamicRoute.page,
            query,
            params
          )
1409
          if (dynamicRouteResult) {
1410 1411 1412 1413 1414
            try {
              return await this.renderToHTMLWithComponents(
                req,
                res,
                dynamicRoute.page,
1415
                dynamicRouteResult,
1416 1417 1418 1419 1420 1421
                { ...this.renderOpts, params }
              )
            } catch (err) {
              if (!(err instanceof NoFallbackError)) {
                throw err
              }
1422
            }
J
Joe Haddad 已提交
1423 1424
          }
        }
1425 1426 1427
      }
    } catch (err) {
      this.logError(err)
1428 1429 1430 1431 1432

      if (err && err.code === 'DECODE_FAILED') {
        res.statusCode = 400
        return await this.renderErrorToHTML(err, req, res, pathname, query)
      }
1433 1434 1435 1436 1437 1438
      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 已提交
1439 1440
  }

J
Joe Haddad 已提交
1441 1442 1443 1444 1445
  public async renderError(
    err: Error | null,
    req: IncomingMessage,
    res: ServerResponse,
    pathname: string,
1446
    query: ParsedUrlQuery = {}
J
Joe Haddad 已提交
1447 1448 1449
  ): Promise<void> {
    res.setHeader(
      'Cache-Control',
1450
      'no-cache, no-store, max-age=0, must-revalidate'
J
Joe Haddad 已提交
1451
    )
N
Naoyuki Kanezawa 已提交
1452
    const html = await this.renderErrorToHTML(err, req, res, pathname, query)
1453
    if (html === null) {
1454 1455
      return
    }
1456
    return this.sendHTML(req, res, html)
N
nkzawa 已提交
1457 1458
  }

1459 1460 1461 1462 1463 1464 1465 1466 1467
  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 已提交
1468 1469 1470 1471 1472
  public async renderErrorToHTML(
    err: Error | null,
    req: IncomingMessage,
    res: ServerResponse,
    _pathname: string,
1473
    query: ParsedUrlQuery = {}
J
Joe Haddad 已提交
1474
  ) {
1475
    let result: null | FindComponentsResult = null
1476

1477 1478 1479
    const is404 = res.statusCode === 404
    let using404Page = false

1480
    // use static 404 page if available and is 404 response
1481
    if (is404) {
1482 1483
      result = await this.findPageComponents('/404')
      using404Page = result !== null
1484 1485 1486 1487 1488 1489
    }

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

1490 1491 1492
    if (
      process.env.NODE_ENV !== 'production' &&
      !using404Page &&
1493 1494
      (await this.hasPage('/_error')) &&
      !(await this.hasPage('/404'))
1495 1496 1497 1498
    ) {
      this.customErrorNo404Warn()
    }

1499
    let html: string | null
1500
    try {
1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511
      try {
        html = await this.renderToHTMLWithComponents(
          req,
          res,
          using404Page ? '/404' : '/_error',
          result!,
          {
            ...this.renderOpts,
            err,
          }
        )
1512 1513
      } catch (maybeFallbackError) {
        if (maybeFallbackError instanceof NoFallbackError) {
1514
          throw new Error('invariant: failed to render error page')
1515
        }
1516
        throw maybeFallbackError
1517
      }
1518 1519
    } catch (renderToHtmlError) {
      console.error(renderToHtmlError)
1520 1521 1522 1523
      res.statusCode = 500
      html = 'Internal Server Error'
    }
    return html
N
Naoyuki Kanezawa 已提交
1524 1525
  }

J
Joe Haddad 已提交
1526 1527 1528
  public async render404(
    req: IncomingMessage,
    res: ServerResponse,
1529
    parsedUrl?: UrlWithParsedQuery
J
Joe Haddad 已提交
1530
  ): Promise<void> {
1531 1532
    const url: any = req.url
    const { pathname, query } = parsedUrl ? parsedUrl : parseUrl(url, true)
N
Naoyuki Kanezawa 已提交
1533
    res.statusCode = 404
1534
    return this.renderError(null, req, res, pathname!, query)
N
Naoyuki Kanezawa 已提交
1535
  }
N
Naoyuki Kanezawa 已提交
1536

J
Joe Haddad 已提交
1537 1538 1539 1540
  public async serveStatic(
    req: IncomingMessage,
    res: ServerResponse,
    path: string,
1541
    parsedUrl?: UrlWithParsedQuery
J
Joe Haddad 已提交
1542
  ): Promise<void> {
A
Arunoda Susiripala 已提交
1543
    if (!this.isServeableUrl(path)) {
1544
      return this.render404(req, res, parsedUrl)
A
Arunoda Susiripala 已提交
1545 1546
    }

1547 1548 1549 1550 1551 1552
    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 已提交
1553
    try {
1554
      await serveStatic(req, res, path)
N
Naoyuki Kanezawa 已提交
1555
    } catch (err) {
T
Tim Neutkens 已提交
1556
      if (err.code === 'ENOENT' || err.statusCode === 404) {
1557
        this.render404(req, res, parsedUrl)
1558 1559 1560
      } else if (err.statusCode === 412) {
        res.statusCode = 412
        return this.renderError(err, req, res, path)
N
Naoyuki Kanezawa 已提交
1561 1562 1563 1564 1565 1566
      } else {
        throw err
      }
    }
  }

1567 1568 1569 1570 1571 1572 1573 1574 1575
  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 已提交
1576
      userFilesStatic = recursiveReadDirSync(pathUserFilesStatic).map((f) =>
1577 1578 1579 1580 1581 1582
        join('.', 'static', f)
      )
    }

    let userFilesPublic: string[] = []
    if (this.publicDir && fs.existsSync(this.publicDir)) {
J
Joe Haddad 已提交
1583
      userFilesPublic = recursiveReadDirSync(this.publicDir).map((f) =>
1584 1585 1586 1587 1588 1589 1590
        join('.', 'public', f)
      )
    }

    let nextFilesStatic: string[] = []
    nextFilesStatic = recursiveReadDirSync(
      join(this.distDir, 'static')
J
Joe Haddad 已提交
1591
    ).map((f) => join('.', relative(this.dir, this.distDir), 'static', f))
1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625

    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 已提交
1626
    if (
1627 1628 1629
      (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 已提交
1630 1631 1632 1633
    ) {
      return false
    }

1634 1635 1636 1637
    // Check against the real filesystem paths
    const filesystemUrls = this.getFilesystemPaths()
    const resolved = relative(this.dir, untrustedFilePath)
    return filesystemUrls.has(resolved)
A
Arunoda Susiripala 已提交
1638 1639
  }

1640
  protected readBuildId(): string {
1641 1642 1643 1644 1645
    const buildIdFile = join(this.distDir, BUILD_ID_FILE)
    try {
      return fs.readFileSync(buildIdFile, 'utf8').trim()
    } catch (err) {
      if (!fs.existsSync(buildIdFile)) {
J
Joe Haddad 已提交
1646
        throw new Error(
1647
          `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 已提交
1648
        )
1649 1650 1651
      }

      throw err
1652
    }
1653
  }
1654

1655
  protected get _isLikeServerless(): boolean {
1656 1657
    return isTargetLikeServerless(this.nextConfig.target)
  }
1658
}
1659

1660 1661 1662 1663
function prepareServerlessUrl(
  req: IncomingMessage,
  query: ParsedUrlQuery
): void {
1664 1665 1666 1667 1668 1669 1670 1671 1672 1673
  const curUrl = parseUrl(req.url!, true)
  req.url = formatUrl({
    ...curUrl,
    search: undefined,
    query: {
      ...curUrl.query,
      ...query,
    },
  })
}
1674 1675

class NoFallbackError extends Error {}