next-server.ts 45.3 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'
J
Joe Haddad 已提交
43
import { apiResolver, tryGetPreviewData, __ApiPreviewProps } from './api-utils'
44
import loadConfig, { isTargetLikeServerless } from './config'
45
import pathMatch from '../lib/router/utils/path-match'
J
Joe Haddad 已提交
46
import { recursiveReadDirSync } from './lib/recursive-readdir-sync'
47
import { loadComponents, LoadComponentsReturnType } from './load-components'
J
Joe Haddad 已提交
48
import { normalizePagePath } from './normalize-page-path'
49
import { RenderOpts, RenderOptsPartial, renderToHTML } from './render'
P
Prateek Bhatnagar 已提交
50
import { getPagePath, requireFontManifest } from './require'
51 52 53
import Router, {
  DynamicRoutes,
  PageChecker,
J
Joe Haddad 已提交
54 55 56
  Params,
  route,
  Route,
57
} from './router'
58
import prepareDestination from '../lib/router/utils/prepare-destination'
59
import { sendPayload } from './send-payload'
J
Joe Haddad 已提交
60
import { serveStatic } from './serve-static'
61
import { IncrementalCache } from './incremental-cache'
62
import { execOnce } from '../lib/utils'
63
import { isBlockedPage } from './utils'
64
import { compile as compilePathToRegex } from 'next/dist/compiled/path-to-regexp'
65
import { loadEnvConfig } from '../../lib/load-env-config'
66
import './node-polyfill-fetch'
J
Jan Potoms 已提交
67
import { PagesManifest } from '../../build/webpack/plugins/pages-manifest-plugin'
68
import { removePathTrailingSlash } from '../../client/normalize-trailing-slash'
69
import getRouteFromAssetPath from '../lib/router/utils/get-route-from-asset-path'
P
Prateek Bhatnagar 已提交
70
import { FontManifest } from './font-utils'
71
import { denormalizePagePath } from './denormalize-page-path'
J
JJ Kasper 已提交
72 73

const getCustomRouteMatcher = pathMatch(true)
74 75 76

type NextConfig = any

77 78 79 80 81 82
type Middleware = (
  req: IncomingMessage,
  res: ServerResponse,
  next: (err?: Error) => void
) => void

83 84 85 86 87
type FindComponentsResult = {
  components: LoadComponentsReturnType
  query: ParsedUrlQuery
}

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

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

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

151
    this.nextConfig = loadConfig(phase, this.dir, conf)
152
    this.distDir = join(this.dir, this.nextConfig.distDir)
153
    this.publicDir = join(this.dir, CLIENT_PUBLIC_FILES_PATH)
154
    this.hasStaticDir = fs.existsSync(join(this.dir, 'static'))
T
Tim Neutkens 已提交
155

156 157
    // Only serverRuntimeConfig needs the default
    // publicRuntimeConfig gets it's default in client/index.js
J
Joe Haddad 已提交
158 159 160 161 162
    const {
      serverRuntimeConfig = {},
      publicRuntimeConfig,
      assetPrefix,
      generateEtags,
163
      compress,
J
Joe Haddad 已提交
164
    } = this.nextConfig
165

T
Tim Neutkens 已提交
166
    this.buildId = this.readBuildId()
167

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

185 186
    // Only the `publicRuntimeConfig` key is exposed to the client side
    // It'll be rendered as part of __NEXT_DATA__ on the client side
187
    if (Object.keys(publicRuntimeConfig).length > 0) {
188
      this.renderOpts.runtimeConfig = publicRuntimeConfig
189 190
    }

191
    if (compress && this.nextConfig.target === 'server') {
192 193 194
      this.compression = compression() as Middleware
    }

195
    // Initialize next/config with the environment configuration
196 197 198 199
    envConfig.setConfig({
      serverRuntimeConfig,
      publicRuntimeConfig,
    })
200

201 202 203 204 205 206 207 208 209 210
    this.serverBuildDir = join(
      this.distDir,
      this._isLikeServerless ? SERVERLESS_DIRECTORY : SERVER_DIRECTORY
    )
    const pagesManifestPath = join(this.serverBuildDir, PAGES_MANIFEST)

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

211
    this.customRoutes = this.getCustomRoutes()
J
JJ Kasper 已提交
212
    this.router = new Router(this.generateRoutes())
213
    this.setAssetPrefix(assetPrefix)
J
JJ Kasper 已提交
214

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

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

    /**
     * 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)
    }
247 248 249
    if (this.renderOpts.optimizeImages) {
      process.env.__NEXT_OPTIMIZE_IMAGES = JSON.stringify(true)
    }
N
Naoyuki Kanezawa 已提交
250
  }
N
nkzawa 已提交
251

252
  protected currentPhase(): string {
253
    return PHASE_PRODUCTION_SERVER
254 255
  }

256 257 258 259
  private logError(err: Error): void {
    if (this.onErrorMiddleware) {
      this.onErrorMiddleware({ err })
    }
260
    if (this.quiet) return
261
    console.error(err)
262 263
  }

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

275 276 277
    // 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 已提交
278
    }
279

280
    const { basePath } = this.nextConfig
281

282 283 284 285 286
    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 已提交
287 288
    }

289
    res.statusCode = 200
290 291 292
    try {
      return await this.run(req, res, parsedUrl)
    } catch (err) {
J
Joe Haddad 已提交
293 294 295
      this.logError(err)
      res.statusCode = 500
      res.end('Internal Server Error')
296
    }
297 298
  }

299
  public getRequestHandler() {
300
    return this.handleRequest.bind(this)
N
nkzawa 已提交
301 302
  }

303
  public setAssetPrefix(prefix?: string): void {
304
    this.renderOpts.assetPrefix = prefix ? prefix.replace(/\/$/, '') : ''
305 306
  }

307
  // Backwards compatibility
308
  public async prepare(): Promise<void> {}
N
nkzawa 已提交
309

T
Tim Neutkens 已提交
310
  // Backwards compatibility
311
  protected async close(): Promise<void> {}
T
Tim Neutkens 已提交
312

313
  protected setImmutableAssetCacheControl(res: ServerResponse): void {
T
Tim Neutkens 已提交
314
    res.setHeader('Cache-Control', 'public, max-age=31536000, immutable')
N
nkzawa 已提交
315 316
  }

317
  protected getCustomRoutes(): CustomRoutes {
J
JJ Kasper 已提交
318 319 320
    return require(join(this.distDir, ROUTES_MANIFEST))
  }

321 322 323 324
  private _cachedPreviewManifest: PrerenderManifest | undefined
  protected getPrerenderManifest(): PrerenderManifest {
    if (this._cachedPreviewManifest) {
      return this._cachedPreviewManifest
J
Joe Haddad 已提交
325
    }
326 327 328 329 330 331
    const manifest = require(join(this.distDir, PRERENDER_MANIFEST))
    return (this._cachedPreviewManifest = manifest)
  }

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

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

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

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

J
Joe Haddad 已提交
383 384 385
          if (
            params.path[0] === CLIENT_STATIC_FILES_RUNTIME ||
            params.path[0] === 'chunks' ||
386 387
            params.path[0] === 'css' ||
            params.path[0] === 'media' ||
388
            params.path[0] === this.buildId ||
389
            params.path[0] === 'pages' ||
390
            params.path[1] === 'pages'
J
Joe Haddad 已提交
391
          ) {
T
Tim Neutkens 已提交
392
            this.setImmutableAssetCacheControl(res)
393
          }
J
Joe Haddad 已提交
394 395 396
          const p = join(
            this.distDir,
            CLIENT_STATIC_FILES_PATH,
397
            ...(params.path || [])
J
Joe Haddad 已提交
398
          )
399
          await this.serveStatic(req, res, p, parsedUrl)
400 401 402
          return {
            finished: true,
          }
403
        },
404
      },
J
JJ Kasper 已提交
405 406
      {
        match: route('/_next/data/:path*'),
407 408
        type: 'route',
        name: '_next/data catchall',
J
JJ Kasper 已提交
409
        fn: async (req, res, params, _parsedUrl) => {
J
JJ Kasper 已提交
410 411 412
          // 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) {
413 414 415 416
            await this.render404(req, res, _parsedUrl)
            return {
              finished: true,
            }
J
JJ Kasper 已提交
417 418 419 420 421 422
          }
          // 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')) {
423 424 425 426
            await this.render404(req, res, _parsedUrl)
            return {
              finished: true,
            }
J
JJ Kasper 已提交
427 428 429
          }

          // re-create page's pathname
430
          const pathname = getRouteFromAssetPath(
431
            `/${params.path.join('/')}`,
432 433
            '.json'
          )
J
JJ Kasper 已提交
434

J
JJ Kasper 已提交
435
          const parsedUrl = parseUrl(pathname, true)
436

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

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

471 472 473 474
    const getCustomRoute = (r: Rewrite | Redirect | Header, type: RouteType) =>
      ({
        ...r,
        type,
475
        match: getCustomRouteMatcher(`${getCustomRouteBasePath(r)}${r.source}`),
476 477 478 479 480 481 482
        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
483
      }
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504

      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}`
            )
        }
505
      }
506 507 508 509 510 511 512 513 514 515 516 517
      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)
518
    }
519

520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
    // 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)
535
            }
536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553
            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,
554 555 556
            parsedUrl.query,
            false,
            getCustomRouteBasePath(redirectRoute)
557
          )
558 559 560 561 562 563 564 565

          const { query } = parsedDestination
          delete parsedDestination.query

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

566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587
          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 {
588
        ...rewriteRoute,
589 590 591 592 593 594 595 596 597
        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,
598 599
            true,
            getCustomRouteBasePath(rewriteRoute)
600
          )
601

602 603
          // external rewrite, proxy it
          if (parsedDestination.protocol) {
604 605 606 607 608 609 610 611 612
            const { query } = parsedDestination
            delete parsedDestination.query
            parsedDestination.search = stringifyQs(
              query,
              undefined,
              undefined,
              { encodeURIComponent: (str) => str }
            )

613 614 615 616 617 618 619 620 621 622 623
            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)
            })
624 625 626
            return {
              finished: true,
            }
627 628
          }
          ;(req as any)._nextRewroteUrl = newUrl
629 630
          ;(req as any)._nextDidRewrite =
            (req as any)._nextRewroteUrl !== req.url
631

632 633 634 635 636 637 638 639
          return {
            finished: false,
            pathname: newUrl,
            query: parsedDestination.query,
          }
        },
      } as Route
    })
640 641 642 643 644 645

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

J
Jan Potoms 已提交
651
        // next.js core assumes page path without trailing slash
652
        pathname = removePathTrailingSlash(pathname)
J
Jan Potoms 已提交
653

654
        if (params?.path?.[0] === 'api') {
655 656 657
          const handled = await this.handleApiRequest(
            req as NextApiRequest,
            res as NextApiResponse,
658
            pathname,
659
            query
660 661 662 663 664 665 666
          )
          if (handled) {
            return { finished: true }
          }
        }

        await this.render(req, res, pathname, query, parsedUrl)
667 668 669 670
        return {
          finished: true,
        }
      },
671
    }
672

673
    const { useFileSystemPublicRoutes } = this.nextConfig
J
Joe Haddad 已提交
674

675 676
    if (useFileSystemPublicRoutes) {
      this.dynamicRoutes = this.getDynamicRoutes()
677
    }
N
nkzawa 已提交
678

679
    return {
680
      headers,
681
      fsRoutes,
682 683
      rewrites,
      redirects,
684
      catchAllRoute,
685
      useFileSystemPublicRoutes,
686
      dynamicRoutes: this.dynamicRoutes,
687
      basePath: this.nextConfig.basePath,
688 689
      pageChecker: this.hasPage.bind(this),
    }
T
Tim Neutkens 已提交
690 691
  }

692
  private async getPagePath(pathname: string): Promise<string> {
693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709
    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
  }

710 711 712 713 714
  protected async _beforeCatchAllRender(
    _req: IncomingMessage,
    _res: ServerResponse,
    _params: Params,
    _parsedUrl: UrlWithParsedQuery
715
  ): Promise<boolean> {
716 717 718
    return false
  }

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

L
Lukáš Huvar 已提交
722 723 724 725 726 727
  /**
   * Resolves `API` request, in development builds on demand
   * @param req http request
   * @param res http response
   * @param pathname path of request
   */
J
Joe Haddad 已提交
728
  private async handleApiRequest(
729 730
    req: IncomingMessage,
    res: ServerResponse,
731 732
    pathname: string,
    query: ParsedUrlQuery
733
  ): Promise<boolean> {
734
    let page = pathname
L
Lukáš Huvar 已提交
735
    let params: Params | boolean = false
736
    let pageFound = await this.hasPage(page)
J
JJ Kasper 已提交
737

738
    if (!pageFound && this.dynamicRoutes) {
L
Lukáš Huvar 已提交
739 740
      for (const dynamicRoute of this.dynamicRoutes) {
        params = dynamicRoute.match(pathname)
741
        if (dynamicRoute.page.startsWith('/api') && params) {
742 743
          page = dynamicRoute.page
          pageFound = true
L
Lukáš Huvar 已提交
744 745 746 747 748
          break
        }
      }
    }

749
    if (!pageFound) {
750
      return false
J
JJ Kasper 已提交
751
    }
752 753 754 755
    // Make sure the page is built before getting the path
    // or else it won't be in the manifest yet
    await this.ensureApiPage(page)

756 757 758 759 760 761 762 763 764 765
    let builtPagePath
    try {
      builtPagePath = await this.getPagePath(page)
    } catch (err) {
      if (err.code === 'ENOENT') {
        return false
      }
      throw err
    }

766
    const pageModule = require(builtPagePath)
767
    query = { ...query, ...params }
J
JJ Kasper 已提交
768

769
    if (!this.renderOpts.dev && this._isLikeServerless) {
770
      if (typeof pageModule.default === 'function') {
771
        prepareServerlessUrl(req, query)
772 773
        await pageModule.default(req, res)
        return true
J
JJ Kasper 已提交
774 775 776
      }
    }

J
Joe Haddad 已提交
777 778 779 780 781
    await apiResolver(
      req,
      res,
      query,
      pageModule,
782
      this.renderOpts.previewProps,
783
      false,
J
Joe Haddad 已提交
784 785
      this.onErrorMiddleware
    )
786
    return true
L
Lukáš Huvar 已提交
787 788
  }

789
  protected generatePublicRoutes(): Route[] {
790
    const publicFiles = new Set(
791 792 793
      recursiveReadDirSync(this.publicDir).map((p) =>
        encodeURI(p.replace(/\\/g, '/'))
      )
794 795 796 797 798 799 800
    )

    return [
      {
        match: route('/:path*'),
        name: 'public folder catchall',
        fn: async (req, res, params, parsedUrl) => {
801
          const pathParts: string[] = params.path || []
802 803 804 805 806 807 808 809
          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()
          }

810
          const path = `/${pathParts.join('/')}`
811 812 813 814 815

          if (publicFiles.has(path)) {
            await this.serveStatic(
              req,
              res,
816
              join(this.publicDir, ...pathParts),
817 818
              parsedUrl
            )
819 820 821
            return {
              finished: true,
            }
822 823 824 825 826 827 828
          }
          return {
            finished: false,
          }
        },
      } as Route,
    ]
829 830
  }

831
  protected getDynamicRoutes() {
832 833
    return getSortedRoutes(Object.keys(this.pagesManifest!))
      .filter(isDynamicRoute)
J
Joe Haddad 已提交
834
      .map((page) => ({
835 836 837
        page,
        match: getRouteMatcher(getRouteRegex(page)),
      }))
J
Joe Haddad 已提交
838 839
  }

840
  private handleCompression(req: IncomingMessage, res: ServerResponse): void {
841 842 843 844 845
    if (this.compression) {
      this.compression(req, res, () => {})
    }
  }

846
  protected async run(
J
Joe Haddad 已提交
847 848
    req: IncomingMessage,
    res: ServerResponse,
849
    parsedUrl: UrlWithParsedQuery
850
  ): Promise<void> {
851 852
    this.handleCompression(req, res)

853
    try {
854 855
      const matched = await this.router.execute(req, res, parsedUrl)
      if (matched) {
856 857 858 859 860 861 862 863
        return
      }
    } catch (err) {
      if (err.code === 'DECODE_FAILED') {
        res.statusCode = 400
        return this.renderError(null, req, res, '/_error', {})
      }
      throw err
864 865
    }

866
    await this.render404(req, res, parsedUrl)
N
nkzawa 已提交
867 868
  }

869
  protected async sendHTML(
J
Joe Haddad 已提交
870 871
    req: IncomingMessage,
    res: ServerResponse,
872
    html: string
873
  ): Promise<void> {
T
Tim Neutkens 已提交
874
    const { generateEtags, poweredByHeader } = this.renderOpts
875 876 877 878
    return sendPayload(req, res, html, 'html', {
      generateEtags,
      poweredByHeader,
    })
879 880
  }

J
Joe Haddad 已提交
881 882 883 884 885
  public async render(
    req: IncomingMessage,
    res: ServerResponse,
    pathname: string,
    query: ParsedUrlQuery = {},
886
    parsedUrl?: UrlWithParsedQuery
J
Joe Haddad 已提交
887
  ): Promise<void> {
888 889 890 891 892 893
    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`
      )
    }

894 895 896 897 898 899 900 901 902 903
    if (
      this.renderOpts.customServer &&
      pathname === '/index' &&
      !(await this.hasPage('/index'))
    ) {
      // maintain backwards compatibility for custom server
      // (see custom-server integration tests)
      pathname = '/'
    }

904
    const url: any = req.url
905

906 907 908 909
    // 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
910
    if (
911 912 913
      !query._nextDataReq &&
      (url.match(/^\/_next\//) ||
        (this.hasStaticDir && url.match(/^\/static\//)))
914
    ) {
915 916 917
      return this.handleRequest(req, res, parsedUrl)
    }

918
    if (isBlockedPage(pathname)) {
919
      return this.render404(req, res, parsedUrl)
920 921
    }

922
    const html = await this.renderToHTML(req, res, pathname, query)
923 924
    // Request was ended by the user
    if (html === null) {
925 926 927
      return
    }

928
    return this.sendHTML(req, res, html)
N
Naoyuki Kanezawa 已提交
929
  }
N
nkzawa 已提交
930

J
Joe Haddad 已提交
931
  private async findPageComponents(
J
Joe Haddad 已提交
932
    pathname: string,
933 934 935 936 937 938 939 940 941
    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 已提交
942
      try {
943
        const components = await loadComponents(
J
Joe Haddad 已提交
944
          this.distDir,
945 946
          pagePath!,
          !this.renderOpts.dev && this._isLikeServerless
J
Joe Haddad 已提交
947
        )
948 949 950
        return {
          components,
          query: {
951
            ...(components.getStaticProps
952
              ? { _nextDataReq: query._nextDataReq, amp: query.amp }
953 954 955 956
              : query),
            ...(params || {}),
          },
        }
J
JJ Kasper 已提交
957 958 959 960
      } catch (err) {
        if (err.code !== 'ENOENT') throw err
      }
    }
961
    return null
J
Joe Haddad 已提交
962 963
  }

964
  protected async getStaticPaths(
965 966 967
    pathname: string
  ): Promise<{
    staticPaths: string[] | undefined
968
    fallbackMode: 'static' | 'blocking' | false
969
  }> {
970 971 972 973 974
    // `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.
975 976
    const fallbackField = this.getPrerenderManifest().dynamicRoutes[pathname]
      .fallback
977

978 979 980 981 982 983 984 985 986
    return {
      staticPaths,
      fallbackMode:
        typeof fallbackField === 'string'
          ? 'static'
          : fallbackField === null
          ? 'blocking'
          : false,
    }
987 988
  }

J
Joe Haddad 已提交
989 990 991 992
  private async renderToHTMLWithComponents(
    req: IncomingMessage,
    res: ServerResponse,
    pathname: string,
993
    { components, query }: FindComponentsResult,
994
    opts: RenderOptsPartial
995
  ): Promise<string | null> {
996
    // we need to ensure the status code if /404 is visited directly
997
    if (pathname === '/404') {
998 999 1000
      res.statusCode = 404
    }

J
JJ Kasper 已提交
1001
    // handle static page
1002 1003
    if (typeof components.Component === 'string') {
      return components.Component
J
Joe Haddad 已提交
1004 1005
    }

J
JJ Kasper 已提交
1006 1007
    // check request state
    const isLikeServerless =
1008 1009
      typeof components.Component === 'object' &&
      typeof (components.Component as any).renderReqToHTML === 'function'
1010 1011 1012
    const isSSG = !!components.getStaticProps
    const isServerProps = !!components.getServerSideProps
    const hasStaticPaths = !!components.getStaticPaths
1013

1014 1015 1016 1017
    if (!query.amp) {
      delete query.amp
    }

1018
    // Toggle whether or not this is a Data request
1019
    const isDataReq = !!query._nextDataReq && (isSSG || isServerProps)
1020 1021
    delete query._nextDataReq

1022 1023 1024 1025 1026 1027 1028 1029
    let previewData: string | false | object | undefined
    let isPreviewMode = false

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

1030 1031 1032
    // 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
1033 1034 1035
    let urlPathname = parseUrl(req.url || '').pathname || '/'

    let resolvedUrlPathname = (req as any)._nextRewroteUrl
1036
      ? (req as any)._nextRewroteUrl
1037
      : urlPathname
1038

1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049
    resolvedUrlPathname = removePathTrailingSlash(resolvedUrlPathname)
    urlPathname = removePathTrailingSlash(urlPathname)

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

1051 1052
    // remove /_next/data prefix from urlPathname so it matches
    // for direct page visit and /_next/data visit
1053 1054 1055
    if (isDataReq) {
      resolvedUrlPathname = stripNextDataPath(resolvedUrlPathname)
      urlPathname = stripNextDataPath(urlPathname)
1056 1057
    }

1058 1059 1060
    const ssgCacheKey =
      isPreviewMode || !isSSG
        ? undefined // Preview mode bypasses the cache
1061
        : `${resolvedUrlPathname}${query.amp ? '.amp' : ''}`
J
JJ Kasper 已提交
1062 1063

    // Complete the response with cached data if its present
1064 1065 1066
    const cachedData = ssgCacheKey
      ? await this.incrementalCache.get(ssgCacheKey)
      : undefined
1067

J
JJ Kasper 已提交
1068
    if (cachedData) {
1069
      const data = isDataReq
J
JJ Kasper 已提交
1070 1071 1072
        ? JSON.stringify(cachedData.pageData)
        : cachedData.html

1073
      sendPayload(
1074
        req,
J
JJ Kasper 已提交
1075 1076
        res,
        data,
1077
        isDataReq ? 'json' : 'html',
1078 1079 1080 1081
        {
          generateEtags: this.renderOpts.generateEtags,
          poweredByHeader: this.renderOpts.poweredByHeader,
        },
1082 1083 1084 1085 1086 1087 1088 1089 1090
        !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,
            }
1091
          : undefined
J
JJ Kasper 已提交
1092 1093 1094 1095 1096 1097
      )

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

J
JJ Kasper 已提交
1100
    // If we're here, that means data is missing or it's stale.
1101 1102 1103 1104 1105 1106
    const maybeCoalesceInvoke = ssgCacheKey
      ? (fn: any) => withCoalescedInvoke(fn).bind(null, ssgCacheKey, [])
      : (fn: any) => async () => {
          const value = await fn()
          return { isOrigin: true, value }
        }
J
JJ Kasper 已提交
1107

1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123
    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 已提交
1124 1125 1126 1127
            'passthrough',
            {
              fontManifest: this.renderOpts.fontManifest,
            }
1128
          )
J
JJ Kasper 已提交
1129

1130 1131 1132 1133
          html = renderResult.html
          pageData = renderResult.renderOpts.pageData
          sprRevalidate = renderResult.renderOpts.revalidate
        } else {
1134 1135 1136 1137 1138 1139 1140
          const origQuery = parseUrl(req.url || '', true).query
          const resolvedUrl = formatUrl({
            pathname: resolvedUrlPathname,
            // make sure to only add query values from original URL
            query: origQuery,
          })

1141 1142 1143 1144
          const renderOpts: RenderOpts = {
            ...components,
            ...opts,
            isDataReq,
1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156
            resolvedUrl,
            // 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,
1157
          }
1158

1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170
          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 已提交
1171 1172
        }

1173
        return { html, pageData, sprRevalidate }
J
JJ Kasper 已提交
1174
      }
1175
    )
J
JJ Kasper 已提交
1176

1177
    const isProduction = !this.renderOpts.dev
J
Joe Haddad 已提交
1178
    const isDynamicPathname = isDynamicRoute(pathname)
1179
    const didRespond = isResSent(res)
1180

1181
    const { staticPaths, fallbackMode } = hasStaticPaths
1182
      ? await this.getStaticPaths(pathname)
1183
      : { staticPaths: undefined, fallbackMode: false }
1184

1185 1186 1187 1188 1189
    // When we did not respond from cache, we need to choose to block on
    // rendering or return a skeleton.
    //
    // * Data requests always block.
    //
1190 1191
    // * Blocking mode fallback always blocks.
    //
1192 1193
    // * Preview mode toggles all pages to be resolved in a blocking manner.
    //
1194
    // * Non-dynamic pages should block (though this is an impossible
1195 1196
    //   case in production).
    //
1197 1198
    // * Dynamic pages should return their skeleton if not defined in
    //   getStaticPaths, then finish the data request on the client-side.
1199
    //
J
Joe Haddad 已提交
1200
    if (
1201
      fallbackMode !== 'blocking' &&
1202
      ssgCacheKey &&
1203 1204 1205
      !didRespond &&
      !isPreviewMode &&
      isDynamicPathname &&
1206 1207
      // Development should trigger fallback when the path is not in
      // `getStaticPaths`
1208 1209 1210
      (isProduction ||
        !staticPaths ||
        !staticPaths.includes(resolvedUrlPathname))
J
Joe Haddad 已提交
1211
    ) {
1212 1213 1214 1215 1216
      if (
        // In development, fall through to render to handle missing
        // getStaticPaths.
        (isProduction || staticPaths) &&
        // When fallback isn't present, abort this render so we 404
1217
        fallbackMode !== 'static'
1218
      ) {
1219
        throw new NoFallbackError()
1220 1221
      }

1222 1223
      if (!isDataReq) {
        let html: string
1224

1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236
        // 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
1237 1238
        }

1239 1240 1241 1242 1243 1244
        sendPayload(req, res, html, 'html', {
          generateEtags: this.renderOpts.generateEtags,
          poweredByHeader: this.renderOpts.poweredByHeader,
        })
        return null
      }
1245 1246
    }

1247 1248 1249
    const {
      isOrigin,
      value: { html, pageData, sprRevalidate },
1250
    } = await doRender()
1251 1252
    let resHtml = html
    if (!isResSent(res) && (isSSG || isDataReq || isServerProps)) {
1253
      sendPayload(
1254
        req,
1255 1256
        res,
        isDataReq ? JSON.stringify(pageData) : html,
1257
        isDataReq ? 'json' : 'html',
1258 1259 1260 1261
        {
          generateEtags: this.renderOpts.generateEtags,
          poweredByHeader: this.renderOpts.poweredByHeader,
        },
1262
        !this.renderOpts.dev || (isServerProps && !isDataReq)
1263 1264
          ? {
              private: isPreviewMode,
1265
              stateful: !isSSG,
1266 1267
              revalidate: sprRevalidate,
            }
1268
          : undefined
1269
      )
1270
      resHtml = null
1271
    }
J
JJ Kasper 已提交
1272

1273
    // Update the cache if the head request and cacheable
1274
    if (isOrigin && ssgCacheKey) {
1275 1276 1277 1278 1279
      await this.incrementalCache.set(
        ssgCacheKey,
        { html: html!, pageData },
        sprRevalidate
      )
1280 1281
    }

1282
    return resHtml
1283 1284
  }

1285
  public async renderToHTML(
J
Joe Haddad 已提交
1286 1287 1288
    req: IncomingMessage,
    res: ServerResponse,
    pathname: string,
1289
    query: ParsedUrlQuery = {}
J
Joe Haddad 已提交
1290
  ): Promise<string | null> {
1291 1292 1293
    try {
      const result = await this.findPageComponents(pathname, query)
      if (result) {
1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305
        try {
          return await this.renderToHTMLWithComponents(
            req,
            res,
            pathname,
            result,
            { ...this.renderOpts }
          )
        } catch (err) {
          if (!(err instanceof NoFallbackError)) {
            throw err
          }
1306
        }
1307
      }
J
Joe Haddad 已提交
1308

1309 1310 1311 1312 1313 1314
      if (this.dynamicRoutes) {
        for (const dynamicRoute of this.dynamicRoutes) {
          const params = dynamicRoute.match(pathname)
          if (!params) {
            continue
          }
J
Joe Haddad 已提交
1315

1316
          const dynamicRouteResult = await this.findPageComponents(
1317 1318 1319 1320
            dynamicRoute.page,
            query,
            params
          )
1321
          if (dynamicRouteResult) {
1322 1323 1324 1325 1326
            try {
              return await this.renderToHTMLWithComponents(
                req,
                res,
                dynamicRoute.page,
1327
                dynamicRouteResult,
1328 1329 1330 1331 1332 1333
                { ...this.renderOpts, params }
              )
            } catch (err) {
              if (!(err instanceof NoFallbackError)) {
                throw err
              }
1334
            }
J
Joe Haddad 已提交
1335 1336
          }
        }
1337 1338 1339
      }
    } catch (err) {
      this.logError(err)
1340 1341 1342 1343 1344

      if (err && err.code === 'DECODE_FAILED') {
        res.statusCode = 400
        return await this.renderErrorToHTML(err, req, res, pathname, query)
      }
1345 1346 1347 1348 1349 1350
      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 已提交
1351 1352
  }

J
Joe Haddad 已提交
1353 1354 1355 1356 1357
  public async renderError(
    err: Error | null,
    req: IncomingMessage,
    res: ServerResponse,
    pathname: string,
1358
    query: ParsedUrlQuery = {}
J
Joe Haddad 已提交
1359 1360 1361
  ): Promise<void> {
    res.setHeader(
      'Cache-Control',
1362
      'no-cache, no-store, max-age=0, must-revalidate'
J
Joe Haddad 已提交
1363
    )
N
Naoyuki Kanezawa 已提交
1364
    const html = await this.renderErrorToHTML(err, req, res, pathname, query)
1365
    if (html === null) {
1366 1367
      return
    }
1368
    return this.sendHTML(req, res, html)
N
nkzawa 已提交
1369 1370
  }

1371 1372 1373 1374 1375 1376 1377 1378 1379
  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 已提交
1380 1381 1382 1383 1384
  public async renderErrorToHTML(
    err: Error | null,
    req: IncomingMessage,
    res: ServerResponse,
    _pathname: string,
1385
    query: ParsedUrlQuery = {}
J
Joe Haddad 已提交
1386
  ) {
1387
    let result: null | FindComponentsResult = null
1388

1389 1390 1391
    const is404 = res.statusCode === 404
    let using404Page = false

1392
    // use static 404 page if available and is 404 response
1393
    if (is404) {
1394 1395
      result = await this.findPageComponents('/404')
      using404Page = result !== null
1396 1397 1398 1399 1400 1401
    }

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

1402 1403 1404
    if (
      process.env.NODE_ENV !== 'production' &&
      !using404Page &&
1405 1406
      (await this.hasPage('/_error')) &&
      !(await this.hasPage('/404'))
1407 1408 1409 1410
    ) {
      this.customErrorNo404Warn()
    }

1411
    let html: string | null
1412
    try {
1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423
      try {
        html = await this.renderToHTMLWithComponents(
          req,
          res,
          using404Page ? '/404' : '/_error',
          result!,
          {
            ...this.renderOpts,
            err,
          }
        )
1424 1425
      } catch (maybeFallbackError) {
        if (maybeFallbackError instanceof NoFallbackError) {
1426
          throw new Error('invariant: failed to render error page')
1427
        }
1428
        throw maybeFallbackError
1429
      }
1430 1431
    } catch (renderToHtmlError) {
      console.error(renderToHtmlError)
1432 1433 1434 1435
      res.statusCode = 500
      html = 'Internal Server Error'
    }
    return html
N
Naoyuki Kanezawa 已提交
1436 1437
  }

J
Joe Haddad 已提交
1438 1439 1440
  public async render404(
    req: IncomingMessage,
    res: ServerResponse,
1441
    parsedUrl?: UrlWithParsedQuery
J
Joe Haddad 已提交
1442
  ): Promise<void> {
1443 1444
    const url: any = req.url
    const { pathname, query } = parsedUrl ? parsedUrl : parseUrl(url, true)
N
Naoyuki Kanezawa 已提交
1445
    res.statusCode = 404
1446
    return this.renderError(null, req, res, pathname!, query)
N
Naoyuki Kanezawa 已提交
1447
  }
N
Naoyuki Kanezawa 已提交
1448

J
Joe Haddad 已提交
1449 1450 1451 1452
  public async serveStatic(
    req: IncomingMessage,
    res: ServerResponse,
    path: string,
1453
    parsedUrl?: UrlWithParsedQuery
J
Joe Haddad 已提交
1454
  ): Promise<void> {
A
Arunoda Susiripala 已提交
1455
    if (!this.isServeableUrl(path)) {
1456
      return this.render404(req, res, parsedUrl)
A
Arunoda Susiripala 已提交
1457 1458
    }

1459 1460 1461 1462 1463 1464
    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 已提交
1465
    try {
1466
      await serveStatic(req, res, path)
N
Naoyuki Kanezawa 已提交
1467
    } catch (err) {
T
Tim Neutkens 已提交
1468
      if (err.code === 'ENOENT' || err.statusCode === 404) {
1469
        this.render404(req, res, parsedUrl)
1470 1471 1472
      } else if (err.statusCode === 412) {
        res.statusCode = 412
        return this.renderError(err, req, res, path)
N
Naoyuki Kanezawa 已提交
1473 1474 1475 1476 1477 1478
      } else {
        throw err
      }
    }
  }

1479 1480 1481 1482 1483 1484 1485 1486 1487
  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 已提交
1488
      userFilesStatic = recursiveReadDirSync(pathUserFilesStatic).map((f) =>
1489 1490 1491 1492 1493 1494
        join('.', 'static', f)
      )
    }

    let userFilesPublic: string[] = []
    if (this.publicDir && fs.existsSync(this.publicDir)) {
J
Joe Haddad 已提交
1495
      userFilesPublic = recursiveReadDirSync(this.publicDir).map((f) =>
1496 1497 1498 1499 1500 1501 1502
        join('.', 'public', f)
      )
    }

    let nextFilesStatic: string[] = []
    nextFilesStatic = recursiveReadDirSync(
      join(this.distDir, 'static')
J
Joe Haddad 已提交
1503
    ).map((f) => join('.', relative(this.dir, this.distDir), 'static', f))
1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537

    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 已提交
1538
    if (
1539 1540 1541
      (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 已提交
1542 1543 1544 1545
    ) {
      return false
    }

1546 1547 1548 1549
    // Check against the real filesystem paths
    const filesystemUrls = this.getFilesystemPaths()
    const resolved = relative(this.dir, untrustedFilePath)
    return filesystemUrls.has(resolved)
A
Arunoda Susiripala 已提交
1550 1551
  }

1552
  protected readBuildId(): string {
1553 1554 1555 1556 1557
    const buildIdFile = join(this.distDir, BUILD_ID_FILE)
    try {
      return fs.readFileSync(buildIdFile, 'utf8').trim()
    } catch (err) {
      if (!fs.existsSync(buildIdFile)) {
J
Joe Haddad 已提交
1558
        throw new Error(
1559
          `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 已提交
1560
        )
1561 1562 1563
      }

      throw err
1564
    }
1565
  }
1566

1567
  protected get _isLikeServerless(): boolean {
1568 1569
    return isTargetLikeServerless(this.nextConfig.target)
  }
1570
}
1571

1572 1573 1574 1575
function prepareServerlessUrl(
  req: IncomingMessage,
  query: ParsedUrlQuery
): void {
1576 1577 1578 1579 1580 1581 1582 1583 1584 1585
  const curUrl = parseUrl(req.url!, true)
  req.url = formatUrl({
    ...curUrl,
    search: undefined,
    query: {
      ...curUrl.query,
      ...query,
    },
  })
}
1586 1587

class NoFallbackError extends Error {}