next-serverless-loader.ts 18.8 KB
Newer Older
G
devalue  
Guy Bedford 已提交
1
import devalue from 'next/dist/compiled/devalue'
G
Guy Bedford 已提交
2
import escapeRegexp from 'next/dist/compiled/escape-string-regexp'
3 4
import { join } from 'path'
import { parse } from 'querystring'
J
Joe Haddad 已提交
5 6
import { loader } from 'webpack'
import { API_ROUTE } from '../../../lib/constants'
7 8 9
import {
  BUILD_MANIFEST,
  REACT_LOADABLE_MANIFEST,
J
Joe Haddad 已提交
10
  ROUTES_MANIFEST,
11 12
} from '../../../next-server/lib/constants'
import { isDynamicRoute } from '../../../next-server/lib/router/utils'
J
Joe Haddad 已提交
13
import { __ApiPreviewProps } from '../../../next-server/server/api-utils'
T
Tim Neutkens 已提交
14 15

export type ServerlessLoaderQuery = {
16 17 18 19 20 21
  page: string
  distDir: string
  absolutePagePath: string
  absoluteAppPath: string
  absoluteDocumentPath: string
  absoluteErrorPath: string
22
  buildId: string
23
  assetPrefix: string
T
Tim Neutkens 已提交
24
  generateEtags: string
25
  poweredByHeader: string
26
  canonicalBase: string
T
Tim Neutkens 已提交
27
  basePath: string
28
  runtimeConfig: string
J
Joe Haddad 已提交
29
  previewProps: string
30
  loadedEnvFiles: string
T
Tim Neutkens 已提交
31 32
}

33 34
const vercelHeader = 'x-vercel-id'

J
Joe Haddad 已提交
35
const nextServerlessLoader: loader.Loader = function () {
T
Tim Neutkens 已提交
36 37 38 39
  const {
    distDir,
    absolutePagePath,
    page,
40
    buildId,
41
    canonicalBase,
T
Tim Neutkens 已提交
42 43 44 45
    assetPrefix,
    absoluteAppPath,
    absoluteDocumentPath,
    absoluteErrorPath,
46
    generateEtags,
47
    poweredByHeader,
T
Tim Neutkens 已提交
48
    basePath,
49
    runtimeConfig,
J
Joe Haddad 已提交
50
    previewProps,
51
    loadedEnvFiles,
52 53
  }: ServerlessLoaderQuery =
    typeof this.query === 'string' ? parse(this.query.substr(1)) : this.query
T
Tim Neutkens 已提交
54

T
Tim Neutkens 已提交
55
  const buildManifest = join(distDir, BUILD_MANIFEST).replace(/\\/g, '/')
56 57 58 59
  const reactLoadableManifest = join(distDir, REACT_LOADABLE_MANIFEST).replace(
    /\\/g,
    '/'
  )
60 61
  const routesManifest = join(distDir, ROUTES_MANIFEST).replace(/\\/g, '/')

62
  const escapedBuildId = escapeRegexp(buildId)
63
  const pageIsDynamicRoute = isDynamicRoute(page)
64

J
Joe Haddad 已提交
65 66 67 68
  const encodedPreviewProps = devalue(
    JSON.parse(previewProps) as __ApiPreviewProps
  )

69 70 71 72 73 74
  const defaultRouteRegex = pageIsDynamicRoute
    ? `
      const defaultRouteRegex = getRouteRegex("${page}")
    `
    : ''

75
  const normalizeDynamicRouteParams = pageIsDynamicRoute
76
    ? `
77
      function normalizeDynamicRouteParams(query) {
78
        return Object.keys(defaultRouteRegex.groups)
79 80 81
          .reduce((prev, key) => {
            let value = query[key]

82 83 84 85 86
            ${
              ''
              // non-provided optional values should be undefined so normalize
              // them to undefined
            }
87 88 89 90 91 92 93 94
            if(
              defaultRouteRegex.groups[key].optional &&
              (!value || (
                Array.isArray(value) &&
                value.length === 1 &&
                value[0] === 'index'
              ))
            ) {
95 96 97
              value = undefined
              delete query[key]
            }
98 99 100 101 102
            ${
              ''
              // query values from the proxy aren't already split into arrays
              // so make sure to normalize catch-all values
            }
103 104 105
            if (
              value &&
              typeof value === 'string' &&
106
              defaultRouteRegex.groups[key].repeat
107
            ) {
108 109 110
              value = value.split('/')
            }

111 112 113
            if (value) {
              prev[key] = value
            }
114 115 116 117 118
            return prev
          }, {})
      }
    `
    : ''
119 120
  const envLoading = `
    const { processEnv } = require('next/dist/lib/load-env-config')
121
    processEnv(${Buffer.from(loadedEnvFiles, 'base64').toString()})
122 123
  `

124 125
  const runtimeConfigImports = runtimeConfig
    ? `
126
      const { setConfig } = require('next/config')
127 128 129 130 131 132 133 134 135 136
    `
    : ''

  const runtimeConfigSetter = runtimeConfig
    ? `
      const runtimeConfig = ${runtimeConfig}
      setConfig(runtimeConfig)
    `
    : 'const runtimeConfig = {}'

137 138
  const dynamicRouteImports = pageIsDynamicRoute
    ? `
139 140
    const { getRouteMatcher } = require('next/dist/next-server/lib/router/utils/route-matcher');
      const { getRouteRegex } = require('next/dist/next-server/lib/router/utils/route-regex');
141 142 143 144 145 146 147 148 149 150
  `
    : ''

  const dynamicRouteMatcher = pageIsDynamicRoute
    ? `
    const dynamicRouteMatcher = getRouteMatcher(getRouteRegex("${page}"))
  `
    : ''

  const rewriteImports = `
151
    const { rewrites } = require('${routesManifest}')
152
    const { pathToRegexp, default: pathMatch } = require('next/dist/next-server/lib/router/utils/path-match')
153 154 155 156
  `

  const handleRewrites = `
    const getCustomRouteMatcher = pathMatch(true)
157
    const prepareDestination = require('next/dist/next-server/lib/router/utils/prepare-destination').default
158 159 160 161 162 163 164

    function handleRewrites(parsedUrl) {
      for (const rewrite of rewrites) {
        const matcher = getCustomRouteMatcher(rewrite.source)
        const params = matcher(parsedUrl.pathname)

        if (params) {
165 166
          const { parsedDestination } = prepareDestination(
            rewrite.destination,
167
            params,
168 169 170
            parsedUrl.query,
            true,
            "${basePath}"
171
          )
172

173
          Object.assign(parsedUrl.query, parsedDestination.query)
174
          delete parsedDestination.query
175

176
          Object.assign(parsedUrl, parsedDestination)
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198

          if (parsedUrl.pathname === '${page}'){
            break
          }
          ${
            pageIsDynamicRoute
              ? `
            const dynamicParams = dynamicRouteMatcher(parsedUrl.pathname);\
            if (dynamicParams) {
              parsedUrl.query = {
                ...parsedUrl.query,
                ...dynamicParams
              }
              break
            }
          `
              : ''
          }
        }
      }

      return parsedUrl
199
    }
200 201
  `

202 203 204
  const handleBasePath = basePath
    ? `
    // always strip the basePath if configured since it is required
205
    req.url = req.url.replace(new RegExp('^${basePath}'), '') || '/'
206
    parsedUrl.pathname = parsedUrl.pathname.replace(new RegExp('^${basePath}'), '') || '/'
207 208 209
  `
    : ''

210 211
  if (page.match(API_ROUTE)) {
    return `
212 213
      import initServer from 'next-plugin-loader?middleware=on-init-server!'
      import onError from 'next-plugin-loader?middleware=on-error-server!'
214 215
      import 'next/dist/next-server/server/node-polyfill-fetch'

216
      ${envLoading}
217 218
      ${runtimeConfigImports}
      ${
219 220 221
        /*
          this needs to be called first so its available for any other imports
        */
222 223
        runtimeConfigSetter
      }
224
      ${dynamicRouteImports}
225
      const { parse: parseUrl } = require('url')
226 227 228 229
      const { apiResolver } = require('next/dist/next-server/server/api-utils')
      ${rewriteImports}

      ${dynamicRouteMatcher}
230 231 232

      ${defaultRouteRegex}

233
      ${normalizeDynamicRouteParams}
234

235
      ${handleRewrites}
236

237 238 239
      export default async (req, res) => {
        try {
          await initServer()
T
Tim Neutkens 已提交
240

241 242 243
          // We need to trust the dynamic route params from the proxy
          // to ensure we are using the correct values
          const trustQuery = req.headers['${vercelHeader}']
244
          const parsedUrl = handleRewrites(parseUrl(req.url, true))
245

246 247
          ${handleBasePath}

248
          const params = ${
249
            pageIsDynamicRoute
250
              ? `
251 252 253 254 255
              normalizeDynamicRouteParams(
                trustQuery
                  ? parsedUrl.query
                  : dynamicRouteMatcher(parsedUrl.pathname)
              )
256
              `
257 258
              : `{}`
          }
259

260
          const resolver = require('${absolutePagePath}')
261
          await apiResolver(
262 263 264 265
            req,
            res,
            Object.assign({}, parsedUrl.query, params ),
            resolver,
J
Joe Haddad 已提交
266
            ${encodedPreviewProps},
267
            true,
268 269
            onError
          )
J
JJ Kasper 已提交
270
        } catch (err) {
271
          console.error(err)
J
JJ Kasper 已提交
272
          await onError(err)
273

274
          // TODO: better error for DECODE_FAILED?
275 276 277 278
          if (err.code === 'DECODE_FAILED') {
            res.statusCode = 400
            res.end('Bad Request')
          } else {
279 280
            // Throw the error to crash the serverless function
            throw err
281
          }
282 283 284 285 286
        }
      }
    `
  } else {
    return `
287 288
    import initServer from 'next-plugin-loader?middleware=on-init-server!'
    import onError from 'next-plugin-loader?middleware=on-error-server!'
289
    import 'next/dist/next-server/server/node-polyfill-fetch'
290
    const {isResSent} = require('next/dist/next-server/lib/utils');
291

292
    ${envLoading}
293 294
    ${runtimeConfigImports}
    ${
295
      // this needs to be called first so its available for any other imports
296 297
      runtimeConfigSetter
    }
298
    const {parse: parseUrl, format: formatUrl} = require('url')
299
    const {parse: parseQs} = require('querystring')
P
Prateek Bhatnagar 已提交
300
    const { renderToHTML } = require('next/dist/next-server/server/render');
301
    const { tryGetPreviewData } = require('next/dist/next-server/server/api-utils');
302
    const {sendPayload} = require('next/dist/next-server/server/send-payload');
303 304 305 306 307
    const buildManifest = require('${buildManifest}');
    const reactLoadableManifest = require('${reactLoadableManifest}');
    const Document = require('${absoluteDocumentPath}').default;
    const Error = require('${absoluteErrorPath}').default;
    const App = require('${absoluteAppPath}').default;
P
Prateek Bhatnagar 已提交
308

309 310
    ${dynamicRouteImports}
    ${rewriteImports}
311 312

    const ComponentInfo = require('${absolutePagePath}')
313

314
    const Component = ComponentInfo.default
J
JJ Kasper 已提交
315
    export default Component
316
    export const unstable_getStaticParams = ComponentInfo['unstable_getStaticParam' + 's']
317 318 319 320 321 322
    export const getStaticProps = ComponentInfo['getStaticProp' + 's']
    export const getStaticPaths = ComponentInfo['getStaticPath' + 's']
    export const getServerSideProps = ComponentInfo['getServerSideProp' + 's']

    // kept for detecting legacy exports
    export const unstable_getStaticProps = ComponentInfo['unstable_getStaticProp' + 's']
323
    export const unstable_getStaticPaths = ComponentInfo['unstable_getStaticPath' + 's']
324
    export const unstable_getServerProps = ComponentInfo['unstable_getServerProp' + 's']
325

326
    ${dynamicRouteMatcher}
327
    ${defaultRouteRegex}
328
    ${normalizeDynamicRouteParams}
329 330
    ${handleRewrites}

331
    export const config = ComponentInfo['confi' + 'g'] || {}
J
JJ Kasper 已提交
332
    export const _app = App
333 334
    export async function renderReqToHTML(req, res, renderMode, _renderOpts, _params) {
      const fromExport = renderMode === 'export' || renderMode === true;
335

T
Tim Neutkens 已提交
336 337 338 339
      const options = {
        App,
        Document,
        buildManifest,
340 341 342
        getStaticProps,
        getServerSideProps,
        getStaticPaths,
T
Tim Neutkens 已提交
343
        reactLoadableManifest,
344
        canonicalBase: "${canonicalBase}",
345
        buildId: "${buildId}",
J
JJ Kasper 已提交
346
        assetPrefix: "${assetPrefix}",
347
        runtimeConfig: runtimeConfig.publicRuntimeConfig || {},
J
Joe Haddad 已提交
348
        previewProps: ${encodedPreviewProps},
349
        env: process.env,
350
        basePath: "${basePath}",
351
        ..._renderOpts
J
JJ Kasper 已提交
352
      }
353
      let _nextData = false
354
      let parsedUrl
J
JJ Kasper 已提交
355

356
      try {
357 358 359
        // We need to trust the dynamic route params from the proxy
        // to ensure we are using the correct values
        const trustQuery = !getStaticProps && req.headers['${vercelHeader}']
360
        const parsedUrl = handleRewrites(parseUrl(req.url, true))
361

362 363
        ${handleBasePath}

364
        if (parsedUrl.pathname.match(/_next\\/data/)) {
365 366 367 368 369 370 371 372 373 374 375
          const {
            default: getRouteFromAssetPath,
          } = require('next/dist/next-server/lib/router/utils/get-route-from-asset-path');
          _nextData = true;
          parsedUrl.pathname = getRouteFromAssetPath(
            parsedUrl.pathname.replace(
              new RegExp('/_next/data/${escapedBuildId}/'),
              '/'
            ),
            '.json'
          );
376 377 378 379 380 381
        }

        const renderOpts = Object.assign(
          {
            Component,
            pageConfig: config,
382 383
            nextExport: fromExport,
            isDataReq: _nextData,
384 385 386 387 388 389 390 391 392 393 394 395 396
          },
          options,
        )

        ${
          page === '/_error'
            ? `
          if (!res.statusCode) {
            res.statusCode = 404
          }
        `
            : ''
        }
397

J
Joe Haddad 已提交
398
        ${
399
          pageIsDynamicRoute
400 401
            ? `
            const params = (
402
              fromExport
403
            ) ? {}
404 405 406 407 408
              : normalizeDynamicRouteParams(
                trustQuery
                  ? parsedUrl.query
                  : dynamicRouteMatcher(parsedUrl.pathname)
              )
409
            `
J
Joe Haddad 已提交
410 411
            : `const params = {};`
        }
412
        ${
J
Joe Haddad 已提交
413
          // Temporary work around: `x-now-route-matches` is a platform header
414 415 416 417
          // _only_ set for `Prerender` requests. We should move this logic
          // into our builder to ensure we're decoupled. However, this entails
          // removing reliance on `req.url` and using `req.query` instead
          // (which is needed for "custom routes" anyway).
418
          pageIsDynamicRoute
J
Joe Haddad 已提交
419
            ? `const nowParams = req.headers && req.headers["x-now-route-matches"]
420 421 422 423 424 425 426 427 428 429 430
              ? getRouteMatcher(
                  (function() {
                    const { re, groups } = getRouteRegex("${page}");
                    return {
                      re: {
                        // Simulate a RegExp match from the \`req.url\` input
                        exec: str => {
                          const obj = parseQs(str);
                          return Object.keys(obj).reduce(
                            (prev, key) =>
                              Object.assign(prev, {
431
                                [key]: obj[key]
432 433 434 435 436 437 438 439
                              }),
                            {}
                          );
                        }
                      },
                      groups
                    };
                  })()
J
Joe Haddad 已提交
440
                )(req.headers["x-now-route-matches"])
441 442
              : null;
          `
443 444
            : `const nowParams = null;`
        }
445

446 447 448 449
        // make sure to set renderOpts to the correct params e.g. _params
        // if provided from worker or params if we're parsing them here
        renderOpts.params = _params || params

450 451
        // make sure to normalize req.url on Vercel to strip dynamic params
        // from the query which are added during routing
452 453 454 455 456 457
        ${
          pageIsDynamicRoute
            ? `
          if (trustQuery) {
            const _parsedUrl = parseUrl(req.url, true)
            delete _parsedUrl.search
458

459 460 461 462
            for (const param of Object.keys(defaultRouteRegex.groups)) {
              delete _parsedUrl.query[param]
            }
            req.url = formatUrl(_parsedUrl)
463
          }
464 465
        `
            : ''
466 467
        }

468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490
        // normalize request URL/asPath for fallback pages since the proxy
        // sets the request URL to the output's path for fallback pages
        ${
          pageIsDynamicRoute
            ? `
            if (nowParams) {
              const _parsedUrl = parseUrl(req.url)

              for (const param of Object.keys(defaultRouteRegex.groups)) {
                const paramIdx = _parsedUrl.pathname.indexOf(\`[\${param}]\`)

                if (paramIdx > -1) {
                  _parsedUrl.pathname = _parsedUrl.pathname.substr(0, paramIdx) +
                    encodeURI(nowParams[param]) +
                    _parsedUrl.pathname.substr(paramIdx + param.length + 2)
                }
              }
              req.url = formatUrl(_parsedUrl)
            }
          `
            : ``
        }

491 492
        const isFallback = parsedUrl.query.__nextFallback

493 494 495
        const previewData = tryGetPreviewData(req, res, options.previewProps)
        const isPreviewMode = previewData !== false

P
Prateek Bhatnagar 已提交
496 497
        if (process.env.__NEXT_OPTIMIZE_FONTS) {
          renderOpts.optimizeFonts = true
498 499 500 501 502
          /**
           * __webpack_require__.__NEXT_FONT_MANIFEST__ is added by
           * font-stylesheet-gathering-plugin
           */
          renderOpts.fontManifest = __webpack_require__.__NEXT_FONT_MANIFEST__;
P
Prateek Bhatnagar 已提交
503 504
          process.env['__NEXT_OPTIMIZE_FONT'+'S'] = true
        }
505
        let result = await renderToHTML(req, res, "${page}", Object.assign({}, getStaticProps ? { ...(parsedUrl.query.amp ? { amp: '1' } : {}) } : parsedUrl.query, nowParams ? nowParams : params, _params, isFallback ? { __nextFallback: 'true' } : {}), renderOpts)
506

507 508
        if (!renderMode) {
          if (_nextData || getStaticProps || getServerSideProps) {
509 510 511
            sendPayload(req, res, _nextData ? JSON.stringify(renderOpts.pageData) : result, _nextData ? 'json' : 'html', ${
              generateEtags === 'true' ? true : false
            }, {
512 513 514 515 516 517
              private: isPreviewMode,
              stateful: !!getServerSideProps,
              revalidate: renderOpts.revalidate,
            })
            return null
          }
518 519 520 521 522
        } else if (isPreviewMode) {
          res.setHeader(
            'Cache-Control',
            'private, no-cache, no-store, max-age=0, must-revalidate'
          )
523
        }
J
JJ Kasper 已提交
524

525
        if (renderMode) return { html: result, renderOpts }
T
Tim Neutkens 已提交
526 527
        return result
      } catch (err) {
528
        if (!parsedUrl) {
529
          parsedUrl = parseUrl(req.url, true)
530 531
        }

T
Tim Neutkens 已提交
532 533
        if (err.code === 'ENOENT') {
          res.statusCode = 404
534
        } else if (err.code === 'DECODE_FAILED') {
535
          // TODO: better error?
536
          res.statusCode = 400
T
Tim Neutkens 已提交
537
        } else {
538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564
          console.error('Unhandled error during request:', err)

          // Backwards compat (call getInitialProps in custom error):
          try {
            await renderToHTML(req, res, "/_error", parsedUrl.query, Object.assign({}, options, {
              getStaticProps: undefined,
              getStaticPaths: undefined,
              getServerSideProps: undefined,
              Component: Error,
              err: err,
              // Short-circuit rendering:
              isDataReq: true
            }))
          } catch (underErrorErr) {
            console.error('Failed call /_error subroutine, continuing to crash function:', underErrorErr)
          }

          // Throw the error to crash the serverless function
          if (isResSent(res)) {
            console.error('!!! WARNING !!!')
            console.error(
              'Your function crashed, but closed the response before allowing the function to exit.\\n' +
              'This may cause unexpected behavior for the next request.'
            )
            console.error('!!! WARNING !!!')
          }
          throw err
T
Tim Neutkens 已提交
565
        }
566 567 568 569 570 571 572 573 574

        const result = await renderToHTML(req, res, "/_error", parsedUrl.query, Object.assign({}, options, {
          getStaticProps: undefined,
          getStaticPaths: undefined,
          getServerSideProps: undefined,
          Component: Error,
          err: res.statusCode === 404 ? undefined : err
        }))
        return result
T
Tim Neutkens 已提交
575 576
      }
    }
577
    export async function render (req, res) {
T
Tim Neutkens 已提交
578
      try {
579
        await initServer()
580
        const html = await renderReqToHTML(req, res)
581
        if (html) {
582 583 584
          sendPayload(req, res, html, 'html', {generateEtags: ${JSON.stringify(
            generateEtags === 'true'
          )}, poweredByHeader: ${JSON.stringify(poweredByHeader === 'true')}})
585
        }
T
Tim Neutkens 已提交
586 587
      } catch(err) {
        console.error(err)
588 589 590
        await onError(err)
        // Throw the error to crash the serverless function
        throw err
T
Tim Neutkens 已提交
591 592 593
      }
    }
  `
594
  }
T
Tim Neutkens 已提交
595 596 597
}

export default nextServerlessLoader