next-server.ts 41.2 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 16
import {
  getRedirectStatus,
  Header,
  Redirect,
  Rewrite,
  RouteType,
} from '../../lib/check-custom-routes'
J
JJ Kasper 已提交
17
import { withCoalescedInvoke } from '../../lib/coalesced-function'
J
Joe Haddad 已提交
18 19
import {
  BUILD_ID_FILE,
20
  CLIENT_PUBLIC_FILES_PATH,
J
Joe Haddad 已提交
21 22
  CLIENT_STATIC_FILES_PATH,
  CLIENT_STATIC_FILES_RUNTIME,
23
  PAGES_MANIFEST,
J
Joe Haddad 已提交
24
  PHASE_PRODUCTION_SERVER,
J
Joe Haddad 已提交
25
  PRERENDER_MANIFEST,
26
  ROUTES_MANIFEST,
27
  SERVERLESS_DIRECTORY,
J
Joe Haddad 已提交
28
  SERVER_DIRECTORY,
T
Tim Neutkens 已提交
29
} from '../lib/constants'
J
Joe Haddad 已提交
30 31 32 33
import {
  getRouteMatcher,
  getRouteRegex,
  getSortedRoutes,
34
  isDynamicRoute,
J
Joe Haddad 已提交
35
} from '../lib/router/utils'
36
import * as envConfig from '../lib/runtime-config'
J
Joe Haddad 已提交
37
import { isResSent, NextApiRequest, NextApiResponse } from '../lib/utils'
J
Joe Haddad 已提交
38
import { apiResolver, tryGetPreviewData, __ApiPreviewProps } from './api-utils'
39
import loadConfig, { isTargetLikeServerless } from './config'
40
import pathMatch from './lib/path-match'
J
Joe Haddad 已提交
41
import { recursiveReadDirSync } from './lib/recursive-readdir-sync'
42
import { loadComponents, LoadComponentsReturnType } from './load-components'
J
Joe Haddad 已提交
43
import { normalizePagePath } from './normalize-page-path'
44
import { RenderOpts, RenderOptsPartial, renderToHTML } from './render'
J
Joe Haddad 已提交
45
import { getPagePath } from './require'
46 47 48
import Router, {
  DynamicRoutes,
  PageChecker,
J
Joe Haddad 已提交
49
  Params,
50
  prepareDestination,
J
Joe Haddad 已提交
51 52
  route,
  Route,
53
} from './router'
J
Joe Haddad 已提交
54
import { sendHTML } from './send-html'
55
import { sendPayload } from './send-payload'
J
Joe Haddad 已提交
56
import { serveStatic } from './serve-static'
57
import {
J
Joe Haddad 已提交
58
  getFallback,
59 60 61 62
  getSprCache,
  initializeSprCache,
  setSprCache,
} from './spr-cache'
63
import { execOnce } from '../lib/utils'
64
import { isBlockedPage } from './utils'
65
import { compile as compilePathToRegex } from 'next/dist/compiled/path-to-regexp'
66
import { loadEnvConfig } from '../../lib/load-env-config'
67
import './node-polyfill-fetch'
J
Jan Potoms 已提交
68
import { PagesManifest } from '../../build/webpack/plugins/pages-manifest-plugin'
J
JJ Kasper 已提交
69 70

const getCustomRouteMatcher = pathMatch(true)
71 72 73

type NextConfig = any

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

80 81 82 83 84
type FindComponentsResult = {
  components: LoadComponentsReturnType
  query: ParsedUrlQuery
}

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

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

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

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

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

T
Tim Neutkens 已提交
169
    this.buildId = this.readBuildId()
170

171
    this.renderOpts = {
T
Tim Neutkens 已提交
172
      poweredByHeader: this.nextConfig.poweredByHeader,
173
      canonicalBase: this.nextConfig.amp.canonicalBase,
174
      staticMarkup,
175
      buildId: this.buildId,
176
      generateEtags,
177
      previewProps: this.getPreviewProps(),
178
      customServer: customServer === true ? true : undefined,
179
      ampOptimizerConfig: this.nextConfig.experimental.amp?.optimizer,
180
      basePath: this.nextConfig.experimental.basePath,
181
    }
N
Naoyuki Kanezawa 已提交
182

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

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

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

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

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

J
JJ Kasper 已提交
209
    this.router = new Router(this.generateRoutes())
210
    this.setAssetPrefix(assetPrefix)
J
JJ Kasper 已提交
211

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

J
JJ Kasper 已提交
224 225 226 227 228 229 230 231 232 233 234 235
    initializeSprCache({
      dev,
      distDir: this.distDir,
      pagesDir: join(
        this.distDir,
        this._isLikeServerless
          ? SERVERLESS_DIRECTORY
          : `${SERVER_DIRECTORY}/static/${this.buildId}`,
        'pages'
      ),
      flushToDisk: this.nextConfig.experimental.sprFlushToDisk,
    })
N
Naoyuki Kanezawa 已提交
236
  }
N
nkzawa 已提交
237

238
  protected currentPhase(): string {
239
    return PHASE_PRODUCTION_SERVER
240 241
  }

242 243 244 245
  private logError(err: Error): void {
    if (this.onErrorMiddleware) {
      this.onErrorMiddleware({ err })
    }
246 247
    if (this.quiet) return
    // tslint:disable-next-line
248
    console.error(err)
249 250
  }

251
  private async handleRequest(
J
Joe Haddad 已提交
252 253
    req: IncomingMessage,
    res: ServerResponse,
254
    parsedUrl?: UrlWithParsedQuery
J
Joe Haddad 已提交
255
  ): Promise<void> {
256
    // Parse url if parsedUrl not provided
257
    if (!parsedUrl || typeof parsedUrl !== 'object') {
258 259
      const url: any = req.url
      parsedUrl = parseUrl(url, true)
260
    }
261

262 263 264
    // 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 已提交
265
    }
266

267 268 269 270 271 272
    const { basePath } = this.nextConfig.experimental

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

278
    res.statusCode = 200
279 280 281
    try {
      return await this.run(req, res, parsedUrl)
    } catch (err) {
J
Joe Haddad 已提交
282 283 284
      this.logError(err)
      res.statusCode = 500
      res.end('Internal Server Error')
285
    }
286 287
  }

288
  public getRequestHandler() {
289
    return this.handleRequest.bind(this)
N
nkzawa 已提交
290 291
  }

292
  public setAssetPrefix(prefix?: string): void {
293
    this.renderOpts.assetPrefix = prefix ? prefix.replace(/\/$/, '') : ''
294 295
  }

296
  // Backwards compatibility
297
  public async prepare(): Promise<void> {}
N
nkzawa 已提交
298

T
Tim Neutkens 已提交
299
  // Backwards compatibility
300
  protected async close(): Promise<void> {}
T
Tim Neutkens 已提交
301

302
  protected setImmutableAssetCacheControl(res: ServerResponse): void {
T
Tim Neutkens 已提交
303
    res.setHeader('Cache-Control', 'public, max-age=31536000, immutable')
N
nkzawa 已提交
304 305
  }

J
JJ Kasper 已提交
306 307 308 309
  protected getCustomRoutes() {
    return require(join(this.distDir, ROUTES_MANIFEST))
  }

310 311 312 313
  private _cachedPreviewManifest: PrerenderManifest | undefined
  protected getPrerenderManifest(): PrerenderManifest {
    if (this._cachedPreviewManifest) {
      return this._cachedPreviewManifest
J
Joe Haddad 已提交
314
    }
315 316 317 318 319 320
    const manifest = require(join(this.distDir, PRERENDER_MANIFEST))
    return (this._cachedPreviewManifest = manifest)
  }

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

323
  protected generateRoutes(): {
324 325
    headers: Route[]
    rewrites: Route[]
326
    fsRoutes: Route[]
327
    redirects: Route[]
328 329
    catchAllRoute: Route
    pageChecker: PageChecker
330
    useFileSystemPublicRoutes: boolean
331 332
    dynamicRoutes: DynamicRoutes | undefined
  } {
J
JJ Kasper 已提交
333 334
    this.customRoutes = this.getCustomRoutes()

335 336 337
    const publicRoutes = fs.existsSync(this.publicDir)
      ? this.generatePublicRoutes()
      : []
J
JJ Kasper 已提交
338

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

363 364 365 366
    let headers: Route[] = []
    let rewrites: Route[] = []
    let redirects: Route[] = []

367
    const fsRoutes: Route[] = [
T
Tim Neutkens 已提交
368
      {
369
        match: route('/_next/static/:path*'),
370 371
        type: 'route',
        name: '_next/static catchall',
372
        fn: async (req, res, params, parsedUrl) => {
T
Tim Neutkens 已提交
373 374 375
          // The commons folder holds commonschunk files
          // The chunks folder holds dynamic entries
          // The buildId folder holds pages and potentially other assets. As buildId changes per build it can be long-term cached.
376 377

          // make sure to 404 for /_next/static itself
378 379 380 381 382 383
          if (!params.path) {
            await this.render404(req, res, parsedUrl)
            return {
              finished: true,
            }
          }
384

J
Joe Haddad 已提交
385 386 387
          if (
            params.path[0] === CLIENT_STATIC_FILES_RUNTIME ||
            params.path[0] === 'chunks' ||
388 389
            params.path[0] === 'css' ||
            params.path[0] === 'media' ||
J
Joe Haddad 已提交
390 391
            params.path[0] === this.buildId
          ) {
T
Tim Neutkens 已提交
392
            this.setImmutableAssetCacheControl(res)
393
          }
J
Joe Haddad 已提交
394 395 396
          const p = join(
            this.distDir,
            CLIENT_STATIC_FILES_PATH,
397
            ...(params.path || [])
J
Joe Haddad 已提交
398
          )
399
          await this.serveStatic(req, res, p, parsedUrl)
400 401 402
          return {
            finished: true,
          }
403
        },
404
      },
J
JJ Kasper 已提交
405 406
      {
        match: route('/_next/data/:path*'),
407 408
        type: 'route',
        name: '_next/data catchall',
J
JJ Kasper 已提交
409
        fn: async (req, res, params, _parsedUrl) => {
J
JJ Kasper 已提交
410 411 412
          // Make sure to 404 for /_next/data/ itself and
          // we also want to 404 if the buildId isn't correct
          if (!params.path || params.path[0] !== this.buildId) {
413 414 415 416
            await this.render404(req, res, _parsedUrl)
            return {
              finished: true,
            }
J
JJ Kasper 已提交
417 418 419 420 421 422
          }
          // remove buildId from URL
          params.path.shift()

          // show 404 if it doesn't end with .json
          if (!params.path[params.path.length - 1].endsWith('.json')) {
423 424 425 426
            await this.render404(req, res, _parsedUrl)
            return {
              finished: true,
            }
J
JJ Kasper 已提交
427 428 429 430 431 432 433
          }

          // re-create page's pathname
          const pathname = `/${params.path.join('/')}`
            .replace(/\.json$/, '')
            .replace(/\/index$/, '/')

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

J
JJ Kasper 已提交
463 464
    if (this.customRoutes) {
      const getCustomRoute = (
465 466
        r: Rewrite | Redirect | Header,
        type: RouteType
467 468 469 470 471 472 473 474
      ) =>
        ({
          ...r,
          type,
          match: getCustomRouteMatcher(r.source),
          name: type,
          fn: async (req, res, params, parsedUrl) => ({ finished: false }),
        } as Route & Rewrite & Header)
J
JJ Kasper 已提交
475

476 477 478 479 480 481 482 483 484 485
      const updateHeaderValue = (value: string, params: Params): string => {
        if (!value.includes(':')) {
          return value
        }
        const { parsedDestination } = prepareDestination(value, params, {})

        if (
          !parsedDestination.pathname ||
          !parsedDestination.pathname.startsWith('/')
        ) {
486 487 488 489 490
          // the value needs to start with a forward-slash to be compiled
          // correctly
          return compilePathToRegex(`/${value}`, { validate: false })(
            params
          ).substr(1)
491 492 493 494
        }
        return formatUrl(parsedDestination)
      }

495
      // Headers come very first
J
Joe Haddad 已提交
496
      headers = this.customRoutes.headers.map((r) => {
497 498 499 500 501
        const route = getCustomRoute(r, 'header')
        return {
          match: route.match,
          type: route.type,
          name: `${route.type} ${route.source} header route`,
502
          fn: async (_req, res, params, _parsedUrl) => {
503 504
            const hasParams = Object.keys(params).length > 0

505
            for (const header of (route as Header).headers) {
506
              let { key, value } = header
507 508 509
              if (hasParams) {
                key = updateHeaderValue(key, params)
                value = updateHeaderValue(value, params)
510 511
              }
              res.setHeader(key, value)
512 513 514 515 516
            }
            return { finished: false }
          },
        } as Route
      })
J
JJ Kasper 已提交
517

J
Joe Haddad 已提交
518
      redirects = this.customRoutes.redirects.map((redirect) => {
519 520 521 522 523 524
        const route = getCustomRoute(redirect, 'redirect')
        return {
          type: route.type,
          match: route.match,
          statusCode: route.statusCode,
          name: `Redirect route`,
525
          fn: async (_req, res, params, parsedUrl) => {
526 527
            const { parsedDestination } = prepareDestination(
              route.destination,
528
              params,
529
              parsedUrl.query
530 531 532 533 534 535 536 537 538 539 540
            )
            const updatedDestination = formatUrl(parsedDestination)

            res.setHeader('Location', updatedDestination)
            res.statusCode = getRedirectStatus(route 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}`)
            }
541

542 543 544 545 546 547 548
            res.end()
            return {
              finished: true,
            }
          },
        } as Route
      })
549

J
Joe Haddad 已提交
550
      rewrites = this.customRoutes.rewrites.map((rewrite) => {
551 552 553 554 555 556
        const route = getCustomRoute(rewrite, 'rewrite')
        return {
          check: true,
          type: route.type,
          name: `Rewrite route`,
          match: route.match,
557
          fn: async (req, res, params, parsedUrl) => {
558 559
            const { newUrl, parsedDestination } = prepareDestination(
              route.destination,
560
              params,
561 562
              parsedUrl.query,
              true
563 564 565 566 567 568 569 570 571
            )

            // external rewrite, proxy it
            if (parsedDestination.protocol) {
              const target = formatUrl(parsedDestination)
              const proxy = new Proxy({
                target,
                changeOrigin: true,
                ignorePath: true,
572
              })
573
              proxy.web(req, res)
574

575 576 577
              proxy.on('error', (err: Error) => {
                console.error(`Error occurred proxying ${target}`, err)
              })
578
              return {
579
                finished: true,
J
JJ Kasper 已提交
580
              }
581 582
            }
            ;(req as any)._nextDidRewrite = true
583
            ;(req as any)._nextRewroteUrl = newUrl
584

585 586 587 588 589 590 591 592
            return {
              finished: false,
              pathname: newUrl,
              query: parsedDestination.query,
            }
          },
        } as Route
      })
593 594 595 596 597 598 599 600 601 602 603 604
    }

    const catchAllRoute: Route = {
      match: route('/:path*'),
      type: 'route',
      name: 'Catchall render',
      fn: async (req, res, params, parsedUrl) => {
        const { pathname, query } = parsedUrl
        if (!pathname) {
          throw new Error('pathname is undefined')
        }

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

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

624
    const { useFileSystemPublicRoutes } = this.nextConfig
J
Joe Haddad 已提交
625

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

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

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

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

669
  // Used to build API page in development
670
  protected async ensureApiPage(pathname: string): Promise<void> {}
671

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

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

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

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

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

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

J
Joe Haddad 已提交
727 728 729 730 731
    await apiResolver(
      req,
      res,
      query,
      pageModule,
732
      this.renderOpts.previewProps,
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 815
    const { generateEtags, poweredByHeader } = this.renderOpts
    return sendHTML(req, res, html, { generateEtags, poweredByHeader })
816 817
  }

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

831
    const url: any = req.url
832

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

845
    if (isBlockedPage(pathname)) {
846
      return this.render404(req, res, parsedUrl)
847 848
    }

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

855
    return this.sendHTML(req, res, html)
N
Naoyuki Kanezawa 已提交
856
  }
N
nkzawa 已提交
857

J
Joe Haddad 已提交
858
  private async findPageComponents(
J
Joe Haddad 已提交
859
    pathname: string,
860 861 862 863 864 865 866 867 868
    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 已提交
869
      try {
870
        const components = await loadComponents(
J
Joe Haddad 已提交
871 872
          this.distDir,
          this.buildId,
873 874
          pagePath!,
          !this.renderOpts.dev && this._isLikeServerless
J
Joe Haddad 已提交
875
        )
876 877 878
        return {
          components,
          query: {
879
            ...(components.getStaticProps
880
              ? { _nextDataReq: query._nextDataReq, amp: query.amp }
881 882 883 884
              : query),
            ...(params || {}),
          },
        }
J
JJ Kasper 已提交
885 886 887 888
      } catch (err) {
        if (err.code !== 'ENOENT') throw err
      }
    }
889
    return null
J
Joe Haddad 已提交
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 928 929 930 931 932
  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,
          this.buildId,
          pathname,
          !this.renderOpts.dev && this._isLikeServerless
        )
        return paths
      }
      ;({ paths: staticPaths, fallback: hasStaticFallback } = (
        await withCoalescedInvoke(__getStaticPaths)(
          `staticPaths-${pathname}`,
          []
        )
      ).value)
    }

    return { staticPaths, hasStaticFallback }
  }

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

J
JJ Kasper 已提交
945
    // handle static page
946 947
    if (typeof components.Component === 'string') {
      return components.Component
J
Joe Haddad 已提交
948 949
    }

J
JJ Kasper 已提交
950 951
    // check request state
    const isLikeServerless =
952 953
      typeof components.Component === 'object' &&
      typeof (components.Component as any).renderReqToHTML === 'function'
954 955 956
    const isSSG = !!components.getStaticProps
    const isServerProps = !!components.getServerSideProps
    const hasStaticPaths = !!components.getStaticPaths
957

958 959 960 961
    if (!query.amp) {
      delete query.amp
    }

962
    // Toggle whether or not this is a Data request
963
    const isDataReq = !!query._nextDataReq
964 965
    delete query._nextDataReq

966 967 968 969 970 971 972 973
    let previewData: string | false | object | undefined
    let isPreviewMode = false

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

974 975 976 977 978 979
    // 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!}`
980 981 982 983 984 985 986 987 988

    // 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$/, '/')
    }

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

    // Complete the response with cached data if its present
995
    const cachedData = ssgCacheKey ? await getSprCache(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 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 1132
    }

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

1154 1155 1156
    // Update the SPR cache if the head request and cacheable
    if (isOrigin && ssgCacheKey) {
      await setSprCache(ssgCacheKey, { html: html!, pageData }, sprRevalidate)
1157 1158
    }

1159
    return resHtml
1160 1161
  }

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

1186 1187 1188 1189 1190 1191
      if (this.dynamicRoutes) {
        for (const dynamicRoute of this.dynamicRoutes) {
          const params = dynamicRoute.match(pathname)
          if (!params) {
            continue
          }
J
Joe Haddad 已提交
1192

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

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

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

1261 1262 1263
    const is404 = res.statusCode === 404
    let using404Page = false

1264
    // use static 404 page if available and is 404 response
1265
    if (is404) {
1266 1267
      result = await this.findPageComponents('/404')
      using404Page = result !== null
1268 1269 1270 1271 1272 1273
    }

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

1274 1275 1276
    if (
      process.env.NODE_ENV !== 'production' &&
      !using404Page &&
1277 1278
      (await this.hasPage('/_error')) &&
      !(await this.hasPage('/404'))
1279 1280 1281 1282
    ) {
      this.customErrorNo404Warn()
    }

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

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

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

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

1351 1352 1353 1354 1355 1356 1357 1358 1359
  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 已提交
1360
      userFilesStatic = recursiveReadDirSync(pathUserFilesStatic).map((f) =>
1361 1362 1363 1364 1365 1366
        join('.', 'static', f)
      )
    }

    let userFilesPublic: string[] = []
    if (this.publicDir && fs.existsSync(this.publicDir)) {
J
Joe Haddad 已提交
1367
      userFilesPublic = recursiveReadDirSync(this.publicDir).map((f) =>
1368 1369 1370 1371 1372 1373 1374
        join('.', 'public', f)
      )
    }

    let nextFilesStatic: string[] = []
    nextFilesStatic = recursiveReadDirSync(
      join(this.distDir, 'static')
J
Joe Haddad 已提交
1375
    ).map((f) => join('.', relative(this.dir, this.distDir), 'static', f))
1376 1377 1378 1379 1380 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

    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 已提交
1410
    if (
1411 1412 1413
      (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 已提交
1414 1415 1416 1417
    ) {
      return false
    }

1418 1419 1420 1421
    // Check against the real filesystem paths
    const filesystemUrls = this.getFilesystemPaths()
    const resolved = relative(this.dir, untrustedFilePath)
    return filesystemUrls.has(resolved)
A
Arunoda Susiripala 已提交
1422 1423
  }

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

      throw err
1436
    }
1437
  }
1438 1439 1440 1441

  private get _isLikeServerless(): boolean {
    return isTargetLikeServerless(this.nextConfig.target)
  }
1442
}
1443

1444 1445 1446 1447
function prepareServerlessUrl(
  req: IncomingMessage,
  query: ParsedUrlQuery
): void {
1448 1449 1450 1451 1452 1453 1454 1455 1456 1457
  const curUrl = parseUrl(req.url!, true)
  req.url = formatUrl({
    ...curUrl,
    search: undefined,
    query: {
      ...curUrl.query,
      ...query,
    },
  })
}
1458 1459

class NoFallbackError extends Error {}