next-server.ts 42.0 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'
J
Joe Haddad 已提交
6
import nanoid from 'next/dist/compiled/nanoid/index.js'
7
import { join, relative, resolve, sep } from 'path'
8
import { parse as parseQs, ParsedUrlQuery } from 'querystring'
9
import { format as formatUrl, parse as parseUrl, UrlWithParsedQuery } from 'url'
10
import { PrerenderManifest } from '../../build'
J
Joe Haddad 已提交
11 12 13 14 15 16 17
import {
  getRedirectStatus,
  Header,
  Redirect,
  Rewrite,
  RouteType,
} from '../../lib/check-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'
J
JJ Kasper 已提交
68 69

const getCustomRouteMatcher = pathMatch(true)
70 71 72

type NextConfig = any

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

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

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

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

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

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

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

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

172
    this.renderOpts = {
T
Tim Neutkens 已提交
173
      poweredByHeader: this.nextConfig.poweredByHeader,
174
      canonicalBase: this.nextConfig.amp.canonicalBase,
175 176
      documentMiddlewareEnabled: this.nextConfig.experimental
        .documentMiddleware,
J
Joe Haddad 已提交
177
      hasCssMode: this.nextConfig.experimental.css,
178
      staticMarkup,
179
      buildId: this.buildId,
180
      generateEtags,
181
      previewProps: this.getPreviewProps(),
182
      customServer: customServer === true ? true : undefined,
183
      ampOptimizerConfig: this.nextConfig.experimental.amp?.optimizer,
184
      basePath: this.nextConfig.experimental.basePath,
185
    }
N
Naoyuki Kanezawa 已提交
186

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

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

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

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

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

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

242
  protected currentPhase(): string {
243
    return PHASE_PRODUCTION_SERVER
244 245
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

367 368 369 370
    let headers: Route[] = []
    let rewrites: Route[] = []
    let redirects: Route[] = []

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

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

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

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

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

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

480
      // Headers come very first
481 482 483 484 485 486
      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`,
487
          fn: async (_req, res, params, _parsedUrl) => {
488
            for (const header of (route as Header).headers) {
489 490 491 492 493 494 495 496 497 498
              let { key, value } = header
              if (key.includes(':')) {
                // see `prepareDestination` util for explanation for
                // `validate: false` being used
                key = compilePathToRegex(key, { validate: false })(params)
              }
              if (value.includes(':')) {
                value = compilePathToRegex(value, { validate: false })(params)
              }
              res.setHeader(key, value)
499 500 501 502 503
            }
            return { finished: false }
          },
        } as Route
      })
J
JJ Kasper 已提交
504

505 506 507 508 509 510 511
      redirects = this.customRoutes.redirects.map(redirect => {
        const route = getCustomRoute(redirect, 'redirect')
        return {
          type: route.type,
          match: route.match,
          statusCode: route.statusCode,
          name: `Redirect route`,
512
          fn: async (_req, res, params, parsedUrl) => {
513 514
            const { parsedDestination } = prepareDestination(
              route.destination,
515
              params,
516
              parsedUrl.query,
517
              true
518 519 520 521 522 523 524 525 526 527 528
            )
            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}`)
            }
529

530 531 532 533 534 535 536
            res.end()
            return {
              finished: true,
            }
          },
        } as Route
      })
537

538 539 540 541 542 543 544
      rewrites = this.customRoutes.rewrites.map(rewrite => {
        const route = getCustomRoute(rewrite, 'rewrite')
        return {
          check: true,
          type: route.type,
          name: `Rewrite route`,
          match: route.match,
545
          fn: async (req, res, params, parsedUrl) => {
546 547
            const { newUrl, parsedDestination } = prepareDestination(
              route.destination,
548 549
              params,
              parsedUrl.query
550 551 552 553 554 555 556 557 558
            )

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

562 563 564
              proxy.on('error', (err: Error) => {
                console.error(`Error occurred proxying ${target}`, err)
              })
565
              return {
566
                finished: true,
J
JJ Kasper 已提交
567
              }
568 569
            }
            ;(req as any)._nextDidRewrite = true
570

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

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

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

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

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

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

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

628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645
  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
  }

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

655 656 657
  // Used to build API page in development
  protected async ensureApiPage(pathname: string) {}

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

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

685
    if (!pageFound) {
686
      return false
J
JJ Kasper 已提交
687
    }
688 689 690 691 692 693
    // 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)
694
    query = { ...query, ...params }
J
JJ Kasper 已提交
695

696
    if (!this.renderOpts.dev && this._isLikeServerless) {
697
      if (typeof pageModule.default === 'function') {
698
        prepareServerlessUrl(req, query)
699 700
        await pageModule.default(req, res)
        return true
J
JJ Kasper 已提交
701 702 703
      }
    }

J
Joe Haddad 已提交
704 705 706 707 708
    await apiResolver(
      req,
      res,
      query,
      pageModule,
709
      this.renderOpts.previewProps,
J
Joe Haddad 已提交
710 711
      this.onErrorMiddleware
    )
712
    return true
L
Lukáš Huvar 已提交
713 714
  }

715
  protected generatePublicRoutes(): Route[] {
716 717 718 719 720 721 722 723 724
    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) => {
725 726
          const pathParts: string[] = params.path || []
          const path = `/${pathParts.join('/')}`
727 728 729 730 731 732

          if (publicFiles.has(path)) {
            await this.serveStatic(
              req,
              res,
              // we need to re-encode it since send decodes it
733
              join(this.publicDir, ...pathParts.map(encodeURIComponent)),
734 735
              parsedUrl
            )
736 737 738
            return {
              finished: true,
            }
739 740 741 742 743 744 745
          }
          return {
            finished: false,
          }
        },
      } as Route,
    ]
746 747
  }

748
  protected getDynamicRoutes() {
749 750 751
    const dynamicRoutedPages = Object.keys(this.pagesManifest!).filter(
      isDynamicRoute
    )
752 753 754 755
    return getSortedRoutes(dynamicRoutedPages).map(page => ({
      page,
      match: getRouteMatcher(getRouteRegex(page)),
    }))
J
Joe Haddad 已提交
756 757
  }

758 759 760 761 762 763
  private handleCompression(req: IncomingMessage, res: ServerResponse) {
    if (this.compression) {
      this.compression(req, res, () => {})
    }
  }

764
  protected async run(
J
Joe Haddad 已提交
765 766
    req: IncomingMessage,
    res: ServerResponse,
767
    parsedUrl: UrlWithParsedQuery
J
Joe Haddad 已提交
768
  ) {
769 770
    this.handleCompression(req, res)

771
    try {
772 773
      const matched = await this.router.execute(req, res, parsedUrl)
      if (matched) {
774 775 776 777 778 779 780 781
        return
      }
    } catch (err) {
      if (err.code === 'DECODE_FAILED') {
        res.statusCode = 400
        return this.renderError(null, req, res, '/_error', {})
      }
      throw err
782 783
    }

784
    await this.render404(req, res, parsedUrl)
N
nkzawa 已提交
785 786
  }

787
  protected async sendHTML(
J
Joe Haddad 已提交
788 789
    req: IncomingMessage,
    res: ServerResponse,
790
    html: string
J
Joe Haddad 已提交
791
  ) {
T
Tim Neutkens 已提交
792 793
    const { generateEtags, poweredByHeader } = this.renderOpts
    return sendHTML(req, res, html, { generateEtags, poweredByHeader })
794 795
  }

J
Joe Haddad 已提交
796 797 798 799 800
  public async render(
    req: IncomingMessage,
    res: ServerResponse,
    pathname: string,
    query: ParsedUrlQuery = {},
801
    parsedUrl?: UrlWithParsedQuery
J
Joe Haddad 已提交
802
  ): Promise<void> {
803 804 805 806 807 808
    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`
      )
    }

809
    const url: any = req.url
810

811 812 813 814
    // 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
815
    if (
816 817 818
      !query._nextDataReq &&
      (url.match(/^\/_next\//) ||
        (this.hasStaticDir && url.match(/^\/static\//)))
819
    ) {
820 821 822
      return this.handleRequest(req, res, parsedUrl)
    }

823
    if (isBlockedPage(pathname)) {
824
      return this.render404(req, res, parsedUrl)
825 826
    }

827
    const html = await this.renderToHTML(req, res, pathname, query)
828 829
    // Request was ended by the user
    if (html === null) {
830 831 832
      return
    }

833
    return this.sendHTML(req, res, html)
N
Naoyuki Kanezawa 已提交
834
  }
N
nkzawa 已提交
835

J
Joe Haddad 已提交
836
  private async findPageComponents(
J
Joe Haddad 已提交
837
    pathname: string,
838 839 840 841 842 843 844 845 846
    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 已提交
847
      try {
848
        const components = await loadComponents(
J
Joe Haddad 已提交
849 850
          this.distDir,
          this.buildId,
851 852
          pagePath!,
          !this.renderOpts.dev && this._isLikeServerless
J
Joe Haddad 已提交
853
        )
854 855 856
        return {
          components,
          query: {
857
            ...(components.getStaticProps
858
              ? { _nextDataReq: query._nextDataReq, amp: query.amp }
859 860 861 862
              : query),
            ...(params || {}),
          },
        }
J
JJ Kasper 已提交
863 864 865 866
      } catch (err) {
        if (err.code !== 'ENOENT') throw err
      }
    }
867
    return null
J
Joe Haddad 已提交
868 869
  }

870 871 872 873 874 875 876 877 878 879 880 881 882 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
  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 已提交
911 912 913 914
  private async renderToHTMLWithComponents(
    req: IncomingMessage,
    res: ServerResponse,
    pathname: string,
915
    { components, query }: FindComponentsResult,
916
    opts: RenderOptsPartial
917
  ): Promise<string | null> {
918
    // we need to ensure the status code if /404 is visited directly
919
    if (pathname === '/404') {
920 921 922
      res.statusCode = 404
    }

J
JJ Kasper 已提交
923
    // handle static page
924 925
    if (typeof components.Component === 'string') {
      return components.Component
J
Joe Haddad 已提交
926 927
    }

J
JJ Kasper 已提交
928 929
    // check request state
    const isLikeServerless =
930 931
      typeof components.Component === 'object' &&
      typeof (components.Component as any).renderReqToHTML === 'function'
932 933 934
    const isSSG = !!components.getStaticProps
    const isServerProps = !!components.getServerSideProps
    const hasStaticPaths = !!components.getStaticPaths
935

936 937 938 939 940 941 942 943
    if (isSSG && query.amp) {
      pathname += `.amp`
    }

    if (!query.amp) {
      delete query.amp
    }

944
    // Toggle whether or not this is a Data request
945
    const isDataReq = !!query._nextDataReq
946 947
    delete query._nextDataReq

948 949 950 951 952 953 954 955
    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 已提交
956
    // non-spr requests should render like normal
957
    if (!isSSG) {
J
JJ Kasper 已提交
958 959
      // handle serverless
      if (isLikeServerless) {
960
        if (isDataReq) {
961
          const renderResult = await (components.Component as any).renderReqToHTML(
962 963
            req,
            res,
964
            'passthrough'
965 966
          )

967
          sendPayload(
968 969
            res,
            JSON.stringify(renderResult?.renderOpts?.pageData),
970
            'json',
971 972
            !this.renderOpts.dev
              ? {
973 974
                  private: isPreviewMode,
                  stateful: true, // non-SSG data request
975 976
                }
              : undefined
977 978 979
          )
          return null
        }
980
        prepareServerlessUrl(req, query)
981
        return (components.Component as any).renderReqToHTML(req, res)
J
JJ Kasper 已提交
982 983
      }

984 985
      if (isDataReq && isServerProps) {
        const props = await renderToHTML(req, res, pathname, query, {
986
          ...components,
987 988 989
          ...opts,
          isDataReq,
        })
990 991 992
        sendPayload(
          res,
          JSON.stringify(props),
993
          'json',
994 995
          !this.renderOpts.dev
            ? {
996 997
                private: isPreviewMode,
                stateful: true, // GSSP data request
998 999 1000
              }
            : undefined
        )
1001 1002 1003
        return null
      }

1004
      const html = await renderToHTML(req, res, pathname, query, {
1005
        ...components,
J
JJ Kasper 已提交
1006 1007 1008
        ...opts,
      })

1009 1010
      if (html && isServerProps) {
        sendPayload(res, html, 'html', {
1011
          private: isPreviewMode,
1012
          stateful: true, // GSSP request
1013
        })
1014
        return null
1015 1016 1017 1018
      }

      return html
    }
J
Joe Haddad 已提交
1019

1020 1021
    // Compute the iSSG cache key
    let urlPathname = `${parseUrl(req.url || '').pathname!}${
1022 1023
      query.amp ? '.amp' : ''
    }`
1024 1025 1026 1027 1028 1029 1030 1031 1032

    // 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 已提交
1033 1034
    const ssgCacheKey = isPreviewMode
      ? `__` + nanoid() // Preview mode uses a throw away key to not coalesce preview invokes
1035
      : urlPathname
J
JJ Kasper 已提交
1036 1037

    // Complete the response with cached data if its present
J
Joe Haddad 已提交
1038 1039 1040 1041
    const cachedData = isPreviewMode
      ? // Preview data bypasses the cache
        undefined
      : await getSprCache(ssgCacheKey)
J
JJ Kasper 已提交
1042
    if (cachedData) {
1043
      const data = isDataReq
J
JJ Kasper 已提交
1044 1045 1046
        ? JSON.stringify(cachedData.pageData)
        : cachedData.html

1047
      sendPayload(
J
JJ Kasper 已提交
1048 1049
        res,
        data,
1050 1051 1052 1053 1054 1055 1056 1057 1058 1059
        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,
            }
1060
          : undefined
J
JJ Kasper 已提交
1061 1062 1063 1064 1065 1066
      )

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

J
JJ Kasper 已提交
1069 1070 1071 1072
    // If we're here, that means data is missing or it's stale.

    const doRender = withCoalescedInvoke(async function(): Promise<{
      html: string | null
1073
      pageData: any
J
JJ Kasper 已提交
1074 1075
      sprRevalidate: number | false
    }> {
1076
      let pageData: any
J
JJ Kasper 已提交
1077 1078 1079 1080 1081 1082
      let html: string | null
      let sprRevalidate: number | false

      let renderResult
      // handle serverless
      if (isLikeServerless) {
1083
        renderResult = await (components.Component as any).renderReqToHTML(
1084 1085
          req,
          res,
1086
          'passthrough'
1087
        )
J
JJ Kasper 已提交
1088 1089

        html = renderResult.html
1090
        pageData = renderResult.renderOpts.pageData
J
JJ Kasper 已提交
1091 1092
        sprRevalidate = renderResult.renderOpts.revalidate
      } else {
1093
        const renderOpts: RenderOpts = {
1094
          ...components,
J
JJ Kasper 已提交
1095 1096 1097 1098 1099
          ...opts,
        }
        renderResult = await renderToHTML(req, res, pathname, query, renderOpts)

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

1105
      return { html, pageData, sprRevalidate }
1106
    })
J
JJ Kasper 已提交
1107

1108
    const isProduction = !this.renderOpts.dev
J
Joe Haddad 已提交
1109
    const isDynamicPathname = isDynamicRoute(pathname)
1110
    const didRespond = isResSent(res)
1111

1112 1113 1114
    const { staticPaths, hasStaticFallback } = hasStaticPaths
      ? await this.getStaticPaths(pathname)
      : { staticPaths: undefined, hasStaticFallback: false }
1115

1116 1117 1118 1119 1120 1121 1122 1123 1124 1125
    // 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.
    //
1126
    // * Non-dynamic pages should block (though this is an impossible
1127 1128
    //   case in production).
    //
1129 1130
    // * Dynamic pages should return their skeleton if not defined in
    //   getStaticPaths, then finish the data request on the client-side.
1131
    //
J
Joe Haddad 已提交
1132
    if (
1133
      !didRespond &&
J
Joe Haddad 已提交
1134
      !isDataReq &&
1135 1136
      !isPreviewMode &&
      isDynamicPathname &&
1137 1138 1139
      // Development should trigger fallback when the path is not in
      // `getStaticPaths`
      (isProduction || !staticPaths || !staticPaths.includes(urlPathname))
J
Joe Haddad 已提交
1140
    ) {
1141 1142 1143 1144 1145 1146 1147
      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
      ) {
1148
        throw new NoFallbackError()
1149 1150
      }

1151
      let html: string
1152

1153 1154
      // Production already emitted the fallback as static HTML.
      if (isProduction) {
1155
        html = await getFallback(pathname)
1156 1157 1158
      }
      // We need to generate the fallback on-demand for development.
      else {
1159 1160
        query.__nextFallback = 'true'
        if (isLikeServerless) {
1161
          prepareServerlessUrl(req, query)
1162 1163 1164 1165 1166 1167
          const renderResult = await (components.Component as any).renderReqToHTML(
            req,
            res,
            'passthrough'
          )
          html = renderResult.html
1168 1169
        } else {
          html = (await renderToHTML(req, res, pathname, query, {
1170
            ...components,
1171 1172 1173 1174 1175
            ...opts,
          })) as string
        }
      }

1176
      sendPayload(res, html, 'html')
1177 1178
    }

1179 1180 1181 1182 1183
    const {
      isOrigin,
      value: { html, pageData, sprRevalidate },
    } = await doRender(ssgCacheKey, [])
    if (!isResSent(res)) {
1184
      sendPayload(
1185 1186
        res,
        isDataReq ? JSON.stringify(pageData) : html,
1187
        isDataReq ? 'json' : 'html',
1188
        !this.renderOpts.dev
1189 1190 1191 1192 1193
          ? {
              private: isPreviewMode,
              stateful: false, // GSP response
              revalidate: sprRevalidate,
            }
1194
          : undefined
1195 1196
      )
    }
J
JJ Kasper 已提交
1197

1198 1199 1200 1201 1202
    // Update the SPR cache if the head request
    if (isOrigin) {
      // Preview mode should not be stored in cache
      if (!isPreviewMode) {
        await setSprCache(ssgCacheKey, { html: html!, pageData }, sprRevalidate)
J
JJ Kasper 已提交
1203
      }
1204 1205 1206
    }

    return null
1207 1208
  }

1209
  public async renderToHTML(
J
Joe Haddad 已提交
1210 1211 1212
    req: IncomingMessage,
    res: ServerResponse,
    pathname: string,
1213
    query: ParsedUrlQuery = {}
J
Joe Haddad 已提交
1214
  ): Promise<string | null> {
1215 1216 1217
    try {
      const result = await this.findPageComponents(pathname, query)
      if (result) {
1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229
        try {
          return await this.renderToHTMLWithComponents(
            req,
            res,
            pathname,
            result,
            { ...this.renderOpts }
          )
        } catch (err) {
          if (!(err instanceof NoFallbackError)) {
            throw err
          }
1230
        }
1231
      }
J
Joe Haddad 已提交
1232

1233 1234 1235 1236 1237 1238
      if (this.dynamicRoutes) {
        for (const dynamicRoute of this.dynamicRoutes) {
          const params = dynamicRoute.match(pathname)
          if (!params) {
            continue
          }
J
Joe Haddad 已提交
1239

1240 1241 1242 1243 1244 1245
          const result = await this.findPageComponents(
            dynamicRoute.page,
            query,
            params
          )
          if (result) {
1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257
            try {
              return await this.renderToHTMLWithComponents(
                req,
                res,
                dynamicRoute.page,
                result,
                { ...this.renderOpts, params }
              )
            } catch (err) {
              if (!(err instanceof NoFallbackError)) {
                throw err
              }
1258
            }
J
Joe Haddad 已提交
1259 1260
          }
        }
1261 1262 1263 1264 1265 1266 1267 1268 1269
      }
    } 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 已提交
1270 1271
  }

J
Joe Haddad 已提交
1272 1273 1274 1275 1276
  public async renderError(
    err: Error | null,
    req: IncomingMessage,
    res: ServerResponse,
    pathname: string,
1277
    query: ParsedUrlQuery = {}
J
Joe Haddad 已提交
1278 1279 1280
  ): Promise<void> {
    res.setHeader(
      'Cache-Control',
1281
      'no-cache, no-store, max-age=0, must-revalidate'
J
Joe Haddad 已提交
1282
    )
N
Naoyuki Kanezawa 已提交
1283
    const html = await this.renderErrorToHTML(err, req, res, pathname, query)
1284
    if (html === null) {
1285 1286
      return
    }
1287
    return this.sendHTML(req, res, html)
N
nkzawa 已提交
1288 1289
  }

1290 1291 1292 1293 1294 1295 1296 1297 1298
  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 已提交
1299 1300 1301 1302 1303
  public async renderErrorToHTML(
    err: Error | null,
    req: IncomingMessage,
    res: ServerResponse,
    _pathname: string,
1304
    query: ParsedUrlQuery = {}
J
Joe Haddad 已提交
1305
  ) {
1306
    let result: null | FindComponentsResult = null
1307

1308 1309 1310
    const is404 = res.statusCode === 404
    let using404Page = false

1311
    // use static 404 page if available and is 404 response
1312
    if (is404) {
1313 1314
      result = await this.findPageComponents('/404')
      using404Page = result !== null
1315 1316 1317 1318 1319 1320
    }

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

1321 1322 1323 1324 1325 1326 1327 1328
    if (
      process.env.NODE_ENV !== 'production' &&
      !using404Page &&
      (await this.hasPage('/_error'))
    ) {
      this.customErrorNo404Warn()
    }

1329
    let html: string | null
1330
    try {
1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344
      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')
1345
        }
1346
        throw err
1347
      }
1348 1349 1350 1351 1352 1353
    } catch (err) {
      console.error(err)
      res.statusCode = 500
      html = 'Internal Server Error'
    }
    return html
N
Naoyuki Kanezawa 已提交
1354 1355
  }

J
Joe Haddad 已提交
1356 1357 1358
  public async render404(
    req: IncomingMessage,
    res: ServerResponse,
1359
    parsedUrl?: UrlWithParsedQuery
J
Joe Haddad 已提交
1360
  ): Promise<void> {
1361 1362
    const url: any = req.url
    const { pathname, query } = parsedUrl ? parsedUrl : parseUrl(url, true)
N
Naoyuki Kanezawa 已提交
1363
    res.statusCode = 404
1364
    return this.renderError(null, req, res, pathname!, query)
N
Naoyuki Kanezawa 已提交
1365
  }
N
Naoyuki Kanezawa 已提交
1366

J
Joe Haddad 已提交
1367 1368 1369 1370
  public async serveStatic(
    req: IncomingMessage,
    res: ServerResponse,
    path: string,
1371
    parsedUrl?: UrlWithParsedQuery
J
Joe Haddad 已提交
1372
  ): Promise<void> {
A
Arunoda Susiripala 已提交
1373
    if (!this.isServeableUrl(path)) {
1374
      return this.render404(req, res, parsedUrl)
A
Arunoda Susiripala 已提交
1375 1376
    }

1377 1378 1379 1380 1381 1382
    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 已提交
1383
    try {
1384
      await serveStatic(req, res, path)
N
Naoyuki Kanezawa 已提交
1385
    } catch (err) {
T
Tim Neutkens 已提交
1386
      if (err.code === 'ENOENT' || err.statusCode === 404) {
1387
        this.render404(req, res, parsedUrl)
1388 1389 1390
      } else if (err.statusCode === 412) {
        res.statusCode = 412
        return this.renderError(err, req, res, path)
N
Naoyuki Kanezawa 已提交
1391 1392 1393 1394 1395 1396
      } else {
        throw err
      }
    }
  }

1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 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
  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 已提交
1456
    if (
1457 1458 1459
      (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 已提交
1460 1461 1462 1463
    ) {
      return false
    }

1464 1465 1466 1467
    // Check against the real filesystem paths
    const filesystemUrls = this.getFilesystemPaths()
    const resolved = relative(this.dir, untrustedFilePath)
    return filesystemUrls.has(resolved)
A
Arunoda Susiripala 已提交
1468 1469
  }

1470
  protected readBuildId(): string {
1471 1472 1473 1474 1475
    const buildIdFile = join(this.distDir, BUILD_ID_FILE)
    try {
      return fs.readFileSync(buildIdFile, 'utf8').trim()
    } catch (err) {
      if (!fs.existsSync(buildIdFile)) {
J
Joe Haddad 已提交
1476
        throw new Error(
1477
          `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 已提交
1478
        )
1479 1480 1481
      }

      throw err
1482
    }
1483
  }
1484 1485 1486 1487

  private get _isLikeServerless(): boolean {
    return isTargetLikeServerless(this.nextConfig.target)
  }
1488
}
1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500

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

class NoFallbackError extends Error {}