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
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 {
J
Joe Haddad 已提交
59
  getFallback,
60 61 62 63
  getSprCache,
  initializeSprCache,
  setSprCache,
} from './spr-cache'
64
import { execOnce } from '../lib/utils'
65
import { isBlockedPage } from './utils'
66
import { compile as compilePathToRegex } from 'next/dist/compiled/path-to-regexp'
67
import { loadEnvConfig } from '../../lib/load-env-config'
68
import './node-polyfill-fetch'
J
Jan Potoms 已提交
69
import { PagesManifest } from '../../build/webpack/plugins/pages-manifest-plugin'
J
JJ Kasper 已提交
70 71

const getCustomRouteMatcher = pathMatch(true)
72 73 74

type NextConfig = any

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

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

T
Tim Neutkens 已提交
86
export type ServerConstructor = {
87 88 89
  /**
   * Where the Next project is located - @default '.'
   */
J
Joe Haddad 已提交
90
  dir?: string
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
    buildId: string
    generateEtags: boolean
    runtimeConfig?: { [key: string]: any }
119 120 121
    assetPrefix?: string
    canonicalBase: string
    dev?: boolean
122
    previewProps: __ApiPreviewProps
123
    customServer?: boolean
124
    ampOptimizerConfig?: { [key: string]: any }
125
    basePath: string
126
  }
127
  private compression?: Middleware
J
JJ Kasper 已提交
128
  private onErrorMiddleware?: ({ err }: { err: Error }) => Promise<void>
129
  router: Router
130
  protected dynamicRoutes?: DynamicRoutes
131
  protected customRoutes: CustomRoutes
132 133 134
  protected staticPathsWorker?: import('jest-worker').default & {
    loadStaticPaths: typeof import('../../server/static-paths-worker').loadStaticPaths
  }
135

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

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

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

T
Tim Neutkens 已提交
163
    this.buildId = this.readBuildId()
164

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

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

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

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

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

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

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

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

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

230
  protected currentPhase(): string {
231
    return PHASE_PRODUCTION_SERVER
232 233
  }

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

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

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

259
    const { basePath } = this.nextConfig
260 261 262 263 264

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

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

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

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

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

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

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

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

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

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

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

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

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

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

          // re-create page's pathname
414 415 416 417 418
          const pathname = `/${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('/')}`
J
JJ Kasper 已提交
419 420 421
            .replace(/\.json$/, '')
            .replace(/\/index$/, '/')

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

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

452 453 454 455 456 457 458 459 460 461 462 463
    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
464
      }
465 466 467 468 469 470 471 472 473 474 475 476 477 478
      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)
    }
479

480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
    // 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)
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 548
            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
          )
549

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

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

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

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

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

608
    const { useFileSystemPublicRoutes } = this.nextConfig
J
Joe Haddad 已提交
609

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

826
    const url: any = req.url
827

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

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

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

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

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

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

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

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

951 952 953 954
    if (!query.amp) {
      delete query.amp
    }

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

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

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

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

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

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

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

    // Complete the response with cached data if its present
991
    const cachedData = ssgCacheKey ? await getSprCache(ssgCacheKey) : undefined
992

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

998
      sendPayload(
J
JJ Kasper 已提交
999 1000
        res,
        data,
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
        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,
            }
1011
          : undefined
J
JJ Kasper 已提交
1012 1013 1014 1015 1016 1017
      )

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

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

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

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

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

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

1063
      return { html, pageData, sprRevalidate }
1064
    })
J
JJ Kasper 已提交
1065

1066
    const isProduction = !this.renderOpts.dev
J
Joe Haddad 已提交
1067
    const isDynamicPathname = isDynamicRoute(pathname)
1068
    const didRespond = isResSent(res)
1069

1070 1071 1072
    const { staticPaths, hasStaticFallback } = hasStaticPaths
      ? await this.getStaticPaths(pathname)
      : { staticPaths: undefined, hasStaticFallback: false }
1073

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

1110
      let html: string
1111

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

1126
      sendPayload(res, html, 'html')
1127
      return null
1128 1129
    }

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

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

1156
    return resHtml
1157 1158
  }

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

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

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

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

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

1258 1259 1260
    const is404 = res.statusCode === 404
    let using404Page = false

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

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

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

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

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

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

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

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

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

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

    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 已提交
1407
    if (
1408 1409 1410
      (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 已提交
1411 1412 1413 1414
    ) {
      return false
    }

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

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

      throw err
1433
    }
1434
  }
1435 1436 1437 1438

  private get _isLikeServerless(): boolean {
    return isTargetLikeServerless(this.nextConfig.target)
  }
1439
}
1440

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

class NoFallbackError extends Error {}