next-server.ts 50.4 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'
82
import { detectDomainLocale } from '../lib/i18n/detect-domain-locale'
J
JJ Kasper 已提交
83 84

const getCustomRouteMatcher = pathMatch(true)
85 86 87

type NextConfig = any

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

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

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

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

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

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

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

T
Tim Neutkens 已提交
180
    this.buildId = this.readBuildId()
181

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

299 300 301 302 303
    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 已提交
304 305
    }

306
    if (i18n && !parsedUrl.pathname?.startsWith('/_next')) {
307 308
      // get pathname from URL with basePath stripped for locale detection
      const { pathname, ...parsed } = parseUrl(req.url || '/')
309
      let defaultLocale = i18n.defaultLocale
310 311
      let detectedLocale = detectLocaleCookie(req, i18n.locales)

312 313 314 315 316
      const detectedDomain = detectDomainLocale(i18n.domains, req)
      if (detectedDomain) {
        defaultLocale = detectedDomain.defaultLocale
        detectedLocale = defaultLocale
      }
317

318
      if (!detectedLocale) {
319 320
        detectedLocale = accept.language(
          req.headers['accept-language'],
321
          i18n.locales
322
        )
323 324
      }

325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
      let localeDomainRedirect: string | undefined
      const localePathResult = normalizeLocalePath(pathname!, i18n.locales)

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

        // check if the locale prefix matches a domain's defaultLocale
        // and we're on a locale specific domain if so redirect to that domain
        if (detectedDomain) {
          const matchedDomain = detectDomainLocale(
            i18n.domains,
            undefined,
            detectedLocale
          )

          if (matchedDomain) {
            localeDomainRedirect = `http${matchedDomain.http ? '' : 's'}://${
              matchedDomain?.domain
            }`
          }
        }
      }

353
      const denormalizedPagePath = denormalizePagePath(pathname || '/')
354
      const detectedDefaultLocale =
355 356
        !detectedLocale ||
        detectedLocale.toLowerCase() === defaultLocale.toLowerCase()
357
      const shouldStripDefaultLocale =
358
        detectedDefaultLocale &&
359 360
        denormalizedPagePath.toLowerCase() ===
          `/${i18n.defaultLocale.toLowerCase()}`
361 362
      const shouldAddLocalePrefix =
        !detectedDefaultLocale && denormalizedPagePath === '/'
363

364
      detectedLocale = detectedLocale || i18n.defaultLocale
365

366 367
      if (
        i18n.localeDetection !== false &&
368 369 370
        (localeDomainRedirect ||
          shouldAddLocalePrefix ||
          shouldStripDefaultLocale)
371 372 373 374 375 376
      ) {
        res.setHeader(
          'Location',
          formatUrl({
            // make sure to include any query values when redirecting
            ...parsed,
377 378 379 380 381
            pathname: localeDomainRedirect
              ? localeDomainRedirect
              : shouldStripDefaultLocale
              ? '/'
              : `/${detectedLocale}`,
382 383 384 385
          })
        )
        res.statusCode = 307
        res.end()
386
        return
387
      }
388
      parsedUrl.query.__nextLocale = detectedLocale || defaultLocale
389 390
    }

391
    res.statusCode = 200
392 393 394
    try {
      return await this.run(req, res, parsedUrl)
    } catch (err) {
J
Joe Haddad 已提交
395 396 397
      this.logError(err)
      res.statusCode = 500
      res.end('Internal Server Error')
398
    }
399 400
  }

401
  public getRequestHandler() {
402
    return this.handleRequest.bind(this)
N
nkzawa 已提交
403 404
  }

405
  public setAssetPrefix(prefix?: string): void {
406
    this.renderOpts.assetPrefix = prefix ? prefix.replace(/\/$/, '') : ''
407 408
  }

409
  // Backwards compatibility
410
  public async prepare(): Promise<void> {}
N
nkzawa 已提交
411

T
Tim Neutkens 已提交
412
  // Backwards compatibility
413
  protected async close(): Promise<void> {}
T
Tim Neutkens 已提交
414

415
  protected setImmutableAssetCacheControl(res: ServerResponse): void {
T
Tim Neutkens 已提交
416
    res.setHeader('Cache-Control', 'public, max-age=31536000, immutable')
N
nkzawa 已提交
417 418
  }

419
  protected getCustomRoutes(): CustomRoutes {
J
JJ Kasper 已提交
420 421 422
    return require(join(this.distDir, ROUTES_MANIFEST))
  }

423 424 425 426
  private _cachedPreviewManifest: PrerenderManifest | undefined
  protected getPrerenderManifest(): PrerenderManifest {
    if (this._cachedPreviewManifest) {
      return this._cachedPreviewManifest
J
Joe Haddad 已提交
427
    }
428 429 430 431 432 433
    const manifest = require(join(this.distDir, PRERENDER_MANIFEST))
    return (this._cachedPreviewManifest = manifest)
  }

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

436
  protected generateRoutes(): {
437
    basePath: string
438 439
    headers: Route[]
    rewrites: Route[]
440
    fsRoutes: Route[]
441
    redirects: Route[]
442 443
    catchAllRoute: Route
    pageChecker: PageChecker
444
    useFileSystemPublicRoutes: boolean
445 446
    dynamicRoutes: DynamicRoutes | undefined
  } {
447 448 449
    const publicRoutes = fs.existsSync(this.publicDir)
      ? this.generatePublicRoutes()
      : []
J
JJ Kasper 已提交
450

451
    const staticFilesRoute = this.hasStaticDir
452 453 454 455 456
      ? [
          {
            // 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.
457
            // See more: https://github.com/vercel/next.js/issues/2617
458
            match: route('/static/:path*'),
459
            name: 'static catchall',
460
            fn: async (req, res, params, parsedUrl) => {
461
              const p = join(this.dir, 'static', ...params.path)
462
              await this.serveStatic(req, res, p, parsedUrl)
463 464 465
              return {
                finished: true,
              }
466 467 468 469
            },
          } as Route,
        ]
      : []
470

471
    const fsRoutes: Route[] = [
T
Tim Neutkens 已提交
472
      {
473
        match: route('/_next/static/:path*'),
474 475
        type: 'route',
        name: '_next/static catchall',
476
        fn: async (req, res, params, parsedUrl) => {
477
          // make sure to 404 for /_next/static itself
478 479 480 481 482 483
          if (!params.path) {
            await this.render404(req, res, parsedUrl)
            return {
              finished: true,
            }
          }
484

J
Joe Haddad 已提交
485 486 487
          if (
            params.path[0] === CLIENT_STATIC_FILES_RUNTIME ||
            params.path[0] === 'chunks' ||
488 489
            params.path[0] === 'css' ||
            params.path[0] === 'media' ||
490
            params.path[0] === this.buildId ||
491
            params.path[0] === 'pages' ||
492
            params.path[1] === 'pages'
J
Joe Haddad 已提交
493
          ) {
T
Tim Neutkens 已提交
494
            this.setImmutableAssetCacheControl(res)
495
          }
J
Joe Haddad 已提交
496 497 498
          const p = join(
            this.distDir,
            CLIENT_STATIC_FILES_PATH,
499
            ...(params.path || [])
J
Joe Haddad 已提交
500
          )
501
          await this.serveStatic(req, res, p, parsedUrl)
502 503 504
          return {
            finished: true,
          }
505
        },
506
      },
J
JJ Kasper 已提交
507 508
      {
        match: route('/_next/data/:path*'),
509 510
        type: 'route',
        name: '_next/data catchall',
J
JJ Kasper 已提交
511
        fn: async (req, res, params, _parsedUrl) => {
J
JJ Kasper 已提交
512 513 514
          // 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) {
515 516 517 518
            await this.render404(req, res, _parsedUrl)
            return {
              finished: true,
            }
J
JJ Kasper 已提交
519 520 521 522 523 524
          }
          // 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')) {
525 526 527 528
            await this.render404(req, res, _parsedUrl)
            return {
              finished: true,
            }
J
JJ Kasper 已提交
529 530 531
          }

          // re-create page's pathname
532 533
          let pathname = `/${params.path.join('/')}`

534 535 536 537
          const { i18n } = this.nextConfig.experimental

          if (i18n) {
            const localePathResult = normalizeLocalePath(pathname, i18n.locales)
538 539
            const { defaultLocale } =
              detectDomainLocale(i18n.domains, req) || {}
540
            let detectedLocale = defaultLocale
541 542 543 544 545

            if (localePathResult.detectedLocale) {
              pathname = localePathResult.pathname
              detectedLocale = localePathResult.detectedLocale
            }
546
            _parsedUrl.query.__nextLocale = detectedLocale!
547 548
          }
          pathname = getRouteFromAssetPath(pathname, '.json')
J
JJ Kasper 已提交
549

J
JJ Kasper 已提交
550
          const parsedUrl = parseUrl(pathname, true)
551

J
JJ Kasper 已提交
552 553 554 555
          await this.render(
            req,
            res,
            pathname,
556
            { ..._parsedUrl.query, _nextDataReq: '1' },
J
JJ Kasper 已提交
557 558
            parsedUrl
          )
559 560 561
          return {
            finished: true,
          }
J
JJ Kasper 已提交
562 563
        },
      },
T
Tim Neutkens 已提交
564
      {
565
        match: route('/_next/:path*'),
566 567
        type: 'route',
        name: '_next catchall',
T
Tim Neutkens 已提交
568
        // This path is needed because `render()` does a check for `/_next` and the calls the routing again
569
        fn: async (req, res, _params, parsedUrl) => {
T
Tim Neutkens 已提交
570
          await this.render404(req, res, parsedUrl)
571 572 573
          return {
            finished: true,
          }
L
Lukáš Huvar 已提交
574 575
        },
      },
576 577
      ...publicRoutes,
      ...staticFilesRoute,
T
Tim Neutkens 已提交
578
    ]
579

580 581 582 583 584 585
    const getCustomRouteBasePath = (r: { basePath?: false }) => {
      return r.basePath !== false && this.renderOpts.dev
        ? this.nextConfig.basePath
        : ''
    }

586 587 588 589
    const getCustomRoute = (r: Rewrite | Redirect | Header, type: RouteType) =>
      ({
        ...r,
        type,
590
        match: getCustomRouteMatcher(`${getCustomRouteBasePath(r)}${r.source}`),
591 592 593 594 595 596 597
        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
598
      }
599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619

      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}`
            )
        }
620
      }
621 622 623 624 625 626 627 628 629 630 631 632
      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)
633
    }
634

635 636 637 638 639 640 641 642 643 644 645 646 647 648 649
    // 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)
650
            }
651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668
            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,
669 670 671
            parsedUrl.query,
            false,
            getCustomRouteBasePath(redirectRoute)
672
          )
673 674 675 676 677 678 679 680

          const { query } = parsedDestination
          delete parsedDestination.query

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

681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702
          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 {
703
        ...rewriteRoute,
704 705 706 707 708 709 710 711 712
        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,
713 714
            true,
            getCustomRouteBasePath(rewriteRoute)
715
          )
716

717 718
          // external rewrite, proxy it
          if (parsedDestination.protocol) {
719 720 721 722 723 724 725 726 727
            const { query } = parsedDestination
            delete parsedDestination.query
            parsedDestination.search = stringifyQs(
              query,
              undefined,
              undefined,
              { encodeURIComponent: (str) => str }
            )

728 729 730 731 732 733 734 735 736 737 738
            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)
            })
739 740 741
            return {
              finished: true,
            }
742 743
          }
          ;(req as any)._nextRewroteUrl = newUrl
744 745
          ;(req as any)._nextDidRewrite =
            (req as any)._nextRewroteUrl !== req.url
746

747 748 749 750 751 752 753 754
          return {
            finished: false,
            pathname: newUrl,
            query: parsedDestination.query,
          }
        },
      } as Route
    })
755 756 757 758 759 760

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

J
Jan Potoms 已提交
766
        // next.js core assumes page path without trailing slash
767
        pathname = removePathTrailingSlash(pathname)
J
Jan Potoms 已提交
768

769
        if (params?.path?.[0] === 'api') {
770 771 772
          const handled = await this.handleApiRequest(
            req as NextApiRequest,
            res as NextApiResponse,
773
            pathname,
774
            query
775 776 777 778 779 780 781
          )
          if (handled) {
            return { finished: true }
          }
        }

        await this.render(req, res, pathname, query, parsedUrl)
782 783 784 785
        return {
          finished: true,
        }
      },
786
    }
787

788
    const { useFileSystemPublicRoutes } = this.nextConfig
J
Joe Haddad 已提交
789

790 791
    if (useFileSystemPublicRoutes) {
      this.dynamicRoutes = this.getDynamicRoutes()
792
    }
N
nkzawa 已提交
793

794
    return {
795
      headers,
796
      fsRoutes,
797 798
      rewrites,
      redirects,
799
      catchAllRoute,
800
      useFileSystemPublicRoutes,
801
      dynamicRoutes: this.dynamicRoutes,
802
      basePath: this.nextConfig.basePath,
803 804
      pageChecker: this.hasPage.bind(this),
    }
T
Tim Neutkens 已提交
805 806
  }

807
  private async getPagePath(pathname: string): Promise<string> {
808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824
    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
  }

825 826 827 828 829
  protected async _beforeCatchAllRender(
    _req: IncomingMessage,
    _res: ServerResponse,
    _params: Params,
    _parsedUrl: UrlWithParsedQuery
830
  ): Promise<boolean> {
831 832 833
    return false
  }

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

L
Lukáš Huvar 已提交
837 838 839 840 841 842
  /**
   * Resolves `API` request, in development builds on demand
   * @param req http request
   * @param res http response
   * @param pathname path of request
   */
J
Joe Haddad 已提交
843
  private async handleApiRequest(
844 845
    req: IncomingMessage,
    res: ServerResponse,
846 847
    pathname: string,
    query: ParsedUrlQuery
848
  ): Promise<boolean> {
849
    let page = pathname
L
Lukáš Huvar 已提交
850
    let params: Params | boolean = false
851
    let pageFound = await this.hasPage(page)
J
JJ Kasper 已提交
852

853
    if (!pageFound && this.dynamicRoutes) {
L
Lukáš Huvar 已提交
854 855
      for (const dynamicRoute of this.dynamicRoutes) {
        params = dynamicRoute.match(pathname)
856
        if (dynamicRoute.page.startsWith('/api') && params) {
857 858
          page = dynamicRoute.page
          pageFound = true
L
Lukáš Huvar 已提交
859 860 861 862 863
          break
        }
      }
    }

864
    if (!pageFound) {
865
      return false
J
JJ Kasper 已提交
866
    }
867 868 869 870
    // Make sure the page is built before getting the path
    // or else it won't be in the manifest yet
    await this.ensureApiPage(page)

871 872 873 874 875 876 877 878 879 880
    let builtPagePath
    try {
      builtPagePath = await this.getPagePath(page)
    } catch (err) {
      if (err.code === 'ENOENT') {
        return false
      }
      throw err
    }

881
    const pageModule = await require(builtPagePath)
882
    query = { ...query, ...params }
J
JJ Kasper 已提交
883

884
    if (!this.renderOpts.dev && this._isLikeServerless) {
885
      if (typeof pageModule.default === 'function') {
886
        prepareServerlessUrl(req, query)
887 888
        await pageModule.default(req, res)
        return true
J
JJ Kasper 已提交
889 890 891
      }
    }

J
Joe Haddad 已提交
892 893 894 895 896
    await apiResolver(
      req,
      res,
      query,
      pageModule,
897
      this.renderOpts.previewProps,
898
      false,
J
Joe Haddad 已提交
899 900
      this.onErrorMiddleware
    )
901
    return true
L
Lukáš Huvar 已提交
902 903
  }

904
  protected generatePublicRoutes(): Route[] {
905
    const publicFiles = new Set(
906 907 908
      recursiveReadDirSync(this.publicDir).map((p) =>
        encodeURI(p.replace(/\\/g, '/'))
      )
909 910 911 912 913 914 915
    )

    return [
      {
        match: route('/:path*'),
        name: 'public folder catchall',
        fn: async (req, res, params, parsedUrl) => {
916
          const pathParts: string[] = params.path || []
917 918 919 920 921 922 923 924
          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()
          }

925
          const path = `/${pathParts.join('/')}`
926 927 928 929 930

          if (publicFiles.has(path)) {
            await this.serveStatic(
              req,
              res,
931
              join(this.publicDir, ...pathParts),
932 933
              parsedUrl
            )
934 935 936
            return {
              finished: true,
            }
937 938 939 940 941 942 943
          }
          return {
            finished: false,
          }
        },
      } as Route,
    ]
944 945
  }

946
  protected getDynamicRoutes() {
947 948
    return getSortedRoutes(Object.keys(this.pagesManifest!))
      .filter(isDynamicRoute)
J
Joe Haddad 已提交
949
      .map((page) => ({
950 951 952
        page,
        match: getRouteMatcher(getRouteRegex(page)),
      }))
J
Joe Haddad 已提交
953 954
  }

955
  private handleCompression(req: IncomingMessage, res: ServerResponse): void {
956 957 958 959 960
    if (this.compression) {
      this.compression(req, res, () => {})
    }
  }

961
  protected async run(
J
Joe Haddad 已提交
962 963
    req: IncomingMessage,
    res: ServerResponse,
964
    parsedUrl: UrlWithParsedQuery
965
  ): Promise<void> {
966 967
    this.handleCompression(req, res)

968
    try {
969 970
      const matched = await this.router.execute(req, res, parsedUrl)
      if (matched) {
971 972 973 974 975 976 977 978
        return
      }
    } catch (err) {
      if (err.code === 'DECODE_FAILED') {
        res.statusCode = 400
        return this.renderError(null, req, res, '/_error', {})
      }
      throw err
979 980
    }

981
    await this.render404(req, res, parsedUrl)
N
nkzawa 已提交
982 983
  }

984
  protected async sendHTML(
J
Joe Haddad 已提交
985 986
    req: IncomingMessage,
    res: ServerResponse,
987
    html: string
988
  ): Promise<void> {
T
Tim Neutkens 已提交
989
    const { generateEtags, poweredByHeader } = this.renderOpts
990 991 992 993
    return sendPayload(req, res, html, 'html', {
      generateEtags,
      poweredByHeader,
    })
994 995
  }

J
Joe Haddad 已提交
996 997 998 999 1000
  public async render(
    req: IncomingMessage,
    res: ServerResponse,
    pathname: string,
    query: ParsedUrlQuery = {},
1001
    parsedUrl?: UrlWithParsedQuery
J
Joe Haddad 已提交
1002
  ): Promise<void> {
1003 1004 1005 1006 1007 1008
    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`
      )
    }

1009 1010 1011 1012 1013 1014 1015 1016 1017 1018
    if (
      this.renderOpts.customServer &&
      pathname === '/index' &&
      !(await this.hasPage('/index'))
    ) {
      // maintain backwards compatibility for custom server
      // (see custom-server integration tests)
      pathname = '/'
    }

1019
    const url: any = req.url
1020

1021 1022 1023 1024
    // 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
1025
    if (
1026 1027 1028
      !query._nextDataReq &&
      (url.match(/^\/_next\//) ||
        (this.hasStaticDir && url.match(/^\/static\//)))
1029
    ) {
1030 1031 1032
      return this.handleRequest(req, res, parsedUrl)
    }

1033
    if (isBlockedPage(pathname)) {
1034
      return this.render404(req, res, parsedUrl)
1035 1036
    }

1037
    const html = await this.renderToHTML(req, res, pathname, query)
1038 1039
    // Request was ended by the user
    if (html === null) {
1040 1041 1042
      return
    }

1043
    return this.sendHTML(req, res, html)
N
Naoyuki Kanezawa 已提交
1044
  }
N
nkzawa 已提交
1045

J
Joe Haddad 已提交
1046
  private async findPageComponents(
J
Joe Haddad 已提交
1047
    pathname: string,
1048 1049 1050
    query: ParsedUrlQuery = {},
    params: Params | null = null
  ): Promise<FindComponentsResult | null> {
1051
    let paths = [
1052 1053 1054 1055
      // try serving a static AMP version first
      query.amp ? normalizePagePath(pathname) + '.amp' : null,
      pathname,
    ].filter(Boolean)
1056 1057 1058 1059 1060 1061 1062 1063 1064 1065

    if (query.__nextLocale) {
      paths = [
        ...paths.map(
          (path) => `/${query.__nextLocale}${path === '/' ? '' : path}`
        ),
        ...paths,
      ]
    }

1066
    for (const pagePath of paths) {
J
JJ Kasper 已提交
1067
      try {
1068
        const components = await loadComponents(
J
Joe Haddad 已提交
1069
          this.distDir,
1070 1071
          pagePath!,
          !this.renderOpts.dev && this._isLikeServerless
J
Joe Haddad 已提交
1072
        )
1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084
        // if loading an static HTML file the locale is required
        // to be present since all HTML files are output under their locale
        if (
          query.__nextLocale &&
          typeof components.Component === 'string' &&
          !pagePath?.startsWith(`/${query.__nextLocale}`)
        ) {
          const err = new Error('NOT_FOUND')
          ;(err as any).code = 'ENOENT'
          throw err
        }

1085 1086 1087
        return {
          components,
          query: {
1088
            ...(components.getStaticProps
1089 1090 1091 1092 1093
              ? {
                  amp: query.amp,
                  _nextDataReq: query._nextDataReq,
                  __nextLocale: query.__nextLocale,
                }
1094 1095 1096 1097
              : query),
            ...(params || {}),
          },
        }
J
JJ Kasper 已提交
1098 1099 1100 1101
      } catch (err) {
        if (err.code !== 'ENOENT') throw err
      }
    }
1102
    return null
J
Joe Haddad 已提交
1103 1104
  }

1105
  protected async getStaticPaths(
1106 1107 1108
    pathname: string
  ): Promise<{
    staticPaths: string[] | undefined
1109
    fallbackMode: 'static' | 'blocking' | false
1110
  }> {
1111 1112 1113 1114 1115
    // `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.
1116 1117
    const fallbackField = this.getPrerenderManifest().dynamicRoutes[pathname]
      .fallback
1118

1119 1120 1121 1122 1123 1124 1125 1126 1127
    return {
      staticPaths,
      fallbackMode:
        typeof fallbackField === 'string'
          ? 'static'
          : fallbackField === null
          ? 'blocking'
          : false,
    }
1128 1129
  }

J
Joe Haddad 已提交
1130 1131 1132 1133
  private async renderToHTMLWithComponents(
    req: IncomingMessage,
    res: ServerResponse,
    pathname: string,
1134
    { components, query }: FindComponentsResult,
1135
    opts: RenderOptsPartial
1136
  ): Promise<string | null> {
1137
    // we need to ensure the status code if /404 is visited directly
1138
    if (pathname === '/404') {
1139 1140 1141
      res.statusCode = 404
    }

J
JJ Kasper 已提交
1142
    // handle static page
1143 1144
    if (typeof components.Component === 'string') {
      return components.Component
J
Joe Haddad 已提交
1145 1146
    }

J
JJ Kasper 已提交
1147 1148
    // check request state
    const isLikeServerless =
1149 1150
      typeof components.Component === 'object' &&
      typeof (components.Component as any).renderReqToHTML === 'function'
1151 1152 1153
    const isSSG = !!components.getStaticProps
    const isServerProps = !!components.getServerSideProps
    const hasStaticPaths = !!components.getStaticPaths
1154

1155 1156 1157 1158
    if (!query.amp) {
      delete query.amp
    }

1159
    // Toggle whether or not this is a Data request
1160
    const isDataReq = !!query._nextDataReq && (isSSG || isServerProps)
1161 1162
    delete query._nextDataReq

J
JJ Kasper 已提交
1163 1164
    const locale = query.__nextLocale as string
    delete query.__nextLocale
1165 1166 1167

    const { i18n } = this.nextConfig.experimental
    const locales = i18n.locales as string[]
J
JJ Kasper 已提交
1168

1169 1170 1171 1172 1173 1174 1175 1176
    let previewData: string | false | object | undefined
    let isPreviewMode = false

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

1177 1178 1179
    // 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
1180 1181 1182
    let urlPathname = parseUrl(req.url || '').pathname || '/'

    let resolvedUrlPathname = (req as any)._nextRewroteUrl
1183
      ? (req as any)._nextRewroteUrl
1184
      : urlPathname
1185

1186 1187 1188 1189 1190 1191 1192 1193 1194
    resolvedUrlPathname = removePathTrailingSlash(resolvedUrlPathname)
    urlPathname = removePathTrailingSlash(urlPathname)

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

      if (this.nextConfig.experimental.i18n) {
J
JJ Kasper 已提交
1197
        return normalizeLocalePath(path, locales).pathname
1198
      }
1199 1200
      return path
    }
1201

1202 1203
    // remove /_next/data prefix from urlPathname so it matches
    // for direct page visit and /_next/data visit
1204 1205 1206
    if (isDataReq) {
      resolvedUrlPathname = stripNextDataPath(resolvedUrlPathname)
      urlPathname = stripNextDataPath(urlPathname)
1207 1208
    }

1209 1210 1211
    const ssgCacheKey =
      isPreviewMode || !isSSG
        ? undefined // Preview mode bypasses the cache
1212 1213 1214
        : `${locale ? `/${locale}` : ''}${resolvedUrlPathname}${
            query.amp ? '.amp' : ''
          }`
J
JJ Kasper 已提交
1215 1216

    // Complete the response with cached data if its present
1217 1218 1219
    const cachedData = ssgCacheKey
      ? await this.incrementalCache.get(ssgCacheKey)
      : undefined
1220

J
JJ Kasper 已提交
1221
    if (cachedData) {
1222
      const data = isDataReq
J
JJ Kasper 已提交
1223 1224 1225
        ? JSON.stringify(cachedData.pageData)
        : cachedData.html

1226
      sendPayload(
1227
        req,
J
JJ Kasper 已提交
1228 1229
        res,
        data,
1230
        isDataReq ? 'json' : 'html',
1231 1232 1233 1234
        {
          generateEtags: this.renderOpts.generateEtags,
          poweredByHeader: this.renderOpts.poweredByHeader,
        },
1235 1236 1237 1238 1239 1240 1241 1242 1243
        !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,
            }
1244
          : undefined
J
JJ Kasper 已提交
1245 1246 1247 1248 1249 1250
      )

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

J
JJ Kasper 已提交
1253
    // If we're here, that means data is missing or it's stale.
1254 1255 1256 1257 1258 1259
    const maybeCoalesceInvoke = ssgCacheKey
      ? (fn: any) => withCoalescedInvoke(fn).bind(null, ssgCacheKey, [])
      : (fn: any) => async () => {
          const value = await fn()
          return { isOrigin: true, value }
        }
J
JJ Kasper 已提交
1260

1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276
    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 已提交
1277 1278 1279
            'passthrough',
            {
              fontManifest: this.renderOpts.fontManifest,
1280
              locale,
1281 1282
              locales,
              // defaultLocale,
P
Prateek Bhatnagar 已提交
1283
            }
1284
          )
J
JJ Kasper 已提交
1285

1286 1287 1288 1289
          html = renderResult.html
          pageData = renderResult.renderOpts.pageData
          sprRevalidate = renderResult.renderOpts.revalidate
        } else {
1290 1291 1292 1293 1294 1295 1296
          const origQuery = parseUrl(req.url || '', true).query
          const resolvedUrl = formatUrl({
            pathname: resolvedUrlPathname,
            // make sure to only add query values from original URL
            query: origQuery,
          })

1297 1298 1299 1300
          const renderOpts: RenderOpts = {
            ...components,
            ...opts,
            isDataReq,
1301
            resolvedUrl,
1302
            locale,
1303 1304
            locales,
            // defaultLocale,
1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315
            // 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,
1316
          }
1317

1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329
          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 已提交
1330 1331
        }

1332
        return { html, pageData, sprRevalidate }
J
JJ Kasper 已提交
1333
      }
1334
    )
J
JJ Kasper 已提交
1335

1336
    const isProduction = !this.renderOpts.dev
J
Joe Haddad 已提交
1337
    const isDynamicPathname = isDynamicRoute(pathname)
1338
    const didRespond = isResSent(res)
1339

1340
    const { staticPaths, fallbackMode } = hasStaticPaths
1341
      ? await this.getStaticPaths(pathname)
1342
      : { staticPaths: undefined, fallbackMode: false }
1343

1344 1345 1346 1347 1348
    // When we did not respond from cache, we need to choose to block on
    // rendering or return a skeleton.
    //
    // * Data requests always block.
    //
1349 1350
    // * Blocking mode fallback always blocks.
    //
1351 1352
    // * Preview mode toggles all pages to be resolved in a blocking manner.
    //
1353
    // * Non-dynamic pages should block (though this is an impossible
1354 1355
    //   case in production).
    //
1356 1357
    // * Dynamic pages should return their skeleton if not defined in
    //   getStaticPaths, then finish the data request on the client-side.
1358
    //
J
Joe Haddad 已提交
1359
    if (
1360
      fallbackMode !== 'blocking' &&
1361
      ssgCacheKey &&
1362 1363 1364
      !didRespond &&
      !isPreviewMode &&
      isDynamicPathname &&
1365 1366
      // Development should trigger fallback when the path is not in
      // `getStaticPaths`
1367 1368
      (isProduction ||
        !staticPaths ||
1369 1370 1371 1372 1373
        // static paths always includes locale so make sure it's prefixed
        // with it
        !staticPaths.includes(
          `${locale ? '/' + locale : ''}${resolvedUrlPathname}`
        ))
J
Joe Haddad 已提交
1374
    ) {
1375 1376 1377 1378 1379
      if (
        // In development, fall through to render to handle missing
        // getStaticPaths.
        (isProduction || staticPaths) &&
        // When fallback isn't present, abort this render so we 404
1380
        fallbackMode !== 'static'
1381
      ) {
1382
        throw new NoFallbackError()
1383 1384
      }

1385 1386
      if (!isDataReq) {
        let html: string
1387

1388 1389
        // Production already emitted the fallback as static HTML.
        if (isProduction) {
1390 1391 1392
          html = await this.incrementalCache.getFallback(
            locale ? `/${locale}${pathname}` : pathname
          )
1393 1394 1395 1396 1397 1398 1399 1400 1401
        }
        // 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
1402 1403
        }

1404 1405 1406 1407 1408 1409
        sendPayload(req, res, html, 'html', {
          generateEtags: this.renderOpts.generateEtags,
          poweredByHeader: this.renderOpts.poweredByHeader,
        })
        return null
      }
1410 1411
    }

1412 1413 1414
    const {
      isOrigin,
      value: { html, pageData, sprRevalidate },
1415
    } = await doRender()
1416 1417
    let resHtml = html
    if (!isResSent(res) && (isSSG || isDataReq || isServerProps)) {
1418
      sendPayload(
1419
        req,
1420 1421
        res,
        isDataReq ? JSON.stringify(pageData) : html,
1422
        isDataReq ? 'json' : 'html',
1423 1424 1425 1426
        {
          generateEtags: this.renderOpts.generateEtags,
          poweredByHeader: this.renderOpts.poweredByHeader,
        },
1427
        !this.renderOpts.dev || (isServerProps && !isDataReq)
1428 1429
          ? {
              private: isPreviewMode,
1430
              stateful: !isSSG,
1431 1432
              revalidate: sprRevalidate,
            }
1433
          : undefined
1434
      )
1435
      resHtml = null
1436
    }
J
JJ Kasper 已提交
1437

1438
    // Update the cache if the head request and cacheable
1439
    if (isOrigin && ssgCacheKey) {
1440 1441 1442 1443 1444
      await this.incrementalCache.set(
        ssgCacheKey,
        { html: html!, pageData },
        sprRevalidate
      )
1445 1446
    }

1447
    return resHtml
1448 1449
  }

1450
  public async renderToHTML(
J
Joe Haddad 已提交
1451 1452 1453
    req: IncomingMessage,
    res: ServerResponse,
    pathname: string,
1454
    query: ParsedUrlQuery = {}
J
Joe Haddad 已提交
1455
  ): Promise<string | null> {
1456 1457 1458
    try {
      const result = await this.findPageComponents(pathname, query)
      if (result) {
1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470
        try {
          return await this.renderToHTMLWithComponents(
            req,
            res,
            pathname,
            result,
            { ...this.renderOpts }
          )
        } catch (err) {
          if (!(err instanceof NoFallbackError)) {
            throw err
          }
1471
        }
1472
      }
J
Joe Haddad 已提交
1473

1474 1475 1476 1477 1478 1479
      if (this.dynamicRoutes) {
        for (const dynamicRoute of this.dynamicRoutes) {
          const params = dynamicRoute.match(pathname)
          if (!params) {
            continue
          }
J
Joe Haddad 已提交
1480

1481
          const dynamicRouteResult = await this.findPageComponents(
1482 1483 1484 1485
            dynamicRoute.page,
            query,
            params
          )
1486
          if (dynamicRouteResult) {
1487 1488 1489 1490 1491
            try {
              return await this.renderToHTMLWithComponents(
                req,
                res,
                dynamicRoute.page,
1492
                dynamicRouteResult,
1493 1494 1495 1496 1497 1498
                { ...this.renderOpts, params }
              )
            } catch (err) {
              if (!(err instanceof NoFallbackError)) {
                throw err
              }
1499
            }
J
Joe Haddad 已提交
1500 1501
          }
        }
1502 1503 1504
      }
    } catch (err) {
      this.logError(err)
1505 1506 1507 1508 1509

      if (err && err.code === 'DECODE_FAILED') {
        res.statusCode = 400
        return await this.renderErrorToHTML(err, req, res, pathname, query)
      }
1510 1511 1512 1513 1514
      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 已提交
1515 1516
  }

J
Joe Haddad 已提交
1517 1518 1519 1520 1521
  public async renderError(
    err: Error | null,
    req: IncomingMessage,
    res: ServerResponse,
    pathname: string,
1522
    query: ParsedUrlQuery = {}
J
Joe Haddad 已提交
1523 1524 1525
  ): Promise<void> {
    res.setHeader(
      'Cache-Control',
1526
      'no-cache, no-store, max-age=0, must-revalidate'
J
Joe Haddad 已提交
1527
    )
N
Naoyuki Kanezawa 已提交
1528
    const html = await this.renderErrorToHTML(err, req, res, pathname, query)
1529
    if (html === null) {
1530 1531
      return
    }
1532
    return this.sendHTML(req, res, html)
N
nkzawa 已提交
1533 1534
  }

1535 1536 1537 1538 1539 1540 1541 1542 1543
  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 已提交
1544 1545 1546 1547 1548
  public async renderErrorToHTML(
    err: Error | null,
    req: IncomingMessage,
    res: ServerResponse,
    _pathname: string,
1549
    query: ParsedUrlQuery = {}
J
Joe Haddad 已提交
1550
  ) {
1551
    let result: null | FindComponentsResult = null
1552

1553 1554 1555
    const is404 = res.statusCode === 404
    let using404Page = false

1556
    // use static 404 page if available and is 404 response
1557
    if (is404) {
1558
      result = await this.findPageComponents('/404', query)
1559
      using404Page = result !== null
1560 1561 1562 1563 1564 1565
    }

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

1566 1567 1568
    if (
      process.env.NODE_ENV !== 'production' &&
      !using404Page &&
1569 1570
      (await this.hasPage('/_error')) &&
      !(await this.hasPage('/404'))
1571 1572 1573 1574
    ) {
      this.customErrorNo404Warn()
    }

1575
    let html: string | null
1576
    try {
1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587
      try {
        html = await this.renderToHTMLWithComponents(
          req,
          res,
          using404Page ? '/404' : '/_error',
          result!,
          {
            ...this.renderOpts,
            err,
          }
        )
1588 1589
      } catch (maybeFallbackError) {
        if (maybeFallbackError instanceof NoFallbackError) {
1590
          throw new Error('invariant: failed to render error page')
1591
        }
1592
        throw maybeFallbackError
1593
      }
1594 1595
    } catch (renderToHtmlError) {
      console.error(renderToHtmlError)
1596 1597 1598 1599
      res.statusCode = 500
      html = 'Internal Server Error'
    }
    return html
N
Naoyuki Kanezawa 已提交
1600 1601
  }

J
Joe Haddad 已提交
1602 1603 1604
  public async render404(
    req: IncomingMessage,
    res: ServerResponse,
1605
    parsedUrl?: UrlWithParsedQuery
J
Joe Haddad 已提交
1606
  ): Promise<void> {
1607 1608
    const url: any = req.url
    const { pathname, query } = parsedUrl ? parsedUrl : parseUrl(url, true)
N
Naoyuki Kanezawa 已提交
1609
    res.statusCode = 404
1610
    return this.renderError(null, req, res, pathname!, query)
N
Naoyuki Kanezawa 已提交
1611
  }
N
Naoyuki Kanezawa 已提交
1612

J
Joe Haddad 已提交
1613 1614 1615 1616
  public async serveStatic(
    req: IncomingMessage,
    res: ServerResponse,
    path: string,
1617
    parsedUrl?: UrlWithParsedQuery
J
Joe Haddad 已提交
1618
  ): Promise<void> {
A
Arunoda Susiripala 已提交
1619
    if (!this.isServeableUrl(path)) {
1620
      return this.render404(req, res, parsedUrl)
A
Arunoda Susiripala 已提交
1621 1622
    }

1623 1624 1625 1626 1627 1628
    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 已提交
1629
    try {
1630
      await serveStatic(req, res, path)
N
Naoyuki Kanezawa 已提交
1631
    } catch (err) {
T
Tim Neutkens 已提交
1632
      if (err.code === 'ENOENT' || err.statusCode === 404) {
1633
        this.render404(req, res, parsedUrl)
1634 1635 1636
      } else if (err.statusCode === 412) {
        res.statusCode = 412
        return this.renderError(err, req, res, path)
N
Naoyuki Kanezawa 已提交
1637 1638 1639 1640 1641 1642
      } else {
        throw err
      }
    }
  }

1643 1644 1645 1646 1647 1648 1649 1650 1651
  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 已提交
1652
      userFilesStatic = recursiveReadDirSync(pathUserFilesStatic).map((f) =>
1653 1654 1655 1656 1657 1658
        join('.', 'static', f)
      )
    }

    let userFilesPublic: string[] = []
    if (this.publicDir && fs.existsSync(this.publicDir)) {
J
Joe Haddad 已提交
1659
      userFilesPublic = recursiveReadDirSync(this.publicDir).map((f) =>
1660 1661 1662 1663 1664 1665 1666
        join('.', 'public', f)
      )
    }

    let nextFilesStatic: string[] = []
    nextFilesStatic = recursiveReadDirSync(
      join(this.distDir, 'static')
J
Joe Haddad 已提交
1667
    ).map((f) => join('.', relative(this.dir, this.distDir), 'static', f))
1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701

    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 已提交
1702
    if (
1703 1704 1705
      (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 已提交
1706 1707 1708 1709
    ) {
      return false
    }

1710 1711 1712 1713
    // Check against the real filesystem paths
    const filesystemUrls = this.getFilesystemPaths()
    const resolved = relative(this.dir, untrustedFilePath)
    return filesystemUrls.has(resolved)
A
Arunoda Susiripala 已提交
1714 1715
  }

1716
  protected readBuildId(): string {
1717 1718 1719 1720 1721
    const buildIdFile = join(this.distDir, BUILD_ID_FILE)
    try {
      return fs.readFileSync(buildIdFile, 'utf8').trim()
    } catch (err) {
      if (!fs.existsSync(buildIdFile)) {
J
Joe Haddad 已提交
1722
        throw new Error(
1723
          `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 已提交
1724
        )
1725 1726 1727
      }

      throw err
1728
    }
1729
  }
1730

1731
  protected get _isLikeServerless(): boolean {
1732 1733
    return isTargetLikeServerless(this.nextConfig.target)
  }
1734
}
1735

1736 1737 1738 1739
function prepareServerlessUrl(
  req: IncomingMessage,
  query: ParsedUrlQuery
): void {
1740 1741 1742 1743 1744 1745 1746 1747 1748 1749
  const curUrl = parseUrl(req.url!, true)
  req.url = formatUrl({
    ...curUrl,
    search: undefined,
    query: {
      ...curUrl.query,
      ...query,
    },
  })
}
1750 1751

class NoFallbackError extends Error {}