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

const getCustomRouteMatcher = pathMatch(true)
68 69 70

type NextConfig = any

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

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

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

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

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

142
    this.nextConfig = loadConfig(phase, this.dir, conf)
143
    this.distDir = join(this.dir, this.nextConfig.distDir)
144
    this.publicDir = join(this.dir, CLIENT_PUBLIC_FILES_PATH)
145
    this.hasStaticDir = fs.existsSync(join(this.dir, 'static'))
T
Tim Neutkens 已提交
146

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

T
Tim Neutkens 已提交
157
    this.buildId = this.readBuildId()
158

159
    this.renderOpts = {
T
Tim Neutkens 已提交
160
      poweredByHeader: this.nextConfig.poweredByHeader,
161
      canonicalBase: this.nextConfig.amp.canonicalBase,
162
      buildId: this.buildId,
163
      generateEtags,
164
      previewProps: this.getPreviewProps(),
165
      customServer: customServer === true ? true : undefined,
166
      ampOptimizerConfig: this.nextConfig.experimental.amp?.optimizer,
167
      basePath: this.nextConfig.basePath,
168
    }
N
Naoyuki Kanezawa 已提交
169

170 171
    // Only the `publicRuntimeConfig` key is exposed to the client side
    // It'll be rendered as part of __NEXT_DATA__ on the client side
172
    if (Object.keys(publicRuntimeConfig).length > 0) {
173
      this.renderOpts.runtimeConfig = publicRuntimeConfig
174 175
    }

176
    if (compress && this.nextConfig.target === 'server') {
177 178 179
      this.compression = compression() as Middleware
    }

180
    // Initialize next/config with the environment configuration
181 182 183 184
    envConfig.setConfig({
      serverRuntimeConfig,
      publicRuntimeConfig,
    })
185

186 187 188 189 190 191 192 193 194 195
    this.serverBuildDir = join(
      this.distDir,
      this._isLikeServerless ? SERVERLESS_DIRECTORY : SERVER_DIRECTORY
    )
    const pagesManifestPath = join(this.serverBuildDir, PAGES_MANIFEST)

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

196
    this.customRoutes = this.getCustomRoutes()
J
JJ Kasper 已提交
197
    this.router = new Router(this.generateRoutes())
198
    this.setAssetPrefix(assetPrefix)
J
JJ Kasper 已提交
199

200 201 202
    // call init-server middleware, this is also handled
    // individually in serverless bundles when deployed
    if (!dev && this.nextConfig.experimental.plugins) {
203 204
      const initServer = require(join(this.serverBuildDir, 'init-server.js'))
        .default
205
      this.onErrorMiddleware = require(join(
206
        this.serverBuildDir,
207 208 209 210 211
        'on-error-server.js'
      )).default
      initServer()
    }

212
    this.incrementalCache = new IncrementalCache({
J
JJ Kasper 已提交
213 214 215 216
      dev,
      distDir: this.distDir,
      pagesDir: join(
        this.distDir,
217
        this._isLikeServerless ? SERVERLESS_DIRECTORY : SERVER_DIRECTORY,
J
JJ Kasper 已提交
218 219 220 221
        'pages'
      ),
      flushToDisk: this.nextConfig.experimental.sprFlushToDisk,
    })
N
Naoyuki Kanezawa 已提交
222
  }
N
nkzawa 已提交
223

224
  protected currentPhase(): string {
225
    return PHASE_PRODUCTION_SERVER
226 227
  }

228 229 230 231
  private logError(err: Error): void {
    if (this.onErrorMiddleware) {
      this.onErrorMiddleware({ err })
    }
232 233
    if (this.quiet) return
    // tslint:disable-next-line
234
    console.error(err)
235 236
  }

237
  private async handleRequest(
J
Joe Haddad 已提交
238 239
    req: IncomingMessage,
    res: ServerResponse,
240
    parsedUrl?: UrlWithParsedQuery
J
Joe Haddad 已提交
241
  ): Promise<void> {
242
    // Parse url if parsedUrl not provided
243
    if (!parsedUrl || typeof parsedUrl !== 'object') {
244 245
      const url: any = req.url
      parsedUrl = parseUrl(url, true)
246
    }
247

248 249 250
    // 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 已提交
251
    }
252

253
    const { basePath } = this.nextConfig
254

255 256 257 258 259
    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 已提交
260 261
    }

262
    res.statusCode = 200
263 264 265
    try {
      return await this.run(req, res, parsedUrl)
    } catch (err) {
J
Joe Haddad 已提交
266 267 268
      this.logError(err)
      res.statusCode = 500
      res.end('Internal Server Error')
269
    }
270 271
  }

272
  public getRequestHandler() {
273
    return this.handleRequest.bind(this)
N
nkzawa 已提交
274 275
  }

276
  public setAssetPrefix(prefix?: string): void {
277
    this.renderOpts.assetPrefix = prefix ? prefix.replace(/\/$/, '') : ''
278 279
  }

280
  // Backwards compatibility
281
  public async prepare(): Promise<void> {}
N
nkzawa 已提交
282

T
Tim Neutkens 已提交
283
  // Backwards compatibility
284
  protected async close(): Promise<void> {}
T
Tim Neutkens 已提交
285

286
  protected setImmutableAssetCacheControl(res: ServerResponse): void {
T
Tim Neutkens 已提交
287
    res.setHeader('Cache-Control', 'public, max-age=31536000, immutable')
N
nkzawa 已提交
288 289
  }

290
  protected getCustomRoutes(): CustomRoutes {
J
JJ Kasper 已提交
291 292 293
    return require(join(this.distDir, ROUTES_MANIFEST))
  }

294 295 296 297
  private _cachedPreviewManifest: PrerenderManifest | undefined
  protected getPrerenderManifest(): PrerenderManifest {
    if (this._cachedPreviewManifest) {
      return this._cachedPreviewManifest
J
Joe Haddad 已提交
298
    }
299 300 301 302 303 304
    const manifest = require(join(this.distDir, PRERENDER_MANIFEST))
    return (this._cachedPreviewManifest = manifest)
  }

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

307
  protected generateRoutes(): {
308
    basePath: string
309 310
    headers: Route[]
    rewrites: Route[]
311
    fsRoutes: Route[]
312
    redirects: Route[]
313 314
    catchAllRoute: Route
    pageChecker: PageChecker
315
    useFileSystemPublicRoutes: boolean
316 317
    dynamicRoutes: DynamicRoutes | undefined
  } {
318 319 320
    const publicRoutes = fs.existsSync(this.publicDir)
      ? this.generatePublicRoutes()
      : []
J
JJ Kasper 已提交
321

322
    const staticFilesRoute = this.hasStaticDir
323 324 325 326 327
      ? [
          {
            // 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.
328
            // See more: https://github.com/vercel/next.js/issues/2617
329
            match: route('/static/:path*'),
330
            name: 'static catchall',
331
            fn: async (req, res, params, parsedUrl) => {
332 333 334 335 336
              const p = join(
                this.dir,
                'static',
                ...(params.path || []).map(encodeURIComponent)
              )
337
              await this.serveStatic(req, res, p, parsedUrl)
338 339 340
              return {
                finished: true,
              }
341 342 343 344
            },
          } as Route,
        ]
      : []
345

346
    const fsRoutes: Route[] = [
T
Tim Neutkens 已提交
347
      {
348
        match: route('/_next/static/:path*'),
349 350
        type: 'route',
        name: '_next/static catchall',
351
        fn: async (req, res, params, parsedUrl) => {
352
          // make sure to 404 for /_next/static itself
353 354 355 356 357 358
          if (!params.path) {
            await this.render404(req, res, parsedUrl)
            return {
              finished: true,
            }
          }
359

J
Joe Haddad 已提交
360 361 362
          if (
            params.path[0] === CLIENT_STATIC_FILES_RUNTIME ||
            params.path[0] === 'chunks' ||
363 364
            params.path[0] === 'css' ||
            params.path[0] === 'media' ||
365
            params.path[0] === this.buildId ||
366
            params.path[0] === 'pages' ||
367
            params.path[1] === 'pages'
J
Joe Haddad 已提交
368
          ) {
T
Tim Neutkens 已提交
369
            this.setImmutableAssetCacheControl(res)
370
          }
J
Joe Haddad 已提交
371 372 373
          const p = join(
            this.distDir,
            CLIENT_STATIC_FILES_PATH,
374
            ...(params.path || [])
J
Joe Haddad 已提交
375
          )
376
          await this.serveStatic(req, res, p, parsedUrl)
377 378 379
          return {
            finished: true,
          }
380
        },
381
      },
J
JJ Kasper 已提交
382 383
      {
        match: route('/_next/data/:path*'),
384 385
        type: 'route',
        name: '_next/data catchall',
J
JJ Kasper 已提交
386
        fn: async (req, res, params, _parsedUrl) => {
J
JJ Kasper 已提交
387 388 389
          // 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) {
390 391 392 393
            await this.render404(req, res, _parsedUrl)
            return {
              finished: true,
            }
J
JJ Kasper 已提交
394 395 396 397 398 399
          }
          // 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')) {
400 401 402 403
            await this.render404(req, res, _parsedUrl)
            return {
              finished: true,
            }
J
JJ Kasper 已提交
404 405 406
          }

          // re-create page's pathname
407 408 409 410 411 412 413 414
          const pathname = getRouteFromAssetPath(
            `/${params.path
              // we need to re-encode the params since they are decoded
              // by path-match and we are re-building the URL
              .map((param: string) => encodeURIComponent(param))
              .join('/')}`,
            '.json'
          )
J
JJ Kasper 已提交
415

J
JJ Kasper 已提交
416
          const parsedUrl = parseUrl(pathname, true)
417

J
JJ Kasper 已提交
418 419 420 421
          await this.render(
            req,
            res,
            pathname,
422
            { ..._parsedUrl.query, _nextDataReq: '1' },
J
JJ Kasper 已提交
423 424
            parsedUrl
          )
425 426 427
          return {
            finished: true,
          }
J
JJ Kasper 已提交
428 429
        },
      },
T
Tim Neutkens 已提交
430
      {
431
        match: route('/_next/:path*'),
432 433
        type: 'route',
        name: '_next catchall',
T
Tim Neutkens 已提交
434
        // This path is needed because `render()` does a check for `/_next` and the calls the routing again
435
        fn: async (req, res, _params, parsedUrl) => {
T
Tim Neutkens 已提交
436
          await this.render404(req, res, parsedUrl)
437 438 439
          return {
            finished: true,
          }
L
Lukáš Huvar 已提交
440 441
        },
      },
442 443
      ...publicRoutes,
      ...staticFilesRoute,
T
Tim Neutkens 已提交
444
    ]
445

446 447 448 449 450 451
    const getCustomRouteBasePath = (r: { basePath?: false }) => {
      return r.basePath !== false && this.renderOpts.dev
        ? this.nextConfig.basePath
        : ''
    }

452 453 454 455
    const getCustomRoute = (r: Rewrite | Redirect | Header, type: RouteType) =>
      ({
        ...r,
        type,
456
        match: getCustomRouteMatcher(`${getCustomRouteBasePath(r)}${r.source}`),
457 458 459 460 461 462 463
        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
464
      }
465 466 467 468 469 470 471
      const { parsedDestination } = prepareDestination(
        value,
        params,
        {},
        false,
        ''
      )
472 473 474 475 476 477 478 479 480 481 482 483 484

      if (
        !parsedDestination.pathname ||
        !parsedDestination.pathname.startsWith('/')
      ) {
        // the value needs to start with a forward-slash to be compiled
        // correctly
        return compilePathToRegex(`/${value}`, { validate: false })(
          params
        ).substr(1)
      }
      return formatUrl(parsedDestination)
    }
485

486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
    // 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)
501
            }
502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519
            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,
520 521 522
            parsedUrl.query,
            false,
            getCustomRouteBasePath(redirectRoute)
523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
          )
          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 {
546
        ...rewriteRoute,
547 548 549 550 551 552 553 554 555
        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,
556 557
            true,
            getCustomRouteBasePath(rewriteRoute)
558
          )
559

560 561 562 563 564 565 566 567 568 569 570 571 572
          // external rewrite, proxy it
          if (parsedDestination.protocol) {
            const target = formatUrl(parsedDestination)
            const proxy = new Proxy({
              target,
              changeOrigin: true,
              ignorePath: true,
            })
            proxy.web(req, res)

            proxy.on('error', (err: Error) => {
              console.error(`Error occurred proxying ${target}`, err)
            })
573 574 575
            return {
              finished: true,
            }
576 577
          }
          ;(req as any)._nextRewroteUrl = newUrl
578 579
          ;(req as any)._nextDidRewrite =
            (req as any)._nextRewroteUrl !== req.url
580

581 582 583 584 585 586 587 588
          return {
            finished: false,
            pathname: newUrl,
            query: parsedDestination.query,
          }
        },
      } as Route
    })
589 590 591 592 593 594

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

J
Jan Potoms 已提交
600
        // next.js core assumes page path without trailing slash
601
        pathname = removePathTrailingSlash(pathname)
J
Jan Potoms 已提交
602

603
        if (params?.path?.[0] === 'api') {
604 605 606
          const handled = await this.handleApiRequest(
            req as NextApiRequest,
            res as NextApiResponse,
607
            pathname,
608
            query
609 610 611 612 613 614 615
          )
          if (handled) {
            return { finished: true }
          }
        }

        await this.render(req, res, pathname, query, parsedUrl)
616 617 618 619
        return {
          finished: true,
        }
      },
620
    }
621

622
    const { useFileSystemPublicRoutes } = this.nextConfig
J
Joe Haddad 已提交
623

624 625
    if (useFileSystemPublicRoutes) {
      this.dynamicRoutes = this.getDynamicRoutes()
626
    }
N
nkzawa 已提交
627

628
    return {
629
      headers,
630
      fsRoutes,
631 632
      rewrites,
      redirects,
633
      catchAllRoute,
634
      useFileSystemPublicRoutes,
635
      dynamicRoutes: this.dynamicRoutes,
636
      basePath: this.nextConfig.basePath,
637 638
      pageChecker: this.hasPage.bind(this),
    }
T
Tim Neutkens 已提交
639 640
  }

641
  private async getPagePath(pathname: string): Promise<string> {
642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658
    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
  }

659 660 661 662 663
  protected async _beforeCatchAllRender(
    _req: IncomingMessage,
    _res: ServerResponse,
    _params: Params,
    _parsedUrl: UrlWithParsedQuery
664
  ): Promise<boolean> {
665 666 667
    return false
  }

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

L
Lukáš Huvar 已提交
671 672 673 674 675 676
  /**
   * Resolves `API` request, in development builds on demand
   * @param req http request
   * @param res http response
   * @param pathname path of request
   */
J
Joe Haddad 已提交
677
  private async handleApiRequest(
678 679
    req: IncomingMessage,
    res: ServerResponse,
680 681
    pathname: string,
    query: ParsedUrlQuery
682
  ): Promise<boolean> {
683
    let page = pathname
L
Lukáš Huvar 已提交
684
    let params: Params | boolean = false
685
    let pageFound = await this.hasPage(page)
J
JJ Kasper 已提交
686

687
    if (!pageFound && this.dynamicRoutes) {
L
Lukáš Huvar 已提交
688 689
      for (const dynamicRoute of this.dynamicRoutes) {
        params = dynamicRoute.match(pathname)
690
        if (dynamicRoute.page.startsWith('/api') && params) {
691 692
          page = dynamicRoute.page
          pageFound = true
L
Lukáš Huvar 已提交
693 694 695 696 697
          break
        }
      }
    }

698
    if (!pageFound) {
699
      return false
J
JJ Kasper 已提交
700
    }
701 702 703 704
    // Make sure the page is built before getting the path
    // or else it won't be in the manifest yet
    await this.ensureApiPage(page)

705 706 707 708 709 710 711 712 713 714
    let builtPagePath
    try {
      builtPagePath = await this.getPagePath(page)
    } catch (err) {
      if (err.code === 'ENOENT') {
        return false
      }
      throw err
    }

715
    const pageModule = require(builtPagePath)
716
    query = { ...query, ...params }
J
JJ Kasper 已提交
717

718
    if (!this.renderOpts.dev && this._isLikeServerless) {
719
      if (typeof pageModule.default === 'function') {
720
        prepareServerlessUrl(req, query)
721 722
        await pageModule.default(req, res)
        return true
J
JJ Kasper 已提交
723 724 725
      }
    }

J
Joe Haddad 已提交
726 727 728 729 730
    await apiResolver(
      req,
      res,
      query,
      pageModule,
731
      this.renderOpts.previewProps,
732
      false,
J
Joe Haddad 已提交
733 734
      this.onErrorMiddleware
    )
735
    return true
L
Lukáš Huvar 已提交
736 737
  }

738
  protected generatePublicRoutes(): Route[] {
739
    const publicFiles = new Set(
J
Joe Haddad 已提交
740
      recursiveReadDirSync(this.publicDir).map((p) => p.replace(/\\/g, '/'))
741 742 743 744 745 746 747
    )

    return [
      {
        match: route('/:path*'),
        name: 'public folder catchall',
        fn: async (req, res, params, parsedUrl) => {
748 749
          const pathParts: string[] = params.path || []
          const path = `/${pathParts.join('/')}`
750 751 752 753 754 755

          if (publicFiles.has(path)) {
            await this.serveStatic(
              req,
              res,
              // we need to re-encode it since send decodes it
756
              join(this.publicDir, ...pathParts.map(encodeURIComponent)),
757 758
              parsedUrl
            )
759 760 761
            return {
              finished: true,
            }
762 763 764 765 766 767 768
          }
          return {
            finished: false,
          }
        },
      } as Route,
    ]
769 770
  }

771
  protected getDynamicRoutes() {
772 773
    return getSortedRoutes(Object.keys(this.pagesManifest!))
      .filter(isDynamicRoute)
J
Joe Haddad 已提交
774
      .map((page) => ({
775 776 777
        page,
        match: getRouteMatcher(getRouteRegex(page)),
      }))
J
Joe Haddad 已提交
778 779
  }

780
  private handleCompression(req: IncomingMessage, res: ServerResponse): void {
781 782 783 784 785
    if (this.compression) {
      this.compression(req, res, () => {})
    }
  }

786
  protected async run(
J
Joe Haddad 已提交
787 788
    req: IncomingMessage,
    res: ServerResponse,
789
    parsedUrl: UrlWithParsedQuery
790
  ): Promise<void> {
791 792
    this.handleCompression(req, res)

793
    try {
794 795
      const matched = await this.router.execute(req, res, parsedUrl)
      if (matched) {
796 797 798 799 800 801 802 803
        return
      }
    } catch (err) {
      if (err.code === 'DECODE_FAILED') {
        res.statusCode = 400
        return this.renderError(null, req, res, '/_error', {})
      }
      throw err
804 805
    }

806
    await this.render404(req, res, parsedUrl)
N
nkzawa 已提交
807 808
  }

809
  protected async sendHTML(
J
Joe Haddad 已提交
810 811
    req: IncomingMessage,
    res: ServerResponse,
812
    html: string
813
  ): Promise<void> {
T
Tim Neutkens 已提交
814
    const { generateEtags, poweredByHeader } = this.renderOpts
815 816 817 818
    return sendPayload(req, res, html, 'html', {
      generateEtags,
      poweredByHeader,
    })
819 820
  }

J
Joe Haddad 已提交
821 822 823 824 825
  public async render(
    req: IncomingMessage,
    res: ServerResponse,
    pathname: string,
    query: ParsedUrlQuery = {},
826
    parsedUrl?: UrlWithParsedQuery
J
Joe Haddad 已提交
827
  ): Promise<void> {
828 829 830 831 832 833
    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`
      )
    }

834 835 836 837 838 839 840 841 842 843
    if (
      this.renderOpts.customServer &&
      pathname === '/index' &&
      !(await this.hasPage('/index'))
    ) {
      // maintain backwards compatibility for custom server
      // (see custom-server integration tests)
      pathname = '/'
    }

844
    const url: any = req.url
845

846 847 848 849
    // 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
850
    if (
851 852 853
      !query._nextDataReq &&
      (url.match(/^\/_next\//) ||
        (this.hasStaticDir && url.match(/^\/static\//)))
854
    ) {
855 856 857
      return this.handleRequest(req, res, parsedUrl)
    }

858
    if (isBlockedPage(pathname)) {
859
      return this.render404(req, res, parsedUrl)
860 861
    }

862
    const html = await this.renderToHTML(req, res, pathname, query)
863 864
    // Request was ended by the user
    if (html === null) {
865 866 867
      return
    }

868
    return this.sendHTML(req, res, html)
N
Naoyuki Kanezawa 已提交
869
  }
N
nkzawa 已提交
870

J
Joe Haddad 已提交
871
  private async findPageComponents(
J
Joe Haddad 已提交
872
    pathname: string,
873 874 875 876 877 878 879 880 881
    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 已提交
882
      try {
883
        const components = await loadComponents(
J
Joe Haddad 已提交
884
          this.distDir,
885 886
          pagePath!,
          !this.renderOpts.dev && this._isLikeServerless
J
Joe Haddad 已提交
887
        )
888 889 890
        return {
          components,
          query: {
891
            ...(components.getStaticProps
892
              ? { _nextDataReq: query._nextDataReq, amp: query.amp }
893 894 895 896
              : query),
            ...(params || {}),
          },
        }
J
JJ Kasper 已提交
897 898 899 900
      } catch (err) {
        if (err.code !== 'ENOENT') throw err
      }
    }
901
    return null
J
Joe Haddad 已提交
902 903
  }

904
  protected async getStaticPaths(
905 906 907 908 909
    pathname: string
  ): Promise<{
    staticPaths: string[] | undefined
    hasStaticFallback: boolean
  }> {
910 911 912 913 914 915 916 917
    // `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.
    const hasStaticFallback =
      typeof this.getPrerenderManifest().dynamicRoutes[pathname].fallback ===
      'string'
918 919 920 921

    return { staticPaths, hasStaticFallback }
  }

J
Joe Haddad 已提交
922 923 924 925
  private async renderToHTMLWithComponents(
    req: IncomingMessage,
    res: ServerResponse,
    pathname: string,
926
    { components, query }: FindComponentsResult,
927
    opts: RenderOptsPartial
928
  ): Promise<string | null> {
929
    // we need to ensure the status code if /404 is visited directly
930
    if (pathname === '/404') {
931 932 933
      res.statusCode = 404
    }

J
JJ Kasper 已提交
934
    // handle static page
935 936
    if (typeof components.Component === 'string') {
      return components.Component
J
Joe Haddad 已提交
937 938
    }

J
JJ Kasper 已提交
939 940
    // check request state
    const isLikeServerless =
941 942
      typeof components.Component === 'object' &&
      typeof (components.Component as any).renderReqToHTML === 'function'
943 944 945
    const isSSG = !!components.getStaticProps
    const isServerProps = !!components.getServerSideProps
    const hasStaticPaths = !!components.getStaticPaths
946

947 948 949 950
    if (!query.amp) {
      delete query.amp
    }

951
    // Toggle whether or not this is a Data request
952
    const isDataReq = !!query._nextDataReq && (isSSG || isServerProps)
953 954
    delete query._nextDataReq

955 956 957 958 959 960 961 962
    let previewData: string | false | object | undefined
    let isPreviewMode = false

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

963 964 965 966 967 968
    // Compute the iSSG cache key. We use the rewroteUrl since
    // pages with fallback: false are allowed to be rewritten to
    // and we need to look up the path by the rewritten path
    let urlPathname = (req as any)._nextRewroteUrl
      ? (req as any)._nextRewroteUrl
      : `${parseUrl(req.url || '').pathname!}`
969

970 971 972
    // remove trailing slash
    urlPathname = urlPathname.replace(/(?!^)\/$/, '')

973 974 975 976 977 978 979 980
    // remove /_next/data prefix from urlPathname so it matches
    // for direct page visit and /_next/data visit
    if (isDataReq && urlPathname.includes(this.buildId)) {
      urlPathname = (urlPathname.split(this.buildId).pop() || '/')
        .replace(/\.json$/, '')
        .replace(/\/index$/, '/')
    }

981 982 983 984
    const ssgCacheKey =
      isPreviewMode || !isSSG
        ? undefined // Preview mode bypasses the cache
        : `${urlPathname}${query.amp ? '.amp' : ''}`
J
JJ Kasper 已提交
985 986

    // Complete the response with cached data if its present
987 988 989
    const cachedData = ssgCacheKey
      ? await this.incrementalCache.get(ssgCacheKey)
      : undefined
990

J
JJ Kasper 已提交
991
    if (cachedData) {
992
      const data = isDataReq
J
JJ Kasper 已提交
993 994 995
        ? JSON.stringify(cachedData.pageData)
        : cachedData.html

996
      sendPayload(
997
        req,
J
JJ Kasper 已提交
998 999
        res,
        data,
1000
        isDataReq ? 'json' : 'html',
1001 1002 1003 1004
        {
          generateEtags: this.renderOpts.generateEtags,
          poweredByHeader: this.renderOpts.poweredByHeader,
        },
1005 1006 1007 1008 1009 1010 1011 1012 1013
        !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,
            }
1014
          : undefined
J
JJ Kasper 已提交
1015 1016 1017 1018 1019 1020
      )

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

J
JJ Kasper 已提交
1023
    // If we're here, that means data is missing or it's stale.
1024 1025 1026 1027 1028 1029
    const maybeCoalesceInvoke = ssgCacheKey
      ? (fn: any) => withCoalescedInvoke(fn).bind(null, ssgCacheKey, [])
      : (fn: any) => async () => {
          const value = await fn()
          return { isOrigin: true, value }
        }
J
JJ Kasper 已提交
1030

1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048
    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,
            'passthrough'
          )
J
JJ Kasper 已提交
1049

1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070
          html = renderResult.html
          pageData = renderResult.renderOpts.pageData
          sprRevalidate = renderResult.renderOpts.revalidate
        } else {
          const renderOpts: RenderOpts = {
            ...components,
            ...opts,
            isDataReq,
          }
          renderResult = await renderToHTML(
            req,
            res,
            pathname,
            query,
            renderOpts
          )

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

1073
        return { html, pageData, sprRevalidate }
J
JJ Kasper 已提交
1074
      }
1075
    )
J
JJ Kasper 已提交
1076

1077
    const isProduction = !this.renderOpts.dev
J
Joe Haddad 已提交
1078
    const isDynamicPathname = isDynamicRoute(pathname)
1079
    const didRespond = isResSent(res)
1080

1081 1082 1083
    const { staticPaths, hasStaticFallback } = hasStaticPaths
      ? await this.getStaticPaths(pathname)
      : { staticPaths: undefined, hasStaticFallback: false }
1084

1085 1086 1087 1088 1089 1090 1091
    // When we did not respond from cache, we need to choose to block on
    // rendering or return a skeleton.
    //
    // * Data requests always block.
    //
    // * Preview mode toggles all pages to be resolved in a blocking manner.
    //
1092
    // * Non-dynamic pages should block (though this is an impossible
1093 1094
    //   case in production).
    //
1095 1096
    // * Dynamic pages should return their skeleton if not defined in
    //   getStaticPaths, then finish the data request on the client-side.
1097
    //
J
Joe Haddad 已提交
1098
    if (
1099
      ssgCacheKey &&
1100
      !didRespond &&
J
Joe Haddad 已提交
1101
      !isDataReq &&
1102 1103
      !isPreviewMode &&
      isDynamicPathname &&
1104 1105 1106
      // Development should trigger fallback when the path is not in
      // `getStaticPaths`
      (isProduction || !staticPaths || !staticPaths.includes(urlPathname))
J
Joe Haddad 已提交
1107
    ) {
1108 1109 1110 1111 1112 1113 1114
      if (
        // In development, fall through to render to handle missing
        // getStaticPaths.
        (isProduction || staticPaths) &&
        // When fallback isn't present, abort this render so we 404
        !hasStaticFallback
      ) {
1115
        throw new NoFallbackError()
1116 1117
      }

1118
      let html: string
1119

1120 1121
      // Production already emitted the fallback as static HTML.
      if (isProduction) {
1122
        html = await this.incrementalCache.getFallback(pathname)
1123 1124 1125
      }
      // We need to generate the fallback on-demand for development.
      else {
1126 1127
        query.__nextFallback = 'true'
        if (isLikeServerless) {
1128
          prepareServerlessUrl(req, query)
1129
        }
1130 1131
        const { value: renderResult } = await doRender()
        html = renderResult.html
1132 1133
      }

1134 1135 1136 1137
      sendPayload(req, res, html, 'html', {
        generateEtags: this.renderOpts.generateEtags,
        poweredByHeader: this.renderOpts.poweredByHeader,
      })
1138
      return null
1139 1140
    }

1141 1142 1143
    const {
      isOrigin,
      value: { html, pageData, sprRevalidate },
1144
    } = await doRender()
1145 1146
    let resHtml = html
    if (!isResSent(res) && (isSSG || isDataReq || isServerProps)) {
1147
      sendPayload(
1148
        req,
1149 1150
        res,
        isDataReq ? JSON.stringify(pageData) : html,
1151
        isDataReq ? 'json' : 'html',
1152 1153 1154 1155
        {
          generateEtags: this.renderOpts.generateEtags,
          poweredByHeader: this.renderOpts.poweredByHeader,
        },
1156
        !this.renderOpts.dev || (isServerProps && !isDataReq)
1157 1158
          ? {
              private: isPreviewMode,
1159
              stateful: !isSSG,
1160 1161
              revalidate: sprRevalidate,
            }
1162
          : undefined
1163
      )
1164
      resHtml = null
1165
    }
J
JJ Kasper 已提交
1166

1167
    // Update the cache if the head request and cacheable
1168
    if (isOrigin && ssgCacheKey) {
1169 1170 1171 1172 1173
      await this.incrementalCache.set(
        ssgCacheKey,
        { html: html!, pageData },
        sprRevalidate
      )
1174 1175
    }

1176
    return resHtml
1177 1178
  }

1179
  public async renderToHTML(
J
Joe Haddad 已提交
1180 1181 1182
    req: IncomingMessage,
    res: ServerResponse,
    pathname: string,
1183
    query: ParsedUrlQuery = {}
J
Joe Haddad 已提交
1184
  ): Promise<string | null> {
1185 1186 1187
    try {
      const result = await this.findPageComponents(pathname, query)
      if (result) {
1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199
        try {
          return await this.renderToHTMLWithComponents(
            req,
            res,
            pathname,
            result,
            { ...this.renderOpts }
          )
        } catch (err) {
          if (!(err instanceof NoFallbackError)) {
            throw err
          }
1200
        }
1201
      }
J
Joe Haddad 已提交
1202

1203 1204 1205 1206 1207 1208
      if (this.dynamicRoutes) {
        for (const dynamicRoute of this.dynamicRoutes) {
          const params = dynamicRoute.match(pathname)
          if (!params) {
            continue
          }
J
Joe Haddad 已提交
1209

1210
          const dynamicRouteResult = await this.findPageComponents(
1211 1212 1213 1214
            dynamicRoute.page,
            query,
            params
          )
1215
          if (dynamicRouteResult) {
1216 1217 1218 1219 1220
            try {
              return await this.renderToHTMLWithComponents(
                req,
                res,
                dynamicRoute.page,
1221
                dynamicRouteResult,
1222 1223 1224 1225 1226 1227
                { ...this.renderOpts, params }
              )
            } catch (err) {
              if (!(err instanceof NoFallbackError)) {
                throw err
              }
1228
            }
J
Joe Haddad 已提交
1229 1230
          }
        }
1231 1232 1233 1234 1235 1236 1237 1238 1239
      }
    } catch (err) {
      this.logError(err)
      res.statusCode = 500
      return await this.renderErrorToHTML(err, req, res, pathname, query)
    }

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

J
Joe Haddad 已提交
1242 1243 1244 1245 1246
  public async renderError(
    err: Error | null,
    req: IncomingMessage,
    res: ServerResponse,
    pathname: string,
1247
    query: ParsedUrlQuery = {}
J
Joe Haddad 已提交
1248 1249 1250
  ): Promise<void> {
    res.setHeader(
      'Cache-Control',
1251
      'no-cache, no-store, max-age=0, must-revalidate'
J
Joe Haddad 已提交
1252
    )
N
Naoyuki Kanezawa 已提交
1253
    const html = await this.renderErrorToHTML(err, req, res, pathname, query)
1254
    if (html === null) {
1255 1256
      return
    }
1257
    return this.sendHTML(req, res, html)
N
nkzawa 已提交
1258 1259
  }

1260 1261 1262 1263 1264 1265 1266 1267 1268
  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 已提交
1269 1270 1271 1272 1273
  public async renderErrorToHTML(
    err: Error | null,
    req: IncomingMessage,
    res: ServerResponse,
    _pathname: string,
1274
    query: ParsedUrlQuery = {}
J
Joe Haddad 已提交
1275
  ) {
1276
    let result: null | FindComponentsResult = null
1277

1278 1279 1280
    const is404 = res.statusCode === 404
    let using404Page = false

1281
    // use static 404 page if available and is 404 response
1282
    if (is404) {
1283 1284
      result = await this.findPageComponents('/404')
      using404Page = result !== null
1285 1286 1287 1288 1289 1290
    }

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

1291 1292 1293
    if (
      process.env.NODE_ENV !== 'production' &&
      !using404Page &&
1294 1295
      (await this.hasPage('/_error')) &&
      !(await this.hasPage('/404'))
1296 1297 1298 1299
    ) {
      this.customErrorNo404Warn()
    }

1300
    let html: string | null
1301
    try {
1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312
      try {
        html = await this.renderToHTMLWithComponents(
          req,
          res,
          using404Page ? '/404' : '/_error',
          result!,
          {
            ...this.renderOpts,
            err,
          }
        )
1313 1314
      } catch (maybeFallbackError) {
        if (maybeFallbackError instanceof NoFallbackError) {
1315
          throw new Error('invariant: failed to render error page')
1316
        }
1317
        throw maybeFallbackError
1318
      }
1319 1320
    } catch (renderToHtmlError) {
      console.error(renderToHtmlError)
1321 1322 1323 1324
      res.statusCode = 500
      html = 'Internal Server Error'
    }
    return html
N
Naoyuki Kanezawa 已提交
1325 1326
  }

J
Joe Haddad 已提交
1327 1328 1329
  public async render404(
    req: IncomingMessage,
    res: ServerResponse,
1330
    parsedUrl?: UrlWithParsedQuery
J
Joe Haddad 已提交
1331
  ): Promise<void> {
1332 1333
    const url: any = req.url
    const { pathname, query } = parsedUrl ? parsedUrl : parseUrl(url, true)
N
Naoyuki Kanezawa 已提交
1334
    res.statusCode = 404
1335
    return this.renderError(null, req, res, pathname!, query)
N
Naoyuki Kanezawa 已提交
1336
  }
N
Naoyuki Kanezawa 已提交
1337

J
Joe Haddad 已提交
1338 1339 1340 1341
  public async serveStatic(
    req: IncomingMessage,
    res: ServerResponse,
    path: string,
1342
    parsedUrl?: UrlWithParsedQuery
J
Joe Haddad 已提交
1343
  ): Promise<void> {
A
Arunoda Susiripala 已提交
1344
    if (!this.isServeableUrl(path)) {
1345
      return this.render404(req, res, parsedUrl)
A
Arunoda Susiripala 已提交
1346 1347
    }

1348 1349 1350 1351 1352 1353
    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 已提交
1354
    try {
1355
      await serveStatic(req, res, path)
N
Naoyuki Kanezawa 已提交
1356
    } catch (err) {
T
Tim Neutkens 已提交
1357
      if (err.code === 'ENOENT' || err.statusCode === 404) {
1358
        this.render404(req, res, parsedUrl)
1359 1360 1361
      } else if (err.statusCode === 412) {
        res.statusCode = 412
        return this.renderError(err, req, res, path)
N
Naoyuki Kanezawa 已提交
1362 1363 1364 1365 1366 1367
      } else {
        throw err
      }
    }
  }

1368 1369 1370 1371 1372 1373 1374 1375 1376
  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 已提交
1377
      userFilesStatic = recursiveReadDirSync(pathUserFilesStatic).map((f) =>
1378 1379 1380 1381 1382 1383
        join('.', 'static', f)
      )
    }

    let userFilesPublic: string[] = []
    if (this.publicDir && fs.existsSync(this.publicDir)) {
J
Joe Haddad 已提交
1384
      userFilesPublic = recursiveReadDirSync(this.publicDir).map((f) =>
1385 1386 1387 1388 1389 1390 1391
        join('.', 'public', f)
      )
    }

    let nextFilesStatic: string[] = []
    nextFilesStatic = recursiveReadDirSync(
      join(this.distDir, 'static')
J
Joe Haddad 已提交
1392
    ).map((f) => join('.', relative(this.dir, this.distDir), 'static', f))
1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426

    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 已提交
1427
    if (
1428 1429 1430
      (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 已提交
1431 1432 1433 1434
    ) {
      return false
    }

1435 1436 1437 1438
    // Check against the real filesystem paths
    const filesystemUrls = this.getFilesystemPaths()
    const resolved = relative(this.dir, untrustedFilePath)
    return filesystemUrls.has(resolved)
A
Arunoda Susiripala 已提交
1439 1440
  }

1441
  protected readBuildId(): string {
1442 1443 1444 1445 1446
    const buildIdFile = join(this.distDir, BUILD_ID_FILE)
    try {
      return fs.readFileSync(buildIdFile, 'utf8').trim()
    } catch (err) {
      if (!fs.existsSync(buildIdFile)) {
J
Joe Haddad 已提交
1447
        throw new Error(
1448
          `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 已提交
1449
        )
1450 1451 1452
      }

      throw err
1453
    }
1454
  }
1455

1456
  protected get _isLikeServerless(): boolean {
1457 1458
    return isTargetLikeServerless(this.nextConfig.target)
  }
1459
}
1460

1461 1462 1463 1464
function prepareServerlessUrl(
  req: IncomingMessage,
  query: ParsedUrlQuery
): void {
1465 1466 1467 1468 1469 1470 1471 1472 1473 1474
  const curUrl = parseUrl(req.url!, true)
  req.url = formatUrl({
    ...curUrl,
    search: undefined,
    query: {
      ...curUrl.query,
      ...query,
    },
  })
}
1475 1476

class NoFallbackError extends Error {}