next-server.ts 42.3 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 68 69 70 71 72 73 74
import fetch from 'next/dist/compiled/node-fetch'

// @ts-ignore fetch exists globally
if (!global.fetch) {
  // Polyfill fetch() in the Node.js environment
  // @ts-ignore fetch exists globally
  global.fetch = fetch
}
J
JJ Kasper 已提交
75 76

const getCustomRouteMatcher = pathMatch(true)
77 78 79

type NextConfig = any

80 81 82 83 84 85
type Middleware = (
  req: IncomingMessage,
  res: ServerResponse,
  next: (err?: Error) => void
) => void

86 87 88 89 90
type FindComponentsResult = {
  components: LoadComponentsReturnType
  query: ParsedUrlQuery
}

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

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

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

160
    this.nextConfig = loadConfig(phase, this.dir, conf)
161
    this.distDir = join(this.dir, this.nextConfig.distDir)
162
    this.publicDir = join(this.dir, CLIENT_PUBLIC_FILES_PATH)
163
    this.hasStaticDir = fs.existsSync(join(this.dir, 'static'))
T
Tim Neutkens 已提交
164

165 166
    // Only serverRuntimeConfig needs the default
    // publicRuntimeConfig gets it's default in client/index.js
J
Joe Haddad 已提交
167 168 169 170 171
    const {
      serverRuntimeConfig = {},
      publicRuntimeConfig,
      assetPrefix,
      generateEtags,
172
      compress,
J
Joe Haddad 已提交
173
    } = this.nextConfig
174

T
Tim Neutkens 已提交
175
    this.buildId = this.readBuildId()
176

177
    this.renderOpts = {
T
Tim Neutkens 已提交
178
      poweredByHeader: this.nextConfig.poweredByHeader,
179
      canonicalBase: this.nextConfig.amp.canonicalBase,
180
      staticMarkup,
181
      buildId: this.buildId,
182
      generateEtags,
183
      previewProps: this.getPreviewProps(),
184
      customServer: customServer === true ? true : undefined,
185
      ampOptimizerConfig: this.nextConfig.experimental.amp?.optimizer,
186
      basePath: this.nextConfig.experimental.basePath,
187
    }
N
Naoyuki Kanezawa 已提交
188

189 190
    // Only the `publicRuntimeConfig` key is exposed to the client side
    // It'll be rendered as part of __NEXT_DATA__ on the client side
191
    if (Object.keys(publicRuntimeConfig).length > 0) {
192
      this.renderOpts.runtimeConfig = publicRuntimeConfig
193 194
    }

195
    if (compress && this.nextConfig.target === 'server') {
196 197 198
      this.compression = compression() as Middleware
    }

199
    // Initialize next/config with the environment configuration
200 201 202 203
    envConfig.setConfig({
      serverRuntimeConfig,
      publicRuntimeConfig,
    })
204

205 206 207 208 209 210 211 212 213 214
    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 已提交
215
    this.router = new Router(this.generateRoutes())
216
    this.setAssetPrefix(assetPrefix)
J
JJ Kasper 已提交
217

218 219 220
    // call init-server middleware, this is also handled
    // individually in serverless bundles when deployed
    if (!dev && this.nextConfig.experimental.plugins) {
221 222
      const initServer = require(join(this.serverBuildDir, 'init-server.js'))
        .default
223
      this.onErrorMiddleware = require(join(
224
        this.serverBuildDir,
225 226 227 228 229
        'on-error-server.js'
      )).default
      initServer()
    }

J
JJ Kasper 已提交
230 231 232 233 234 235 236 237 238 239 240 241
    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 已提交
242
  }
N
nkzawa 已提交
243

244
  protected currentPhase(): string {
245
    return PHASE_PRODUCTION_SERVER
246 247
  }

248 249 250 251
  private logError(err: Error): void {
    if (this.onErrorMiddleware) {
      this.onErrorMiddleware({ err })
    }
252 253
    if (this.quiet) return
    // tslint:disable-next-line
254
    console.error(err)
255 256
  }

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

268 269 270
    // 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 已提交
271
    }
272

273 274 275 276 277 278
    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 已提交
279
      // If replace ends up replacing the full url it'll be `undefined`, meaning we have to default it to `/`
280 281
      parsedUrl.pathname = parsedUrl.pathname!.replace(basePath, '') || '/'
      req.url = req.url!.replace(basePath, '')
T
Tim Neutkens 已提交
282 283
    }

284
    res.statusCode = 200
285 286 287
    try {
      return await this.run(req, res, parsedUrl)
    } catch (err) {
J
Joe Haddad 已提交
288 289 290
      this.logError(err)
      res.statusCode = 500
      res.end('Internal Server Error')
291
    }
292 293
  }

294
  public getRequestHandler() {
295
    return this.handleRequest.bind(this)
N
nkzawa 已提交
296 297
  }

298
  public setAssetPrefix(prefix?: string) {
299
    this.renderOpts.assetPrefix = prefix ? prefix.replace(/\/$/, '') : ''
300 301
  }

302
  // Backwards compatibility
303
  public async prepare(): Promise<void> {}
N
nkzawa 已提交
304

T
Tim Neutkens 已提交
305
  // Backwards compatibility
306
  protected async close(): Promise<void> {}
T
Tim Neutkens 已提交
307

308
  protected setImmutableAssetCacheControl(res: ServerResponse) {
T
Tim Neutkens 已提交
309
    res.setHeader('Cache-Control', 'public, max-age=31536000, immutable')
N
nkzawa 已提交
310 311
  }

J
JJ Kasper 已提交
312 313 314 315
  protected getCustomRoutes() {
    return require(join(this.distDir, ROUTES_MANIFEST))
  }

316 317 318 319
  private _cachedPreviewManifest: PrerenderManifest | undefined
  protected getPrerenderManifest(): PrerenderManifest {
    if (this._cachedPreviewManifest) {
      return this._cachedPreviewManifest
J
Joe Haddad 已提交
320
    }
321 322 323 324 325 326
    const manifest = require(join(this.distDir, PRERENDER_MANIFEST))
    return (this._cachedPreviewManifest = manifest)
  }

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

329
  protected generateRoutes(): {
330 331
    headers: Route[]
    rewrites: Route[]
332
    fsRoutes: Route[]
333
    redirects: Route[]
334 335
    catchAllRoute: Route
    pageChecker: PageChecker
336
    useFileSystemPublicRoutes: boolean
337 338
    dynamicRoutes: DynamicRoutes | undefined
  } {
J
JJ Kasper 已提交
339 340
    this.customRoutes = this.getCustomRoutes()

341 342 343
    const publicRoutes = fs.existsSync(this.publicDir)
      ? this.generatePublicRoutes()
      : []
J
JJ Kasper 已提交
344

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

369 370 371 372
    let headers: Route[] = []
    let rewrites: Route[] = []
    let redirects: Route[] = []

373
    const fsRoutes: Route[] = [
T
Tim Neutkens 已提交
374
      {
375
        match: route('/_next/static/:path*'),
376 377
        type: 'route',
        name: '_next/static catchall',
378
        fn: async (req, res, params, parsedUrl) => {
T
Tim Neutkens 已提交
379 380 381
          // 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.
382 383

          // make sure to 404 for /_next/static itself
384 385 386 387 388 389
          if (!params.path) {
            await this.render404(req, res, parsedUrl)
            return {
              finished: true,
            }
          }
390

J
Joe Haddad 已提交
391 392 393
          if (
            params.path[0] === CLIENT_STATIC_FILES_RUNTIME ||
            params.path[0] === 'chunks' ||
394 395
            params.path[0] === 'css' ||
            params.path[0] === 'media' ||
J
Joe Haddad 已提交
396 397
            params.path[0] === this.buildId
          ) {
T
Tim Neutkens 已提交
398
            this.setImmutableAssetCacheControl(res)
399
          }
J
Joe Haddad 已提交
400 401 402
          const p = join(
            this.distDir,
            CLIENT_STATIC_FILES_PATH,
403
            ...(params.path || [])
J
Joe Haddad 已提交
404
          )
405
          await this.serveStatic(req, res, p, parsedUrl)
406 407 408
          return {
            finished: true,
          }
409
        },
410
      },
J
JJ Kasper 已提交
411 412
      {
        match: route('/_next/data/:path*'),
413 414
        type: 'route',
        name: '_next/data catchall',
J
JJ Kasper 已提交
415
        fn: async (req, res, params, _parsedUrl) => {
J
JJ Kasper 已提交
416 417 418
          // 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) {
419 420 421 422
            await this.render404(req, res, _parsedUrl)
            return {
              finished: true,
            }
J
JJ Kasper 已提交
423 424 425 426 427 428
          }
          // 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')) {
429 430 431 432
            await this.render404(req, res, _parsedUrl)
            return {
              finished: true,
            }
J
JJ Kasper 已提交
433 434 435 436 437 438 439
          }

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

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

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

482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
      const updateHeaderValue = (value: string, params: Params): string => {
        if (!value.includes(':')) {
          return value
        }
        const { parsedDestination } = prepareDestination(value, params, {})

        if (
          !parsedDestination.pathname ||
          !parsedDestination.pathname.startsWith('/')
        ) {
          return compilePathToRegex(value, { validate: false })(params)
        }
        return formatUrl(parsedDestination)
      }

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

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

520 521 522 523 524 525 526
      redirects = this.customRoutes.redirects.map(redirect => {
        const route = getCustomRoute(redirect, 'redirect')
        return {
          type: route.type,
          match: route.match,
          statusCode: route.statusCode,
          name: `Redirect route`,
527
          fn: async (_req, res, params, parsedUrl) => {
528 529
            const { parsedDestination } = prepareDestination(
              route.destination,
530
              params,
531
              parsedUrl.query
532 533 534 535 536 537 538 539 540 541 542
            )
            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}`)
            }
543

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

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

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

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

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

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

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

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

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

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

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

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

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

670 671 672
  // Used to build API page in development
  protected async ensureApiPage(pathname: string) {}

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

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

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

    const builtPagePath = await this.getPagePath(page)
    const pageModule = require(builtPagePath)
709
    query = { ...query, ...params }
J
JJ Kasper 已提交
710

711
    if (!this.renderOpts.dev && this._isLikeServerless) {
712
      if (typeof pageModule.default === 'function') {
713
        prepareServerlessUrl(req, query)
714 715
        await pageModule.default(req, res)
        return true
J
JJ Kasper 已提交
716 717 718
      }
    }

J
Joe Haddad 已提交
719 720 721 722 723
    await apiResolver(
      req,
      res,
      query,
      pageModule,
724
      this.renderOpts.previewProps,
J
Joe Haddad 已提交
725 726
      this.onErrorMiddleware
    )
727
    return true
L
Lukáš Huvar 已提交
728 729
  }

730
  protected generatePublicRoutes(): Route[] {
731 732 733 734 735 736 737 738 739
    const publicFiles = new Set(
      recursiveReadDirSync(this.publicDir).map(p => p.replace(/\\/g, '/'))
    )

    return [
      {
        match: route('/:path*'),
        name: 'public folder catchall',
        fn: async (req, res, params, parsedUrl) => {
740 741
          const pathParts: string[] = params.path || []
          const path = `/${pathParts.join('/')}`
742 743 744 745 746 747

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

763
  protected getDynamicRoutes() {
764 765 766
    const dynamicRoutedPages = Object.keys(this.pagesManifest!).filter(
      isDynamicRoute
    )
767 768 769 770
    return getSortedRoutes(dynamicRoutedPages).map(page => ({
      page,
      match: getRouteMatcher(getRouteRegex(page)),
    }))
J
Joe Haddad 已提交
771 772
  }

773 774 775 776 777 778
  private handleCompression(req: IncomingMessage, res: ServerResponse) {
    if (this.compression) {
      this.compression(req, res, () => {})
    }
  }

779
  protected async run(
J
Joe Haddad 已提交
780 781
    req: IncomingMessage,
    res: ServerResponse,
782
    parsedUrl: UrlWithParsedQuery
J
Joe Haddad 已提交
783
  ) {
784 785
    this.handleCompression(req, res)

786
    try {
787 788
      const matched = await this.router.execute(req, res, parsedUrl)
      if (matched) {
789 790 791 792 793 794 795 796
        return
      }
    } catch (err) {
      if (err.code === 'DECODE_FAILED') {
        res.statusCode = 400
        return this.renderError(null, req, res, '/_error', {})
      }
      throw err
797 798
    }

799
    await this.render404(req, res, parsedUrl)
N
nkzawa 已提交
800 801
  }

802
  protected async sendHTML(
J
Joe Haddad 已提交
803 804
    req: IncomingMessage,
    res: ServerResponse,
805
    html: string
J
Joe Haddad 已提交
806
  ) {
T
Tim Neutkens 已提交
807 808
    const { generateEtags, poweredByHeader } = this.renderOpts
    return sendHTML(req, res, html, { generateEtags, poweredByHeader })
809 810
  }

J
Joe Haddad 已提交
811 812 813 814 815
  public async render(
    req: IncomingMessage,
    res: ServerResponse,
    pathname: string,
    query: ParsedUrlQuery = {},
816
    parsedUrl?: UrlWithParsedQuery
J
Joe Haddad 已提交
817
  ): Promise<void> {
818 819 820 821 822 823
    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`
      )
    }

824
    const url: any = req.url
825

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

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

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

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

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

J
JJ Kasper 已提交
967
    // non-spr requests should render like normal
968
    if (!isSSG) {
J
JJ Kasper 已提交
969 970
      // handle serverless
      if (isLikeServerless) {
971
        if (isDataReq) {
972
          const renderResult = await (components.Component as any).renderReqToHTML(
973 974
            req,
            res,
975
            'passthrough'
976 977
          )

978
          sendPayload(
979 980
            res,
            JSON.stringify(renderResult?.renderOpts?.pageData),
981
            'json',
982 983
            !this.renderOpts.dev
              ? {
984 985
                  private: isPreviewMode,
                  stateful: true, // non-SSG data request
986 987
                }
              : undefined
988 989 990
          )
          return null
        }
991
        prepareServerlessUrl(req, query)
992
        return (components.Component as any).renderReqToHTML(req, res)
J
JJ Kasper 已提交
993 994
      }

995 996
      if (isDataReq && isServerProps) {
        const props = await renderToHTML(req, res, pathname, query, {
997
          ...components,
998 999 1000
          ...opts,
          isDataReq,
        })
1001 1002 1003
        sendPayload(
          res,
          JSON.stringify(props),
1004
          'json',
1005 1006
          !this.renderOpts.dev
            ? {
1007 1008
                private: isPreviewMode,
                stateful: true, // GSSP data request
1009 1010 1011
              }
            : undefined
        )
1012 1013 1014
        return null
      }

1015
      const html = await renderToHTML(req, res, pathname, query, {
1016
        ...components,
J
JJ Kasper 已提交
1017 1018 1019
        ...opts,
      })

1020 1021
      if (html && isServerProps) {
        sendPayload(res, html, 'html', {
1022
          private: isPreviewMode,
1023
          stateful: true, // GSSP request
1024
        })
1025
        return null
1026 1027 1028 1029
      }

      return html
    }
J
Joe Haddad 已提交
1030

1031 1032
    // Compute the iSSG cache key
    let urlPathname = `${parseUrl(req.url || '').pathname!}${
1033 1034
      query.amp ? '.amp' : ''
    }`
1035 1036 1037 1038 1039 1040 1041 1042 1043

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

J
Joe Haddad 已提交
1044
    const ssgCacheKey = isPreviewMode
1045
      ? undefined // Preview mode bypasses the cache
1046
      : urlPathname
J
JJ Kasper 已提交
1047 1048

    // Complete the response with cached data if its present
1049
    const cachedData = ssgCacheKey ? await getSprCache(ssgCacheKey) : undefined
J
JJ Kasper 已提交
1050
    if (cachedData) {
1051
      const data = isDataReq
J
JJ Kasper 已提交
1052 1053 1054
        ? JSON.stringify(cachedData.pageData)
        : cachedData.html

1055
      sendPayload(
J
JJ Kasper 已提交
1056 1057
        res,
        data,
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067
        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,
            }
1068
          : undefined
J
JJ Kasper 已提交
1069 1070 1071 1072 1073 1074
      )

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

J
JJ Kasper 已提交
1077
    // If we're here, that means data is missing or it's stale.
1078 1079 1080 1081 1082 1083
    const maybeCoalesceInvoke = ssgCacheKey
      ? (fn: any) => withCoalescedInvoke(fn).bind(null, ssgCacheKey, [])
      : (fn: any) => async () => {
          const value = await fn()
          return { isOrigin: true, value }
        }
J
JJ Kasper 已提交
1084

1085
    const doRender = maybeCoalesceInvoke(async function(): Promise<{
J
JJ Kasper 已提交
1086
      html: string | null
1087
      pageData: any
J
JJ Kasper 已提交
1088 1089
      sprRevalidate: number | false
    }> {
1090
      let pageData: any
J
JJ Kasper 已提交
1091 1092 1093 1094 1095 1096
      let html: string | null
      let sprRevalidate: number | false

      let renderResult
      // handle serverless
      if (isLikeServerless) {
1097
        renderResult = await (components.Component as any).renderReqToHTML(
1098 1099
          req,
          res,
1100
          'passthrough'
1101
        )
J
JJ Kasper 已提交
1102 1103

        html = renderResult.html
1104
        pageData = renderResult.renderOpts.pageData
J
JJ Kasper 已提交
1105 1106
        sprRevalidate = renderResult.renderOpts.revalidate
      } else {
1107
        const renderOpts: RenderOpts = {
1108
          ...components,
J
JJ Kasper 已提交
1109 1110 1111 1112 1113
          ...opts,
        }
        renderResult = await renderToHTML(req, res, pathname, query, renderOpts)

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

1119
      return { html, pageData, sprRevalidate }
1120
    })
J
JJ Kasper 已提交
1121

1122
    const isProduction = !this.renderOpts.dev
J
Joe Haddad 已提交
1123
    const isDynamicPathname = isDynamicRoute(pathname)
1124
    const didRespond = isResSent(res)
1125

1126 1127 1128
    const { staticPaths, hasStaticFallback } = hasStaticPaths
      ? await this.getStaticPaths(pathname)
      : { staticPaths: undefined, hasStaticFallback: false }
1129

1130 1131 1132 1133 1134 1135 1136 1137 1138 1139
    // 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.
    //
1140
    // * Non-dynamic pages should block (though this is an impossible
1141 1142
    //   case in production).
    //
1143 1144
    // * Dynamic pages should return their skeleton if not defined in
    //   getStaticPaths, then finish the data request on the client-side.
1145
    //
J
Joe Haddad 已提交
1146
    if (
1147
      !didRespond &&
J
Joe Haddad 已提交
1148
      !isDataReq &&
1149 1150
      !isPreviewMode &&
      isDynamicPathname &&
1151 1152 1153
      // Development should trigger fallback when the path is not in
      // `getStaticPaths`
      (isProduction || !staticPaths || !staticPaths.includes(urlPathname))
J
Joe Haddad 已提交
1154
    ) {
1155 1156 1157 1158 1159 1160 1161
      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
      ) {
1162
        throw new NoFallbackError()
1163 1164
      }

1165
      let html: string
1166

1167 1168
      // Production already emitted the fallback as static HTML.
      if (isProduction) {
1169
        html = await getFallback(pathname)
1170 1171 1172
      }
      // We need to generate the fallback on-demand for development.
      else {
1173 1174
        query.__nextFallback = 'true'
        if (isLikeServerless) {
1175
          prepareServerlessUrl(req, query)
1176 1177 1178 1179 1180 1181
          const renderResult = await (components.Component as any).renderReqToHTML(
            req,
            res,
            'passthrough'
          )
          html = renderResult.html
1182 1183
        } else {
          html = (await renderToHTML(req, res, pathname, query, {
1184
            ...components,
1185 1186 1187 1188 1189
            ...opts,
          })) as string
        }
      }

1190
      sendPayload(res, html, 'html')
1191 1192
    }

1193 1194 1195
    const {
      isOrigin,
      value: { html, pageData, sprRevalidate },
1196
    } = await doRender()
1197
    if (!isResSent(res)) {
1198
      sendPayload(
1199 1200
        res,
        isDataReq ? JSON.stringify(pageData) : html,
1201
        isDataReq ? 'json' : 'html',
1202
        !this.renderOpts.dev
1203 1204 1205 1206 1207
          ? {
              private: isPreviewMode,
              stateful: false, // GSP response
              revalidate: sprRevalidate,
            }
1208
          : undefined
1209 1210
      )
    }
J
JJ Kasper 已提交
1211

1212 1213 1214
    // Update the SPR cache if the head request and cacheable
    if (isOrigin && ssgCacheKey) {
      await setSprCache(ssgCacheKey, { html: html!, pageData }, sprRevalidate)
1215 1216 1217
    }

    return null
1218 1219
  }

1220
  public async renderToHTML(
J
Joe Haddad 已提交
1221 1222 1223
    req: IncomingMessage,
    res: ServerResponse,
    pathname: string,
1224
    query: ParsedUrlQuery = {}
J
Joe Haddad 已提交
1225
  ): Promise<string | null> {
1226 1227 1228
    try {
      const result = await this.findPageComponents(pathname, query)
      if (result) {
1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240
        try {
          return await this.renderToHTMLWithComponents(
            req,
            res,
            pathname,
            result,
            { ...this.renderOpts }
          )
        } catch (err) {
          if (!(err instanceof NoFallbackError)) {
            throw err
          }
1241
        }
1242
      }
J
Joe Haddad 已提交
1243

1244 1245 1246 1247 1248 1249
      if (this.dynamicRoutes) {
        for (const dynamicRoute of this.dynamicRoutes) {
          const params = dynamicRoute.match(pathname)
          if (!params) {
            continue
          }
J
Joe Haddad 已提交
1250

1251 1252 1253 1254 1255 1256
          const result = await this.findPageComponents(
            dynamicRoute.page,
            query,
            params
          )
          if (result) {
1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268
            try {
              return await this.renderToHTMLWithComponents(
                req,
                res,
                dynamicRoute.page,
                result,
                { ...this.renderOpts, params }
              )
            } catch (err) {
              if (!(err instanceof NoFallbackError)) {
                throw err
              }
1269
            }
J
Joe Haddad 已提交
1270 1271
          }
        }
1272 1273 1274 1275 1276 1277 1278 1279 1280
      }
    } 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 已提交
1281 1282
  }

J
Joe Haddad 已提交
1283 1284 1285 1286 1287
  public async renderError(
    err: Error | null,
    req: IncomingMessage,
    res: ServerResponse,
    pathname: string,
1288
    query: ParsedUrlQuery = {}
J
Joe Haddad 已提交
1289 1290 1291
  ): Promise<void> {
    res.setHeader(
      'Cache-Control',
1292
      'no-cache, no-store, max-age=0, must-revalidate'
J
Joe Haddad 已提交
1293
    )
N
Naoyuki Kanezawa 已提交
1294
    const html = await this.renderErrorToHTML(err, req, res, pathname, query)
1295
    if (html === null) {
1296 1297
      return
    }
1298
    return this.sendHTML(req, res, html)
N
nkzawa 已提交
1299 1300
  }

1301 1302 1303 1304 1305 1306 1307 1308 1309
  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 已提交
1310 1311 1312 1313 1314
  public async renderErrorToHTML(
    err: Error | null,
    req: IncomingMessage,
    res: ServerResponse,
    _pathname: string,
1315
    query: ParsedUrlQuery = {}
J
Joe Haddad 已提交
1316
  ) {
1317
    let result: null | FindComponentsResult = null
1318

1319 1320 1321
    const is404 = res.statusCode === 404
    let using404Page = false

1322
    // use static 404 page if available and is 404 response
1323
    if (is404) {
1324 1325
      result = await this.findPageComponents('/404')
      using404Page = result !== null
1326 1327 1328 1329 1330 1331
    }

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

1332 1333 1334
    if (
      process.env.NODE_ENV !== 'production' &&
      !using404Page &&
1335 1336
      (await this.hasPage('/_error')) &&
      !(await this.hasPage('/404'))
1337 1338 1339 1340
    ) {
      this.customErrorNo404Warn()
    }

1341
    let html: string | null
1342
    try {
1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356
      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')
1357
        }
1358
        throw err
1359
      }
1360 1361 1362 1363 1364 1365
    } catch (err) {
      console.error(err)
      res.statusCode = 500
      html = 'Internal Server Error'
    }
    return html
N
Naoyuki Kanezawa 已提交
1366 1367
  }

J
Joe Haddad 已提交
1368 1369 1370
  public async render404(
    req: IncomingMessage,
    res: ServerResponse,
1371
    parsedUrl?: UrlWithParsedQuery
J
Joe Haddad 已提交
1372
  ): Promise<void> {
1373 1374
    const url: any = req.url
    const { pathname, query } = parsedUrl ? parsedUrl : parseUrl(url, true)
N
Naoyuki Kanezawa 已提交
1375
    res.statusCode = 404
1376
    return this.renderError(null, req, res, pathname!, query)
N
Naoyuki Kanezawa 已提交
1377
  }
N
Naoyuki Kanezawa 已提交
1378

J
Joe Haddad 已提交
1379 1380 1381 1382
  public async serveStatic(
    req: IncomingMessage,
    res: ServerResponse,
    path: string,
1383
    parsedUrl?: UrlWithParsedQuery
J
Joe Haddad 已提交
1384
  ): Promise<void> {
A
Arunoda Susiripala 已提交
1385
    if (!this.isServeableUrl(path)) {
1386
      return this.render404(req, res, parsedUrl)
A
Arunoda Susiripala 已提交
1387 1388
    }

1389 1390 1391 1392 1393 1394
    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 已提交
1395
    try {
1396
      await serveStatic(req, res, path)
N
Naoyuki Kanezawa 已提交
1397
    } catch (err) {
T
Tim Neutkens 已提交
1398
      if (err.code === 'ENOENT' || err.statusCode === 404) {
1399
        this.render404(req, res, parsedUrl)
1400 1401 1402
      } else if (err.statusCode === 412) {
        res.statusCode = 412
        return this.renderError(err, req, res, path)
N
Naoyuki Kanezawa 已提交
1403 1404 1405 1406 1407 1408
      } else {
        throw err
      }
    }
  }

1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467
  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)) {
      userFilesStatic = recursiveReadDirSync(pathUserFilesStatic).map(f =>
        join('.', 'static', f)
      )
    }

    let userFilesPublic: string[] = []
    if (this.publicDir && fs.existsSync(this.publicDir)) {
      userFilesPublic = recursiveReadDirSync(this.publicDir).map(f =>
        join('.', 'public', f)
      )
    }

    let nextFilesStatic: string[] = []
    nextFilesStatic = recursiveReadDirSync(
      join(this.distDir, 'static')
    ).map(f => join('.', relative(this.dir, this.distDir), 'static', f))

    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 已提交
1468
    if (
1469 1470 1471
      (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 已提交
1472 1473 1474 1475
    ) {
      return false
    }

1476 1477 1478 1479
    // Check against the real filesystem paths
    const filesystemUrls = this.getFilesystemPaths()
    const resolved = relative(this.dir, untrustedFilePath)
    return filesystemUrls.has(resolved)
A
Arunoda Susiripala 已提交
1480 1481
  }

1482
  protected readBuildId(): string {
1483 1484 1485 1486 1487
    const buildIdFile = join(this.distDir, BUILD_ID_FILE)
    try {
      return fs.readFileSync(buildIdFile, 'utf8').trim()
    } catch (err) {
      if (!fs.existsSync(buildIdFile)) {
J
Joe Haddad 已提交
1488
        throw new Error(
1489
          `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 已提交
1490
        )
1491 1492 1493
      }

      throw err
1494
    }
1495
  }
1496 1497 1498 1499

  private get _isLikeServerless(): boolean {
    return isTargetLikeServerless(this.nextConfig.target)
  }
1500
}
1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512

function prepareServerlessUrl(req: IncomingMessage, query: ParsedUrlQuery) {
  const curUrl = parseUrl(req.url!, true)
  req.url = formatUrl({
    ...curUrl,
    search: undefined,
    query: {
      ...curUrl.query,
      ...query,
    },
  })
}
1513 1514

class NoFallbackError extends Error {}