next-server.ts 37.8 KB
Newer Older
1
import compression from 'compression'
J
Joe Haddad 已提交
2
import fs from 'fs'
J
Joe Haddad 已提交
3
import { IncomingMessage, ServerResponse } from 'http'
J
Joe Haddad 已提交
4 5
import Proxy from 'http-proxy'
import nanoid from 'next/dist/compiled/nanoid/index.js'
J
Joe Haddad 已提交
6
import { join, 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 { isBlockedPage } from './utils'
J
JJ Kasper 已提交
64 65

const getCustomRouteMatcher = pathMatch(true)
66 67 68

type NextConfig = any

69 70 71 72 73 74
type Middleware = (
  req: IncomingMessage,
  res: ServerResponse,
  next: (err?: Error) => void
) => void

75 76 77 78 79
type FindComponentsResult = {
  components: LoadComponentsReturnType
  query: ParsedUrlQuery
}

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

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

J
Joe Haddad 已提交
136 137 138 139 140
  public constructor({
    dir = '.',
    staticMarkup = false,
    quiet = false,
    conf = null,
J
JJ Kasper 已提交
141
    dev = false,
142
    customServer = true,
J
Joe Haddad 已提交
143
  }: ServerConstructor = {}) {
N
nkzawa 已提交
144
    this.dir = resolve(dir)
N
Naoyuki Kanezawa 已提交
145
    this.quiet = quiet
T
Tim Neutkens 已提交
146
    const phase = this.currentPhase()
147
    this.nextConfig = loadConfig(phase, this.dir, conf)
148
    this.distDir = join(this.dir, this.nextConfig.distDir)
149
    this.publicDir = join(this.dir, CLIENT_PUBLIC_FILES_PATH)
150
    this.hasStaticDir = fs.existsSync(join(this.dir, 'static'))
T
Tim Neutkens 已提交
151

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

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

164
    this.renderOpts = {
T
Tim Neutkens 已提交
165
      poweredByHeader: this.nextConfig.poweredByHeader,
166
      canonicalBase: this.nextConfig.amp.canonicalBase,
167 168
      documentMiddlewareEnabled: this.nextConfig.experimental
        .documentMiddleware,
J
Joe Haddad 已提交
169
      hasCssMode: this.nextConfig.experimental.css,
170
      staticMarkup,
171
      buildId: this.buildId,
172
      generateEtags,
173
      previewProps: this.getPreviewProps(),
174
      customServer: customServer === true ? true : undefined,
175
    }
N
Naoyuki Kanezawa 已提交
176

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

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

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

193 194 195 196 197 198 199 200 201 202
    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 已提交
203
    this.router = new Router(this.generateRoutes())
204
    this.setAssetPrefix(assetPrefix)
J
JJ Kasper 已提交
205

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

J
JJ Kasper 已提交
218 219 220 221 222 223 224 225 226 227 228 229
    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 已提交
230
  }
N
nkzawa 已提交
231

232
  protected currentPhase(): string {
233
    return PHASE_PRODUCTION_SERVER
234 235
  }

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

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

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

T
Tim Neutkens 已提交
261 262 263 264 265 266 267 268 269 270
    if (parsedUrl.pathname!.startsWith(this.nextConfig.experimental.basePath)) {
      // If replace ends up replacing the full url it'll be `undefined`, meaning we have to default it to `/`
      parsedUrl.pathname =
        parsedUrl.pathname!.replace(
          this.nextConfig.experimental.basePath,
          ''
        ) || '/'
      req.url = req.url!.replace(this.nextConfig.experimental.basePath, '')
    }

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

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

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

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

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

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

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

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

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

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

328 329 330
    const publicRoutes = fs.existsSync(this.publicDir)
      ? this.generatePublicRoutes()
      : []
J
JJ Kasper 已提交
331

332
    const staticFilesRoute = this.hasStaticDir
333 334 335 336 337 338 339
      ? [
          {
            // 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*'),
340
            name: 'static catchall',
341 342 343
            fn: async (req, res, params, parsedUrl) => {
              const p = join(this.dir, 'static', ...(params.path || []))
              await this.serveStatic(req, res, p, parsedUrl)
344 345 346
              return {
                finished: true,
              }
347 348 349 350
            },
          } as Route,
        ]
      : []
351

352 353 354 355
    let headers: Route[] = []
    let rewrites: Route[] = []
    let redirects: Route[] = []

356
    const fsRoutes: Route[] = [
T
Tim Neutkens 已提交
357
      {
358
        match: route('/_next/static/:path*'),
359 360
        type: 'route',
        name: '_next/static catchall',
361
        fn: async (req, res, params, parsedUrl) => {
T
Tim Neutkens 已提交
362 363 364
          // 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.
365 366

          // make sure to 404 for /_next/static itself
367 368 369 370 371 372
          if (!params.path) {
            await this.render404(req, res, parsedUrl)
            return {
              finished: true,
            }
          }
373

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

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

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

J
JJ Kasper 已提交
453 454
    if (this.customRoutes) {
      const getCustomRoute = (
455 456
        r: Rewrite | Redirect | Header,
        type: RouteType
457 458 459 460 461 462 463 464
      ) =>
        ({
          ...r,
          type,
          match: getCustomRouteMatcher(r.source),
          name: type,
          fn: async (req, res, params, parsedUrl) => ({ finished: false }),
        } as Route & Rewrite & Header)
J
JJ Kasper 已提交
465

466
      // Headers come very first
467 468 469 470 471 472 473 474 475 476 477 478 479 480
      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`,
          fn: async (_req, res, _params, _parsedUrl) => {
            for (const header of (route as Header).headers) {
              res.setHeader(header.key, header.value)
            }
            return { finished: false }
          },
        } as Route
      })
J
JJ Kasper 已提交
481

482 483 484 485 486 487 488 489 490 491
      redirects = this.customRoutes.redirects.map(redirect => {
        const route = getCustomRoute(redirect, 'redirect')
        return {
          type: route.type,
          match: route.match,
          statusCode: route.statusCode,
          name: `Redirect route`,
          fn: async (_req, res, params, _parsedUrl) => {
            const { parsedDestination } = prepareDestination(
              route.destination,
492 493
              params,
              true
494 495 496 497 498 499 500 501 502 503 504
            )
            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}`)
            }
505

506 507 508 509 510 511 512
            res.end()
            return {
              finished: true,
            }
          },
        } as Route
      })
513

514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
      rewrites = this.customRoutes.rewrites.map(rewrite => {
        const route = getCustomRoute(rewrite, 'rewrite')
        return {
          check: true,
          type: route.type,
          name: `Rewrite route`,
          match: route.match,
          fn: async (req, res, params, _parsedUrl) => {
            const { newUrl, parsedDestination } = prepareDestination(
              route.destination,
              params
            )

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

537 538 539
              proxy.on('error', (err: Error) => {
                console.error(`Error occurred proxying ${target}`, err)
              })
540
              return {
541
                finished: true,
J
JJ Kasper 已提交
542
              }
543 544
            }
            ;(req as any)._nextDidRewrite = true
545

546 547 548 549 550 551 552 553
            return {
              finished: false,
              pathname: newUrl,
              query: parsedDestination.query,
            }
          },
        } as Route
      })
554 555 556 557 558 559 560 561 562 563 564 565
    }

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

566
        if (params?.path?.[0] === 'api') {
567 568 569
          const handled = await this.handleApiRequest(
            req as NextApiRequest,
            res as NextApiResponse,
570 571
            pathname!,
            query
572 573 574 575 576 577 578
          )
          if (handled) {
            return { finished: true }
          }
        }

        await this.render(req, res, pathname, query, parsedUrl)
579 580 581 582
        return {
          finished: true,
        }
      },
583
    }
584

585
    const { useFileSystemPublicRoutes } = this.nextConfig
J
Joe Haddad 已提交
586

587 588
    if (useFileSystemPublicRoutes) {
      this.dynamicRoutes = this.getDynamicRoutes()
589
    }
N
nkzawa 已提交
590

591
    return {
592
      headers,
593
      fsRoutes,
594 595
      rewrites,
      redirects,
596
      catchAllRoute,
597
      useFileSystemPublicRoutes,
598 599 600
      dynamicRoutes: this.dynamicRoutes,
      pageChecker: this.hasPage.bind(this),
    }
T
Tim Neutkens 已提交
601 602
  }

603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620
  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
  }

621 622 623 624 625 626 627 628 629
  protected async _beforeCatchAllRender(
    _req: IncomingMessage,
    _res: ServerResponse,
    _params: Params,
    _parsedUrl: UrlWithParsedQuery
  ) {
    return false
  }

630 631 632
  // Used to build API page in development
  protected async ensureApiPage(pathname: string) {}

L
Lukáš Huvar 已提交
633 634 635 636 637 638
  /**
   * Resolves `API` request, in development builds on demand
   * @param req http request
   * @param res http response
   * @param pathname path of request
   */
J
Joe Haddad 已提交
639
  private async handleApiRequest(
640 641
    req: IncomingMessage,
    res: ServerResponse,
642 643
    pathname: string,
    query: ParsedUrlQuery
J
Joe Haddad 已提交
644
  ) {
645
    let page = pathname
L
Lukáš Huvar 已提交
646
    let params: Params | boolean = false
647
    let pageFound = await this.hasPage(page)
J
JJ Kasper 已提交
648

649
    if (!pageFound && this.dynamicRoutes) {
L
Lukáš Huvar 已提交
650 651
      for (const dynamicRoute of this.dynamicRoutes) {
        params = dynamicRoute.match(pathname)
652
        if (dynamicRoute.page.startsWith('/api') && params) {
653 654
          page = dynamicRoute.page
          pageFound = true
L
Lukáš Huvar 已提交
655 656 657 658 659
          break
        }
      }
    }

660
    if (!pageFound) {
661
      return false
J
JJ Kasper 已提交
662
    }
663 664 665 666 667 668
    // 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)
669
    query = { ...query, ...params }
J
JJ Kasper 已提交
670

671
    if (!this.renderOpts.dev && this._isLikeServerless) {
672
      if (typeof pageModule.default === 'function') {
673
        prepareServerlessUrl(req, query)
674 675
        await pageModule.default(req, res)
        return true
J
JJ Kasper 已提交
676 677 678
      }
    }

J
Joe Haddad 已提交
679 680 681 682 683
    await apiResolver(
      req,
      res,
      query,
      pageModule,
684
      this.renderOpts.previewProps,
J
Joe Haddad 已提交
685 686
      this.onErrorMiddleware
    )
687
    return true
L
Lukáš Huvar 已提交
688 689
  }

690
  protected generatePublicRoutes(): Route[] {
691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709
    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) => {
          const path = `/${(params.path || []).join('/')}`

          if (publicFiles.has(path)) {
            await this.serveStatic(
              req,
              res,
              // we need to re-encode it since send decodes it
              join(this.dir, 'public', encodeURIComponent(path)),
              parsedUrl
            )
710 711 712
            return {
              finished: true,
            }
713 714 715 716 717 718 719
          }
          return {
            finished: false,
          }
        },
      } as Route,
    ]
720 721
  }

722
  protected getDynamicRoutes() {
723 724 725
    const dynamicRoutedPages = Object.keys(this.pagesManifest!).filter(
      isDynamicRoute
    )
726 727 728 729
    return getSortedRoutes(dynamicRoutedPages).map(page => ({
      page,
      match: getRouteMatcher(getRouteRegex(page)),
    }))
J
Joe Haddad 已提交
730 731
  }

732 733 734 735 736 737
  private handleCompression(req: IncomingMessage, res: ServerResponse) {
    if (this.compression) {
      this.compression(req, res, () => {})
    }
  }

738
  protected async run(
J
Joe Haddad 已提交
739 740
    req: IncomingMessage,
    res: ServerResponse,
741
    parsedUrl: UrlWithParsedQuery
J
Joe Haddad 已提交
742
  ) {
743 744
    this.handleCompression(req, res)

745
    try {
746 747
      const matched = await this.router.execute(req, res, parsedUrl)
      if (matched) {
748 749 750 751 752 753 754 755
        return
      }
    } catch (err) {
      if (err.code === 'DECODE_FAILED') {
        res.statusCode = 400
        return this.renderError(null, req, res, '/_error', {})
      }
      throw err
756 757
    }

758
    await this.render404(req, res, parsedUrl)
N
nkzawa 已提交
759 760
  }

761
  protected async sendHTML(
J
Joe Haddad 已提交
762 763
    req: IncomingMessage,
    res: ServerResponse,
764
    html: string
J
Joe Haddad 已提交
765
  ) {
T
Tim Neutkens 已提交
766 767
    const { generateEtags, poweredByHeader } = this.renderOpts
    return sendHTML(req, res, html, { generateEtags, poweredByHeader })
768 769
  }

J
Joe Haddad 已提交
770 771 772 773 774
  public async render(
    req: IncomingMessage,
    res: ServerResponse,
    pathname: string,
    query: ParsedUrlQuery = {},
775
    parsedUrl?: UrlWithParsedQuery
J
Joe Haddad 已提交
776
  ): Promise<void> {
777
    const url: any = req.url
778 779 780 781 782

    if (
      url.match(/^\/_next\//) ||
      (this.hasStaticDir && url.match(/^\/static\//))
    ) {
783 784 785
      return this.handleRequest(req, res, parsedUrl)
    }

786
    if (isBlockedPage(pathname)) {
787
      return this.render404(req, res, parsedUrl)
788 789
    }

790
    const html = await this.renderToHTML(req, res, pathname, query)
791 792
    // Request was ended by the user
    if (html === null) {
793 794 795
      return
    }

796
    return this.sendHTML(req, res, html)
N
Naoyuki Kanezawa 已提交
797
  }
N
nkzawa 已提交
798

J
Joe Haddad 已提交
799
  private async findPageComponents(
J
Joe Haddad 已提交
800
    pathname: string,
801 802 803 804 805 806 807 808 809
    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 已提交
810
      try {
811
        const components = await loadComponents(
J
Joe Haddad 已提交
812 813
          this.distDir,
          this.buildId,
814 815
          pagePath!,
          !this.renderOpts.dev && this._isLikeServerless
J
Joe Haddad 已提交
816
        )
817 818 819
        return {
          components,
          query: {
820
            ...(components.getStaticProps
821 822 823 824 825
              ? { _nextDataReq: query._nextDataReq }
              : query),
            ...(params || {}),
          },
        }
J
JJ Kasper 已提交
826 827 828 829
      } catch (err) {
        if (err.code !== 'ENOENT') throw err
      }
    }
830
    return null
J
Joe Haddad 已提交
831 832
  }

833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873
  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 已提交
874 875 876 877
  private async renderToHTMLWithComponents(
    req: IncomingMessage,
    res: ServerResponse,
    pathname: string,
878
    { components, query }: FindComponentsResult,
879
    opts: RenderOptsPartial
880
  ): Promise<string | null> {
881
    // we need to ensure the status code if /404 is visited directly
882
    if (pathname === '/404') {
883 884 885
      res.statusCode = 404
    }

J
JJ Kasper 已提交
886
    // handle static page
887 888
    if (typeof components.Component === 'string') {
      return components.Component
J
Joe Haddad 已提交
889 890
    }

J
JJ Kasper 已提交
891 892
    // check request state
    const isLikeServerless =
893 894
      typeof components.Component === 'object' &&
      typeof (components.Component as any).renderReqToHTML === 'function'
895 896 897
    const isSSG = !!components.getStaticProps
    const isServerProps = !!components.getServerSideProps
    const hasStaticPaths = !!components.getStaticPaths
898 899

    // Toggle whether or not this is a Data request
900
    const isDataReq = !!query._nextDataReq
901 902 903 904 905 906 907 908 909 910 911 912
    delete query._nextDataReq

    // Serverless requests need its URL transformed back into the original
    // request path (to emulate lambda behavior in production)
    if (isLikeServerless && isDataReq) {
      let { pathname } = parseUrl(req.url || '', true)
      pathname = !pathname || pathname === '/' ? '/index' : pathname
      req.url = formatUrl({
        pathname: `/_next/data/${this.buildId}${pathname}.json`,
        query,
      })
    }
J
JJ Kasper 已提交
913

914 915 916 917 918 919 920 921
    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 已提交
922
    // non-spr requests should render like normal
923
    if (!isSSG) {
J
JJ Kasper 已提交
924 925
      // handle serverless
      if (isLikeServerless) {
926
        if (isDataReq) {
927
          const renderResult = await (components.Component as any).renderReqToHTML(
928 929
            req,
            res,
930
            'passthrough'
931 932
          )

933
          sendPayload(
934 935
            res,
            JSON.stringify(renderResult?.renderOpts?.pageData),
936
            'json',
937 938
            !this.renderOpts.dev
              ? {
939 940
                  private: isPreviewMode,
                  stateful: true, // non-SSG data request
941 942
                }
              : undefined
943 944 945
          )
          return null
        }
946
        prepareServerlessUrl(req, query)
947
        return (components.Component as any).renderReqToHTML(req, res)
J
JJ Kasper 已提交
948 949
      }

950 951
      if (isDataReq && isServerProps) {
        const props = await renderToHTML(req, res, pathname, query, {
952
          ...components,
953 954 955
          ...opts,
          isDataReq,
        })
956 957 958
        sendPayload(
          res,
          JSON.stringify(props),
959
          'json',
960 961
          !this.renderOpts.dev
            ? {
962 963
                private: isPreviewMode,
                stateful: true, // GSSP data request
964 965 966
              }
            : undefined
        )
967 968 969
        return null
      }

970
      const html = await renderToHTML(req, res, pathname, query, {
971
        ...components,
J
JJ Kasper 已提交
972 973 974
        ...opts,
      })

975 976
      if (html && isServerProps) {
        sendPayload(res, html, 'html', {
977
          private: isPreviewMode,
978
          stateful: true, // GSSP request
979
        })
980
        return null
981 982 983 984
      }

      return html
    }
J
Joe Haddad 已提交
985

J
JJ Kasper 已提交
986
    // Compute the SPR cache key
987
    const urlPathname = parseUrl(req.url || '').pathname!
J
Joe Haddad 已提交
988 989
    const ssgCacheKey = isPreviewMode
      ? `__` + nanoid() // Preview mode uses a throw away key to not coalesce preview invokes
990
      : urlPathname
J
JJ Kasper 已提交
991 992

    // Complete the response with cached data if its present
J
Joe Haddad 已提交
993 994 995 996
    const cachedData = isPreviewMode
      ? // Preview data bypasses the cache
        undefined
      : await getSprCache(ssgCacheKey)
J
JJ Kasper 已提交
997
    if (cachedData) {
998
      const data = isDataReq
J
JJ Kasper 已提交
999 1000 1001
        ? JSON.stringify(cachedData.pageData)
        : cachedData.html

1002
      sendPayload(
J
JJ Kasper 已提交
1003 1004
        res,
        data,
1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
        isDataReq ? 'json' : 'html',
        !this.renderOpts.dev
          ? {
              private: isPreviewMode,
              stateful: false, // GSP response
              revalidate:
                cachedData.curRevalidate !== undefined
                  ? cachedData.curRevalidate
                  : /* default to minimum revalidate (this should be an invariant) */ 1,
            }
1015
          : undefined
J
JJ Kasper 已提交
1016 1017 1018 1019 1020 1021
      )

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

J
JJ Kasper 已提交
1024 1025 1026 1027
    // If we're here, that means data is missing or it's stale.

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

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

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

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

1060
      return { html, pageData, sprRevalidate }
1061
    })
J
JJ Kasper 已提交
1062

1063
    const isProduction = !this.renderOpts.dev
J
Joe Haddad 已提交
1064
    const isDynamicPathname = isDynamicRoute(pathname)
1065
    const didRespond = isResSent(res)
1066

1067 1068 1069
    const { staticPaths, hasStaticFallback } = hasStaticPaths
      ? await this.getStaticPaths(pathname)
      : { staticPaths: undefined, hasStaticFallback: false }
1070

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

1106
      let html: string
1107

1108 1109
      // Production already emitted the fallback as static HTML.
      if (isProduction) {
1110
        html = await getFallback(pathname)
1111 1112 1113
      }
      // We need to generate the fallback on-demand for development.
      else {
1114 1115
        query.__nextFallback = 'true'
        if (isLikeServerless) {
1116
          prepareServerlessUrl(req, query)
1117 1118 1119 1120 1121 1122
          const renderResult = await (components.Component as any).renderReqToHTML(
            req,
            res,
            'passthrough'
          )
          html = renderResult.html
1123 1124
        } else {
          html = (await renderToHTML(req, res, pathname, query, {
1125
            ...components,
1126 1127 1128 1129 1130
            ...opts,
          })) as string
        }
      }

1131
      sendPayload(res, html, 'html')
1132 1133
    }

1134 1135 1136 1137 1138
    const {
      isOrigin,
      value: { html, pageData, sprRevalidate },
    } = await doRender(ssgCacheKey, [])
    if (!isResSent(res)) {
1139
      sendPayload(
1140 1141
        res,
        isDataReq ? JSON.stringify(pageData) : html,
1142
        isDataReq ? 'json' : 'html',
1143
        !this.renderOpts.dev
1144 1145 1146 1147 1148
          ? {
              private: isPreviewMode,
              stateful: false, // GSP response
              revalidate: sprRevalidate,
            }
1149
          : undefined
1150 1151
      )
    }
J
JJ Kasper 已提交
1152

1153 1154 1155 1156 1157
    // 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 已提交
1158
      }
1159 1160 1161
    }

    return null
1162 1163
  }

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

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

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

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

J
Joe Haddad 已提交
1245 1246 1247 1248 1249
  public async renderErrorToHTML(
    err: Error | null,
    req: IncomingMessage,
    res: ServerResponse,
    _pathname: string,
1250
    query: ParsedUrlQuery = {}
J
Joe Haddad 已提交
1251
  ) {
1252
    let result: null | FindComponentsResult = null
1253

1254 1255 1256
    const is404 = res.statusCode === 404
    let using404Page = false

1257
    // use static 404 page if available and is 404 response
1258
    if (is404) {
1259 1260
      result = await this.findPageComponents('/404')
      using404Page = result !== null
1261 1262 1263 1264 1265 1266
    }

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

1267
    let html: string | null
1268
    try {
1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282
      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')
1283
        }
1284
        throw err
1285
      }
1286 1287 1288 1289 1290 1291
    } catch (err) {
      console.error(err)
      res.statusCode = 500
      html = 'Internal Server Error'
    }
    return html
N
Naoyuki Kanezawa 已提交
1292 1293
  }

J
Joe Haddad 已提交
1294 1295 1296
  public async render404(
    req: IncomingMessage,
    res: ServerResponse,
1297
    parsedUrl?: UrlWithParsedQuery
J
Joe Haddad 已提交
1298
  ): Promise<void> {
1299 1300
    const url: any = req.url
    const { pathname, query } = parsedUrl ? parsedUrl : parseUrl(url, true)
N
Naoyuki Kanezawa 已提交
1301
    res.statusCode = 404
1302
    return this.renderError(null, req, res, pathname!, query)
N
Naoyuki Kanezawa 已提交
1303
  }
N
Naoyuki Kanezawa 已提交
1304

J
Joe Haddad 已提交
1305 1306 1307 1308
  public async serveStatic(
    req: IncomingMessage,
    res: ServerResponse,
    path: string,
1309
    parsedUrl?: UrlWithParsedQuery
J
Joe Haddad 已提交
1310
  ): Promise<void> {
A
Arunoda Susiripala 已提交
1311
    if (!this.isServeableUrl(path)) {
1312
      return this.render404(req, res, parsedUrl)
A
Arunoda Susiripala 已提交
1313 1314
    }

1315 1316 1317 1318 1319 1320
    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 已提交
1321
    try {
1322
      await serveStatic(req, res, path)
N
Naoyuki Kanezawa 已提交
1323
    } catch (err) {
T
Tim Neutkens 已提交
1324
      if (err.code === 'ENOENT' || err.statusCode === 404) {
1325
        this.render404(req, res, parsedUrl)
1326 1327 1328
      } else if (err.statusCode === 412) {
        res.statusCode = 412
        return this.renderError(err, req, res, path)
N
Naoyuki Kanezawa 已提交
1329 1330 1331 1332 1333 1334
      } else {
        throw err
      }
    }
  }

1335
  private isServeableUrl(path: string): boolean {
A
Arunoda Susiripala 已提交
1336 1337
    const resolved = resolve(path)
    if (
1338
      resolved.indexOf(join(this.distDir) + sep) !== 0 &&
1339 1340
      resolved.indexOf(join(this.dir, 'static') + sep) !== 0 &&
      resolved.indexOf(join(this.dir, 'public') + sep) !== 0
A
Arunoda Susiripala 已提交
1341 1342 1343 1344 1345 1346 1347 1348
    ) {
      // Seems like the user is trying to traverse the filesystem.
      return false
    }

    return true
  }

1349
  protected readBuildId(): string {
1350 1351 1352 1353 1354
    const buildIdFile = join(this.distDir, BUILD_ID_FILE)
    try {
      return fs.readFileSync(buildIdFile, 'utf8').trim()
    } catch (err) {
      if (!fs.existsSync(buildIdFile)) {
J
Joe Haddad 已提交
1355
        throw new Error(
1356
          `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 已提交
1357
        )
1358 1359 1360
      }

      throw err
1361
    }
1362
  }
1363 1364 1365 1366

  private get _isLikeServerless(): boolean {
    return isTargetLikeServerless(this.nextConfig.target)
  }
1367
}
1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379

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

class NoFallbackError extends Error {}