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'
J
Joe Haddad 已提交
55
import { sendHTML } from './send-html'
56
import { sendPayload } from './send-payload'
J
Joe Haddad 已提交
57
import { serveStatic } from './serve-static'
58
import { IncrementalCache } from './incremental-cache'
59
import { execOnce } from '../lib/utils'
60
import { isBlockedPage } from './utils'
61
import { compile as compilePathToRegex } from 'next/dist/compiled/path-to-regexp'
62
import { loadEnvConfig } from '../../lib/load-env-config'
63
import './node-polyfill-fetch'
J
Jan Potoms 已提交
64
import { PagesManifest } from '../../build/webpack/plugins/pages-manifest-plugin'
65
import { removePathTrailingSlash } from '../../client/normalize-trailing-slash'
66
import getRouteFromAssetPath from '../lib/router/utils/get-route-from-asset-path'
J
JJ Kasper 已提交
67 68

const getCustomRouteMatcher = pathMatch(true)
69 70 71

type NextConfig = any

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

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

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

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

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

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

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

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

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

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

180
    if (compress && this.nextConfig.target === 'server') {
181 182 183
      this.compression = compression() as Middleware
    }

184
    // Initialize next/config with the environment configuration
185 186 187 188
    envConfig.setConfig({
      serverRuntimeConfig,
      publicRuntimeConfig,
    })
189

190 191 192 193 194 195 196 197 198 199
    this.serverBuildDir = join(
      this.distDir,
      this._isLikeServerless ? SERVERLESS_DIRECTORY : SERVER_DIRECTORY
    )
    const pagesManifestPath = join(this.serverBuildDir, PAGES_MANIFEST)

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

200
    this.customRoutes = this.getCustomRoutes()
J
JJ Kasper 已提交
201
    this.router = new Router(this.generateRoutes())
202
    this.setAssetPrefix(assetPrefix)
J
JJ Kasper 已提交
203

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

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

228
  protected currentPhase(): string {
229
    return PHASE_PRODUCTION_SERVER
230 231
  }

232 233 234 235
  private logError(err: Error): void {
    if (this.onErrorMiddleware) {
      this.onErrorMiddleware({ err })
    }
236 237
    if (this.quiet) return
    // tslint:disable-next-line
238
    console.error(err)
239 240
  }

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

252 253 254
    // 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 已提交
255
    }
256

257
    const { basePath } = this.nextConfig
258 259 260 261 262

    // if basePath is set require it be present
    if (basePath && !req.url!.startsWith(basePath)) {
      return this.render404(req, res, parsedUrl)
    } else {
T
Tim Neutkens 已提交
263
      // If replace ends up replacing the full url it'll be `undefined`, meaning we have to default it to `/`
264 265
      parsedUrl.pathname = parsedUrl.pathname!.replace(basePath, '') || '/'
      req.url = req.url!.replace(basePath, '')
T
Tim Neutkens 已提交
266 267
    }

268
    res.statusCode = 200
269 270 271
    try {
      return await this.run(req, res, parsedUrl)
    } catch (err) {
J
Joe Haddad 已提交
272 273 274
      this.logError(err)
      res.statusCode = 500
      res.end('Internal Server Error')
275
    }
276 277
  }

278
  public getRequestHandler() {
279
    return this.handleRequest.bind(this)
N
nkzawa 已提交
280 281
  }

282
  public setAssetPrefix(prefix?: string): void {
283
    this.renderOpts.assetPrefix = prefix ? prefix.replace(/\/$/, '') : ''
284 285
  }

286
  // Backwards compatibility
287
  public async prepare(): Promise<void> {}
N
nkzawa 已提交
288

T
Tim Neutkens 已提交
289
  // Backwards compatibility
290
  protected async close(): Promise<void> {}
T
Tim Neutkens 已提交
291

292
  protected setImmutableAssetCacheControl(res: ServerResponse): void {
T
Tim Neutkens 已提交
293
    res.setHeader('Cache-Control', 'public, max-age=31536000, immutable')
N
nkzawa 已提交
294 295
  }

296
  protected getCustomRoutes(): CustomRoutes {
J
JJ Kasper 已提交
297 298 299
    return require(join(this.distDir, ROUTES_MANIFEST))
  }

300 301 302 303
  private _cachedPreviewManifest: PrerenderManifest | undefined
  protected getPrerenderManifest(): PrerenderManifest {
    if (this._cachedPreviewManifest) {
      return this._cachedPreviewManifest
J
Joe Haddad 已提交
304
    }
305 306 307 308 309 310
    const manifest = require(join(this.distDir, PRERENDER_MANIFEST))
    return (this._cachedPreviewManifest = manifest)
  }

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

313
  protected generateRoutes(): {
314 315
    headers: Route[]
    rewrites: Route[]
316
    fsRoutes: Route[]
317
    redirects: Route[]
318 319
    catchAllRoute: Route
    pageChecker: PageChecker
320
    useFileSystemPublicRoutes: boolean
321 322
    dynamicRoutes: DynamicRoutes | undefined
  } {
323 324 325
    const publicRoutes = fs.existsSync(this.publicDir)
      ? this.generatePublicRoutes()
      : []
J
JJ Kasper 已提交
326

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

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

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

          // re-create page's pathname
412 413 414 415 416 417 418 419
          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 已提交
420

J
JJ Kasper 已提交
421
          const parsedUrl = parseUrl(pathname, true)
422

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

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

      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)
    }
478

479 480 481 482 483 484 485 486 487 488 489 490 491 492 493
    // 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)
494
            }
495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547
            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,
            parsedUrl.query
          )
          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 {
        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,
            true
          )
548

549 550 551 552 553 554 555 556 557 558 559 560 561
          // 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)
            })
562 563 564
            return {
              finished: true,
            }
565 566 567
          }
          ;(req as any)._nextDidRewrite = true
          ;(req as any)._nextRewroteUrl = newUrl
568

569 570 571 572 573 574 575 576
          return {
            finished: false,
            pathname: newUrl,
            query: parsedDestination.query,
          }
        },
      } as Route
    })
577 578 579 580 581 582

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

J
Jan Potoms 已提交
588
        // next.js core assumes page path without trailing slash
589
        pathname = removePathTrailingSlash(pathname)
J
Jan Potoms 已提交
590

591
        if (params?.path?.[0] === 'api') {
592 593 594
          const handled = await this.handleApiRequest(
            req as NextApiRequest,
            res as NextApiResponse,
595
            pathname,
596
            query
597 598 599 600 601 602 603
          )
          if (handled) {
            return { finished: true }
          }
        }

        await this.render(req, res, pathname, query, parsedUrl)
604 605 606 607
        return {
          finished: true,
        }
      },
608
    }
609

610
    const { useFileSystemPublicRoutes } = this.nextConfig
J
Joe Haddad 已提交
611

612 613
    if (useFileSystemPublicRoutes) {
      this.dynamicRoutes = this.getDynamicRoutes()
614
    }
N
nkzawa 已提交
615

616
    return {
617
      headers,
618
      fsRoutes,
619 620
      rewrites,
      redirects,
621
      catchAllRoute,
622
      useFileSystemPublicRoutes,
623 624 625
      dynamicRoutes: this.dynamicRoutes,
      pageChecker: this.hasPage.bind(this),
    }
T
Tim Neutkens 已提交
626 627
  }

628
  private async getPagePath(pathname: string): Promise<string> {
629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645
    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
  }

646 647 648 649 650
  protected async _beforeCatchAllRender(
    _req: IncomingMessage,
    _res: ServerResponse,
    _params: Params,
    _parsedUrl: UrlWithParsedQuery
651
  ): Promise<boolean> {
652 653 654
    return false
  }

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

L
Lukáš Huvar 已提交
658 659 660 661 662 663
  /**
   * Resolves `API` request, in development builds on demand
   * @param req http request
   * @param res http response
   * @param pathname path of request
   */
J
Joe Haddad 已提交
664
  private async handleApiRequest(
665 666
    req: IncomingMessage,
    res: ServerResponse,
667 668
    pathname: string,
    query: ParsedUrlQuery
669
  ): Promise<boolean> {
670
    let page = pathname
L
Lukáš Huvar 已提交
671
    let params: Params | boolean = false
672
    let pageFound = await this.hasPage(page)
J
JJ Kasper 已提交
673

674
    if (!pageFound && this.dynamicRoutes) {
L
Lukáš Huvar 已提交
675 676
      for (const dynamicRoute of this.dynamicRoutes) {
        params = dynamicRoute.match(pathname)
677
        if (dynamicRoute.page.startsWith('/api') && params) {
678 679
          page = dynamicRoute.page
          pageFound = true
L
Lukáš Huvar 已提交
680 681 682 683 684
          break
        }
      }
    }

685
    if (!pageFound) {
686
      return false
J
JJ Kasper 已提交
687
    }
688 689 690 691
    // Make sure the page is built before getting the path
    // or else it won't be in the manifest yet
    await this.ensureApiPage(page)

692 693 694 695 696 697 698 699 700 701
    let builtPagePath
    try {
      builtPagePath = await this.getPagePath(page)
    } catch (err) {
      if (err.code === 'ENOENT') {
        return false
      }
      throw err
    }

702
    const pageModule = require(builtPagePath)
703
    query = { ...query, ...params }
J
JJ Kasper 已提交
704

705
    if (!this.renderOpts.dev && this._isLikeServerless) {
706
      if (typeof pageModule.default === 'function') {
707
        prepareServerlessUrl(req, query)
708 709
        await pageModule.default(req, res)
        return true
J
JJ Kasper 已提交
710 711 712
      }
    }

J
Joe Haddad 已提交
713 714 715 716 717
    await apiResolver(
      req,
      res,
      query,
      pageModule,
718
      this.renderOpts.previewProps,
719
      false,
J
Joe Haddad 已提交
720 721
      this.onErrorMiddleware
    )
722
    return true
L
Lukáš Huvar 已提交
723 724
  }

725
  protected generatePublicRoutes(): Route[] {
726
    const publicFiles = new Set(
J
Joe Haddad 已提交
727
      recursiveReadDirSync(this.publicDir).map((p) => p.replace(/\\/g, '/'))
728 729 730 731 732 733 734
    )

    return [
      {
        match: route('/:path*'),
        name: 'public folder catchall',
        fn: async (req, res, params, parsedUrl) => {
735 736
          const pathParts: string[] = params.path || []
          const path = `/${pathParts.join('/')}`
737 738 739 740 741 742

          if (publicFiles.has(path)) {
            await this.serveStatic(
              req,
              res,
              // we need to re-encode it since send decodes it
743
              join(this.publicDir, ...pathParts.map(encodeURIComponent)),
744 745
              parsedUrl
            )
746 747 748
            return {
              finished: true,
            }
749 750 751 752 753 754 755
          }
          return {
            finished: false,
          }
        },
      } as Route,
    ]
756 757
  }

758
  protected getDynamicRoutes() {
759 760
    return getSortedRoutes(Object.keys(this.pagesManifest!))
      .filter(isDynamicRoute)
J
Joe Haddad 已提交
761
      .map((page) => ({
762 763 764
        page,
        match: getRouteMatcher(getRouteRegex(page)),
      }))
J
Joe Haddad 已提交
765 766
  }

767
  private handleCompression(req: IncomingMessage, res: ServerResponse): void {
768 769 770 771 772
    if (this.compression) {
      this.compression(req, res, () => {})
    }
  }

773
  protected async run(
J
Joe Haddad 已提交
774 775
    req: IncomingMessage,
    res: ServerResponse,
776
    parsedUrl: UrlWithParsedQuery
777
  ): Promise<void> {
778 779
    this.handleCompression(req, res)

780
    try {
781 782
      const matched = await this.router.execute(req, res, parsedUrl)
      if (matched) {
783 784 785 786 787 788 789 790
        return
      }
    } catch (err) {
      if (err.code === 'DECODE_FAILED') {
        res.statusCode = 400
        return this.renderError(null, req, res, '/_error', {})
      }
      throw err
791 792
    }

793
    await this.render404(req, res, parsedUrl)
N
nkzawa 已提交
794 795
  }

796
  protected async sendHTML(
J
Joe Haddad 已提交
797 798
    req: IncomingMessage,
    res: ServerResponse,
799
    html: string
800
  ): Promise<void> {
T
Tim Neutkens 已提交
801 802
    const { generateEtags, poweredByHeader } = this.renderOpts
    return sendHTML(req, res, html, { generateEtags, poweredByHeader })
803 804
  }

J
Joe Haddad 已提交
805 806 807 808 809
  public async render(
    req: IncomingMessage,
    res: ServerResponse,
    pathname: string,
    query: ParsedUrlQuery = {},
810
    parsedUrl?: UrlWithParsedQuery
J
Joe Haddad 已提交
811
  ): Promise<void> {
812 813 814 815 816 817
    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`
      )
    }

818 819 820 821 822 823 824 825 826 827
    if (
      this.renderOpts.customServer &&
      pathname === '/index' &&
      !(await this.hasPage('/index'))
    ) {
      // maintain backwards compatibility for custom server
      // (see custom-server integration tests)
      pathname = '/'
    }

828
    const url: any = req.url
829

830 831 832 833
    // 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
834
    if (
835 836 837
      !query._nextDataReq &&
      (url.match(/^\/_next\//) ||
        (this.hasStaticDir && url.match(/^\/static\//)))
838
    ) {
839 840 841
      return this.handleRequest(req, res, parsedUrl)
    }

842
    if (isBlockedPage(pathname)) {
843
      return this.render404(req, res, parsedUrl)
844 845
    }

846
    const html = await this.renderToHTML(req, res, pathname, query)
847 848
    // Request was ended by the user
    if (html === null) {
849 850 851
      return
    }

852
    return this.sendHTML(req, res, html)
N
Naoyuki Kanezawa 已提交
853
  }
N
nkzawa 已提交
854

J
Joe Haddad 已提交
855
  private async findPageComponents(
J
Joe Haddad 已提交
856
    pathname: string,
857 858 859 860 861 862 863 864 865
    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 已提交
866
      try {
867
        const components = await loadComponents(
J
Joe Haddad 已提交
868
          this.distDir,
869 870
          pagePath!,
          !this.renderOpts.dev && this._isLikeServerless
J
Joe Haddad 已提交
871
        )
872 873 874
        return {
          components,
          query: {
875
            ...(components.getStaticProps
876
              ? { _nextDataReq: query._nextDataReq, amp: query.amp }
877 878 879 880
              : query),
            ...(params || {}),
          },
        }
J
JJ Kasper 已提交
881 882 883 884
      } catch (err) {
        if (err.code !== 'ENOENT') throw err
      }
    }
885
    return null
J
Joe Haddad 已提交
886 887
  }

888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927
  private async getStaticPaths(
    pathname: string
  ): Promise<{
    staticPaths: string[] | undefined
    hasStaticFallback: boolean
  }> {
    // we lazy load the staticPaths to prevent the user
    // from waiting on them for the page to load in dev mode
    let staticPaths: string[] | undefined
    let hasStaticFallback = false

    if (!this.renderOpts.dev) {
      // `staticPaths` is intentionally set to `undefined` as it should've
      // been caught when checking disk data.
      staticPaths = undefined

      // Read whether or not fallback should exist from the manifest.
      hasStaticFallback =
        typeof this.getPrerenderManifest().dynamicRoutes[pathname].fallback ===
        'string'
    } else {
      const __getStaticPaths = async () => {
        const paths = await this.staticPathsWorker!.loadStaticPaths(
          this.distDir,
          pathname,
          !this.renderOpts.dev && this._isLikeServerless
        )
        return paths
      }
      ;({ paths: staticPaths, fallback: hasStaticFallback } = (
        await withCoalescedInvoke(__getStaticPaths)(
          `staticPaths-${pathname}`,
          []
        )
      ).value)
    }

    return { staticPaths, hasStaticFallback }
  }

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

J
JJ Kasper 已提交
940
    // handle static page
941 942
    if (typeof components.Component === 'string') {
      return components.Component
J
Joe Haddad 已提交
943 944
    }

J
JJ Kasper 已提交
945 946
    // check request state
    const isLikeServerless =
947 948
      typeof components.Component === 'object' &&
      typeof (components.Component as any).renderReqToHTML === 'function'
949 950 951
    const isSSG = !!components.getStaticProps
    const isServerProps = !!components.getServerSideProps
    const hasStaticPaths = !!components.getStaticPaths
952

953 954 955 956
    if (!query.amp) {
      delete query.amp
    }

957
    // Toggle whether or not this is a Data request
958
    const isDataReq = !!query._nextDataReq && (isSSG || isServerProps)
959 960
    delete query._nextDataReq

961 962 963 964 965 966 967 968
    let previewData: string | false | object | undefined
    let isPreviewMode = false

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

969 970 971 972 973 974
    // 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!}`
975

976 977 978
    // remove trailing slash
    urlPathname = urlPathname.replace(/(?!^)\/$/, '')

979 980 981 982 983 984 985 986
    // 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$/, '/')
    }

987 988 989 990
    const ssgCacheKey =
      isPreviewMode || !isSSG
        ? undefined // Preview mode bypasses the cache
        : `${urlPathname}${query.amp ? '.amp' : ''}`
J
JJ Kasper 已提交
991 992

    // Complete the response with cached data if its present
993 994 995
    const cachedData = ssgCacheKey
      ? await this.incrementalCache.get(ssgCacheKey)
      : undefined
996

J
JJ Kasper 已提交
997
    if (cachedData) {
998
      const data = isDataReq
J
JJ Kasper 已提交
999 1000 1001
        ? JSON.stringify(cachedData.pageData)
        : cachedData.html

1002
      sendPayload(
J
JJ Kasper 已提交
1003 1004
        res,
        data,
1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
        isDataReq ? 'json' : 'html',
        !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,
            }
1015
          : undefined
J
JJ Kasper 已提交
1016 1017 1018 1019 1020 1021
      )

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

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

J
Joe Haddad 已提交
1032
    const doRender = maybeCoalesceInvoke(async function (): Promise<{
J
JJ Kasper 已提交
1033
      html: string | null
1034
      pageData: any
J
JJ Kasper 已提交
1035 1036
      sprRevalidate: number | false
    }> {
1037
      let pageData: any
J
JJ Kasper 已提交
1038 1039 1040 1041 1042 1043
      let html: string | null
      let sprRevalidate: number | false

      let renderResult
      // handle serverless
      if (isLikeServerless) {
1044
        renderResult = await (components.Component as any).renderReqToHTML(
1045 1046
          req,
          res,
1047
          'passthrough'
1048
        )
J
JJ Kasper 已提交
1049 1050

        html = renderResult.html
1051
        pageData = renderResult.renderOpts.pageData
J
JJ Kasper 已提交
1052 1053
        sprRevalidate = renderResult.renderOpts.revalidate
      } else {
1054
        const renderOpts: RenderOpts = {
1055
          ...components,
J
JJ Kasper 已提交
1056
          ...opts,
1057
          isDataReq,
J
JJ Kasper 已提交
1058 1059 1060 1061
        }
        renderResult = await renderToHTML(req, res, pathname, query, renderOpts)

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

1067
      return { html, pageData, sprRevalidate }
1068
    })
J
JJ Kasper 已提交
1069

1070
    const isProduction = !this.renderOpts.dev
J
Joe Haddad 已提交
1071
    const isDynamicPathname = isDynamicRoute(pathname)
1072
    const didRespond = isResSent(res)
1073

1074 1075 1076
    const { staticPaths, hasStaticFallback } = hasStaticPaths
      ? await this.getStaticPaths(pathname)
      : { staticPaths: undefined, hasStaticFallback: false }
1077

1078 1079 1080 1081 1082 1083 1084 1085 1086 1087
    // const isForcedBlocking =
    //   req.headers['X-Prerender-Bypass-Mode'] !== 'Blocking'

    // 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.
    //
1088
    // * Non-dynamic pages should block (though this is an impossible
1089 1090
    //   case in production).
    //
1091 1092
    // * Dynamic pages should return their skeleton if not defined in
    //   getStaticPaths, then finish the data request on the client-side.
1093
    //
J
Joe Haddad 已提交
1094
    if (
1095
      ssgCacheKey &&
1096
      !didRespond &&
J
Joe Haddad 已提交
1097
      !isDataReq &&
1098 1099
      !isPreviewMode &&
      isDynamicPathname &&
1100 1101 1102
      // Development should trigger fallback when the path is not in
      // `getStaticPaths`
      (isProduction || !staticPaths || !staticPaths.includes(urlPathname))
J
Joe Haddad 已提交
1103
    ) {
1104 1105 1106 1107 1108 1109 1110
      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
      ) {
1111
        throw new NoFallbackError()
1112 1113
      }

1114
      let html: string
1115

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

1130
      sendPayload(res, html, 'html')
1131
      return null
1132 1133
    }

1134 1135 1136
    const {
      isOrigin,
      value: { html, pageData, sprRevalidate },
1137
    } = await doRender()
1138 1139
    let resHtml = html
    if (!isResSent(res) && (isSSG || isDataReq || isServerProps)) {
1140
      sendPayload(
1141 1142
        res,
        isDataReq ? JSON.stringify(pageData) : html,
1143
        isDataReq ? 'json' : 'html',
1144
        !this.renderOpts.dev || (isServerProps && !isDataReq)
1145 1146
          ? {
              private: isPreviewMode,
1147
              stateful: !isSSG,
1148 1149
              revalidate: sprRevalidate,
            }
1150
          : undefined
1151
      )
1152
      resHtml = null
1153
    }
J
JJ Kasper 已提交
1154

1155
    // Update the cache if the head request and cacheable
1156
    if (isOrigin && ssgCacheKey) {
1157 1158 1159 1160 1161
      await this.incrementalCache.set(
        ssgCacheKey,
        { html: html!, pageData },
        sprRevalidate
      )
1162 1163
    }

1164
    return resHtml
1165 1166
  }

1167
  public async renderToHTML(
J
Joe Haddad 已提交
1168 1169 1170
    req: IncomingMessage,
    res: ServerResponse,
    pathname: string,
1171
    query: ParsedUrlQuery = {}
J
Joe Haddad 已提交
1172
  ): Promise<string | null> {
1173 1174 1175
    try {
      const result = await this.findPageComponents(pathname, query)
      if (result) {
1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
        try {
          return await this.renderToHTMLWithComponents(
            req,
            res,
            pathname,
            result,
            { ...this.renderOpts }
          )
        } catch (err) {
          if (!(err instanceof NoFallbackError)) {
            throw err
          }
1188
        }
1189
      }
J
Joe Haddad 已提交
1190

1191 1192 1193 1194 1195 1196
      if (this.dynamicRoutes) {
        for (const dynamicRoute of this.dynamicRoutes) {
          const params = dynamicRoute.match(pathname)
          if (!params) {
            continue
          }
J
Joe Haddad 已提交
1197

1198
          const dynamicRouteResult = await this.findPageComponents(
1199 1200 1201 1202
            dynamicRoute.page,
            query,
            params
          )
1203
          if (dynamicRouteResult) {
1204 1205 1206 1207 1208
            try {
              return await this.renderToHTMLWithComponents(
                req,
                res,
                dynamicRoute.page,
1209
                dynamicRouteResult,
1210 1211 1212 1213 1214 1215
                { ...this.renderOpts, params }
              )
            } catch (err) {
              if (!(err instanceof NoFallbackError)) {
                throw err
              }
1216
            }
J
Joe Haddad 已提交
1217 1218
          }
        }
1219 1220 1221 1222 1223 1224 1225 1226 1227
      }
    } 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 已提交
1228 1229
  }

J
Joe Haddad 已提交
1230 1231 1232 1233 1234
  public async renderError(
    err: Error | null,
    req: IncomingMessage,
    res: ServerResponse,
    pathname: string,
1235
    query: ParsedUrlQuery = {}
J
Joe Haddad 已提交
1236 1237 1238
  ): Promise<void> {
    res.setHeader(
      'Cache-Control',
1239
      'no-cache, no-store, max-age=0, must-revalidate'
J
Joe Haddad 已提交
1240
    )
N
Naoyuki Kanezawa 已提交
1241
    const html = await this.renderErrorToHTML(err, req, res, pathname, query)
1242
    if (html === null) {
1243 1244
      return
    }
1245
    return this.sendHTML(req, res, html)
N
nkzawa 已提交
1246 1247
  }

1248 1249 1250 1251 1252 1253 1254 1255 1256
  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 已提交
1257 1258 1259 1260 1261
  public async renderErrorToHTML(
    err: Error | null,
    req: IncomingMessage,
    res: ServerResponse,
    _pathname: string,
1262
    query: ParsedUrlQuery = {}
J
Joe Haddad 已提交
1263
  ) {
1264
    let result: null | FindComponentsResult = null
1265

1266 1267 1268
    const is404 = res.statusCode === 404
    let using404Page = false

1269
    // use static 404 page if available and is 404 response
1270
    if (is404) {
1271 1272
      result = await this.findPageComponents('/404')
      using404Page = result !== null
1273 1274 1275 1276 1277 1278
    }

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

1279 1280 1281
    if (
      process.env.NODE_ENV !== 'production' &&
      !using404Page &&
1282 1283
      (await this.hasPage('/_error')) &&
      !(await this.hasPage('/404'))
1284 1285 1286 1287
    ) {
      this.customErrorNo404Warn()
    }

1288
    let html: string | null
1289
    try {
1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300
      try {
        html = await this.renderToHTMLWithComponents(
          req,
          res,
          using404Page ? '/404' : '/_error',
          result!,
          {
            ...this.renderOpts,
            err,
          }
        )
1301 1302
      } catch (maybeFallbackError) {
        if (maybeFallbackError instanceof NoFallbackError) {
1303
          throw new Error('invariant: failed to render error page')
1304
        }
1305
        throw maybeFallbackError
1306
      }
1307 1308
    } catch (renderToHtmlError) {
      console.error(renderToHtmlError)
1309 1310 1311 1312
      res.statusCode = 500
      html = 'Internal Server Error'
    }
    return html
N
Naoyuki Kanezawa 已提交
1313 1314
  }

J
Joe Haddad 已提交
1315 1316 1317
  public async render404(
    req: IncomingMessage,
    res: ServerResponse,
1318
    parsedUrl?: UrlWithParsedQuery
J
Joe Haddad 已提交
1319
  ): Promise<void> {
1320 1321
    const url: any = req.url
    const { pathname, query } = parsedUrl ? parsedUrl : parseUrl(url, true)
N
Naoyuki Kanezawa 已提交
1322
    res.statusCode = 404
1323
    return this.renderError(null, req, res, pathname!, query)
N
Naoyuki Kanezawa 已提交
1324
  }
N
Naoyuki Kanezawa 已提交
1325

J
Joe Haddad 已提交
1326 1327 1328 1329
  public async serveStatic(
    req: IncomingMessage,
    res: ServerResponse,
    path: string,
1330
    parsedUrl?: UrlWithParsedQuery
J
Joe Haddad 已提交
1331
  ): Promise<void> {
A
Arunoda Susiripala 已提交
1332
    if (!this.isServeableUrl(path)) {
1333
      return this.render404(req, res, parsedUrl)
A
Arunoda Susiripala 已提交
1334 1335
    }

1336 1337 1338 1339 1340 1341
    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 已提交
1342
    try {
1343
      await serveStatic(req, res, path)
N
Naoyuki Kanezawa 已提交
1344
    } catch (err) {
T
Tim Neutkens 已提交
1345
      if (err.code === 'ENOENT' || err.statusCode === 404) {
1346
        this.render404(req, res, parsedUrl)
1347 1348 1349
      } else if (err.statusCode === 412) {
        res.statusCode = 412
        return this.renderError(err, req, res, path)
N
Naoyuki Kanezawa 已提交
1350 1351 1352 1353 1354 1355
      } else {
        throw err
      }
    }
  }

1356 1357 1358 1359 1360 1361 1362 1363 1364
  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 已提交
1365
      userFilesStatic = recursiveReadDirSync(pathUserFilesStatic).map((f) =>
1366 1367 1368 1369 1370 1371
        join('.', 'static', f)
      )
    }

    let userFilesPublic: string[] = []
    if (this.publicDir && fs.existsSync(this.publicDir)) {
J
Joe Haddad 已提交
1372
      userFilesPublic = recursiveReadDirSync(this.publicDir).map((f) =>
1373 1374 1375 1376 1377 1378 1379
        join('.', 'public', f)
      )
    }

    let nextFilesStatic: string[] = []
    nextFilesStatic = recursiveReadDirSync(
      join(this.distDir, 'static')
J
Joe Haddad 已提交
1380
    ).map((f) => join('.', relative(this.dir, this.distDir), 'static', f))
1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414

    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 已提交
1415
    if (
1416 1417 1418
      (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 已提交
1419 1420 1421 1422
    ) {
      return false
    }

1423 1424 1425 1426
    // Check against the real filesystem paths
    const filesystemUrls = this.getFilesystemPaths()
    const resolved = relative(this.dir, untrustedFilePath)
    return filesystemUrls.has(resolved)
A
Arunoda Susiripala 已提交
1427 1428
  }

1429
  protected readBuildId(): string {
1430 1431 1432 1433 1434
    const buildIdFile = join(this.distDir, BUILD_ID_FILE)
    try {
      return fs.readFileSync(buildIdFile, 'utf8').trim()
    } catch (err) {
      if (!fs.existsSync(buildIdFile)) {
J
Joe Haddad 已提交
1435
        throw new Error(
1436
          `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 已提交
1437
        )
1438 1439 1440
      }

      throw err
1441
    }
1442
  }
1443 1444 1445 1446

  private get _isLikeServerless(): boolean {
    return isTargetLikeServerless(this.nextConfig.target)
  }
1447
}
1448

1449 1450 1451 1452
function prepareServerlessUrl(
  req: IncomingMessage,
  query: ParsedUrlQuery
): void {
1453 1454 1455 1456 1457 1458 1459 1460 1461 1462
  const curUrl = parseUrl(req.url!, true)
  req.url = formatUrl({
    ...curUrl,
    search: undefined,
    query: {
      ...curUrl.query,
      ...query,
    },
  })
}
1463 1464

class NoFallbackError extends Error {}