next-serverless-loader.ts 13.2 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
  canonicalBase: string
T
Tim Neutkens 已提交
26
  basePath: string
27
  runtimeConfig: string
J
Joe Haddad 已提交
28
  previewProps: string
29
  loadedEnvFiles: string
T
Tim Neutkens 已提交
30 31
}

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

T
Tim Neutkens 已提交
51
  const buildManifest = join(distDir, BUILD_MANIFEST).replace(/\\/g, '/')
52 53 54 55
  const reactLoadableManifest = join(distDir, REACT_LOADABLE_MANIFEST).replace(
    /\\/g,
    '/'
  )
56 57
  const routesManifest = join(distDir, ROUTES_MANIFEST).replace(/\\/g, '/')

58
  const escapedBuildId = escapeRegexp(buildId)
59
  const pageIsDynamicRoute = isDynamicRoute(page)
60

J
Joe Haddad 已提交
61 62 63 64
  const encodedPreviewProps = devalue(
    JSON.parse(previewProps) as __ApiPreviewProps
  )

65 66 67 68 69
  const envLoading = `
    const { processEnv } = require('next/dist/lib/load-env-config')
    processEnv(${loadedEnvFiles})
  `

70 71
  const runtimeConfigImports = runtimeConfig
    ? `
72
      const { setConfig } = require('next/config')
73 74 75 76 77 78 79 80 81 82
    `
    : ''

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

83 84
  const dynamicRouteImports = pageIsDynamicRoute
    ? `
85 86
    const { getRouteMatcher } = require('next/dist/next-server/lib/router/utils/route-matcher');
      const { getRouteRegex } = require('next/dist/next-server/lib/router/utils/route-regex');
87 88 89 90 91 92 93 94 95 96
  `
    : ''

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

  const rewriteImports = `
97 98
    const { rewrites } = require('${routesManifest}')
    const { pathToRegexp, default: pathMatch } = require('next/dist/next-server/server/lib/path-match')
99 100 101 102
  `

  const handleRewrites = `
    const getCustomRouteMatcher = pathMatch(true)
103
    const {prepareDestination} = require('next/dist/next-server/server/router')
104 105 106 107 108 109 110

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

        if (params) {
111 112
          const { parsedDestination } = prepareDestination(
            rewrite.destination,
113 114
            params,
            parsedUrl.query
115
          )
116 117
          Object.assign(parsedUrl.query, parsedDestination.query, params)
          delete parsedDestination.query
118

119
          Object.assign(parsedUrl, parsedDestination)
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141

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

      return parsedUrl
142
    }
143 144 145 146
  `

  if (page.match(API_ROUTE)) {
    return `
147 148
      import initServer from 'next-plugin-loader?middleware=on-init-server!'
      import onError from 'next-plugin-loader?middleware=on-error-server!'
149 150
      import 'next/dist/next-server/server/node-polyfill-fetch'

151
      ${envLoading}
152 153
      ${runtimeConfigImports}
      ${
154 155 156
        /*
          this needs to be called first so its available for any other imports
        */
157 158
        runtimeConfigSetter
      }
159 160 161 162 163 164
      ${dynamicRouteImports}
      const { parse } = require('url')
      const { apiResolver } = require('next/dist/next-server/server/api-utils')
      ${rewriteImports}

      ${dynamicRouteMatcher}
165

166
      ${handleRewrites}
167

168 169 170
      export default async (req, res) => {
        try {
          await initServer()
T
Tim Neutkens 已提交
171 172 173 174 175 176 177 178 179 180

          ${
            basePath
              ? `
          if(req.url.startsWith('${basePath}')) {
            req.url = req.url.replace('${basePath}', '')
          }
          `
              : ''
          }
181
          const parsedUrl = handleRewrites(parse(req.url, true))
182

183
          const params = ${
184 185
            pageIsDynamicRoute
              ? `dynamicRouteMatcher(parsedUrl.pathname)`
186 187
              : `{}`
          }
188

189
          const resolver = require('${absolutePagePath}')
190
          await apiResolver(
191 192 193 194
            req,
            res,
            Object.assign({}, parsedUrl.query, params ),
            resolver,
J
Joe Haddad 已提交
195
            ${encodedPreviewProps},
196 197
            onError
          )
J
JJ Kasper 已提交
198
        } catch (err) {
199
          console.error(err)
J
JJ Kasper 已提交
200
          await onError(err)
201 202 203 204 205 206 207 208

          if (err.code === 'DECODE_FAILED') {
            res.statusCode = 400
            res.end('Bad Request')
          } else {
            res.statusCode = 500
            res.end('Internal Server Error')
          }
209 210 211 212 213
        }
      }
    `
  } else {
    return `
214 215
    import initServer from 'next-plugin-loader?middleware=on-init-server!'
    import onError from 'next-plugin-loader?middleware=on-error-server!'
216 217
    import 'next/dist/next-server/server/node-polyfill-fetch'

218
    ${envLoading}
219 220
    ${runtimeConfigImports}
    ${
221
      // this needs to be called first so its available for any other imports
222 223
      runtimeConfigSetter
    }
224 225
    const {parse} = require('url')
    const {parse: parseQs} = require('querystring')
226 227
    const {renderToHTML} = require('next/dist/next-server/server/render');
    const { tryGetPreviewData } = require('next/dist/next-server/server/api-utils');
228
    const {sendHTML} = require('next/dist/next-server/server/send-html');
229
    const {sendPayload} = require('next/dist/next-server/server/send-payload');
230 231 232 233 234 235 236
    const buildManifest = require('${buildManifest}');
    const reactLoadableManifest = require('${reactLoadableManifest}');
    const Document = require('${absoluteDocumentPath}').default;
    const Error = require('${absoluteErrorPath}').default;
    const App = require('${absoluteAppPath}').default;
    ${dynamicRouteImports}
    ${rewriteImports}
237 238

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

240
    const Component = ComponentInfo.default
J
JJ Kasper 已提交
241
    export default Component
242
    export const unstable_getStaticParams = ComponentInfo['unstable_getStaticParam' + 's']
243 244 245 246 247 248
    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']
249
    export const unstable_getStaticPaths = ComponentInfo['unstable_getStaticPath' + 's']
250
    export const unstable_getServerProps = ComponentInfo['unstable_getServerProp' + 's']
251

252 253 254
    ${dynamicRouteMatcher}
    ${handleRewrites}

255
    export const config = ComponentInfo['confi' + 'g'] || {}
J
JJ Kasper 已提交
256
    export const _app = App
257 258
    export async function renderReqToHTML(req, res, renderMode, _renderOpts, _params) {
      const fromExport = renderMode === 'export' || renderMode === true;
T
Tim Neutkens 已提交
259 260 261 262 263 264 265 266 267
      ${
        basePath
          ? `
      if(req.url.startsWith('${basePath}')) {
        req.url = req.url.replace('${basePath}', '')
      }
      `
          : ''
      }
T
Tim Neutkens 已提交
268 269 270 271
      const options = {
        App,
        Document,
        buildManifest,
272 273 274
        getStaticProps,
        getServerSideProps,
        getStaticPaths,
T
Tim Neutkens 已提交
275
        reactLoadableManifest,
276
        canonicalBase: "${canonicalBase}",
277
        buildId: "${buildId}",
J
JJ Kasper 已提交
278
        assetPrefix: "${assetPrefix}",
279
        runtimeConfig: runtimeConfig.publicRuntimeConfig || {},
J
Joe Haddad 已提交
280
        previewProps: ${encodedPreviewProps},
281
        env: process.env,
282
        basePath: "${basePath}",
283
        ..._renderOpts
J
JJ Kasper 已提交
284
      }
285
      let _nextData = false
286
      let parsedUrl
J
JJ Kasper 已提交
287

288 289
      try {
        parsedUrl = handleRewrites(parse(req.url, true))
290

291 292 293 294 295 296 297 298 299 300 301
        if (parsedUrl.pathname.match(/_next\\/data/)) {
          _nextData = true
          parsedUrl.pathname = parsedUrl.pathname
            .replace(new RegExp('/_next/data/${escapedBuildId}/'), '/')
            .replace(/\\.json$/, '')
        }

        const renderOpts = Object.assign(
          {
            Component,
            pageConfig: config,
302 303
            nextExport: fromExport,
            isDataReq: _nextData,
304 305 306 307 308 309 310 311 312 313 314 315 316
          },
          options,
        )

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

J
Joe Haddad 已提交
318
        ${
319
          pageIsDynamicRoute
320
            ? `const params = fromExport && !getStaticProps && !getServerSideProps ? {} : dynamicRouteMatcher(parsedUrl.pathname) || {};`
J
Joe Haddad 已提交
321 322
            : `const params = {};`
        }
323
        ${
J
Joe Haddad 已提交
324
          // Temporary work around: `x-now-route-matches` is a platform header
325 326 327 328
          // _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).
329
          pageIsDynamicRoute
J
Joe Haddad 已提交
330
            ? `const nowParams = req.headers && req.headers["x-now-route-matches"]
331 332 333 334 335 336 337 338 339 340 341
              ? 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, {
342
                                [key]: obj[key]
343 344 345 346 347 348 349 350
                              }),
                            {}
                          );
                        }
                      },
                      groups
                    };
                  })()
J
Joe Haddad 已提交
351
                )(req.headers["x-now-route-matches"])
352 353
              : null;
          `
354 355
            : `const nowParams = null;`
        }
356 357 358 359
        // 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

360 361
        const isFallback = parsedUrl.query.__nextFallback

362 363 364
        const previewData = tryGetPreviewData(req, res, options.previewProps)
        const isPreviewMode = previewData !== false

365
        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)
366

367 368 369 370 371 372 373 374 375
        if (!renderMode) {
          if (_nextData || getStaticProps || getServerSideProps) {
            sendPayload(res, _nextData ? JSON.stringify(renderOpts.pageData) : result, _nextData ? 'json' : 'html', {
              private: isPreviewMode,
              stateful: !!getServerSideProps,
              revalidate: renderOpts.revalidate,
            })
            return null
          }
376 377 378 379 380
        } else if (isPreviewMode) {
          res.setHeader(
            'Cache-Control',
            'private, no-cache, no-store, max-age=0, must-revalidate'
          )
381
        }
J
JJ Kasper 已提交
382

383
        if (renderMode) return { html: result, renderOpts }
T
Tim Neutkens 已提交
384 385
        return result
      } catch (err) {
386 387 388 389
        if (!parsedUrl) {
          parsedUrl = parse(req.url, true)
        }

T
Tim Neutkens 已提交
390 391
        if (err.code === 'ENOENT') {
          res.statusCode = 404
392 393
        } else if (err.code === 'DECODE_FAILED') {
          res.statusCode = 400
T
Tim Neutkens 已提交
394 395 396 397
        } else {
          console.error(err)
          res.statusCode = 500
        }
398 399 400 401 402 403 404 405 406

        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 已提交
407 408
      }
    }
409
    export async function render (req, res) {
T
Tim Neutkens 已提交
410
      try {
411
        await initServer()
412
        const html = await renderReqToHTML(req, res)
413 414 415
        if (html) {
          sendHTML(req, res, html, {generateEtags: ${generateEtags}})
        }
T
Tim Neutkens 已提交
416
      } catch(err) {
417
        await onError(err)
T
Tim Neutkens 已提交
418 419 420 421 422 423
        console.error(err)
        res.statusCode = 500
        res.end('Internal Server Error')
      }
    }
  `
424
  }
T
Tim Neutkens 已提交
425 426 427
}

export default nextServerlessLoader