2020-03-29 01:18:22 +01:00
|
|
|
import devalue from 'next/dist/compiled/devalue'
|
2020-03-29 01:21:07 +01:00
|
|
|
import escapeRegexp from 'next/dist/compiled/escape-string-regexp'
|
2019-05-29 13:57:26 +02:00
|
|
|
import { join } from 'path'
|
|
|
|
import { parse } from 'querystring'
|
2020-02-12 02:16:42 +01:00
|
|
|
import { loader } from 'webpack'
|
|
|
|
import { API_ROUTE } from '../../../lib/constants'
|
2019-09-04 16:00:54 +02:00
|
|
|
import {
|
|
|
|
BUILD_MANIFEST,
|
|
|
|
REACT_LOADABLE_MANIFEST,
|
2020-02-12 02:16:42 +01:00
|
|
|
ROUTES_MANIFEST,
|
2019-09-04 16:00:54 +02:00
|
|
|
} from '../../../next-server/lib/constants'
|
|
|
|
import { isDynamicRoute } from '../../../next-server/lib/router/utils'
|
2020-02-12 02:16:42 +01:00
|
|
|
import { __ApiPreviewProps } from '../../../next-server/server/api-utils'
|
Serverless Next.js (#5927)
**This does not change existing behavior.**
building to serverless is completely opt-in.
- Implements `target: 'serverless'` in `next.config.js`
- Removes `next build --lambdas` (was only available on next@canary so far)
This implements the concept of build targets. Currently there will be 2 build targets:
- server (This is the target that already existed / the default, no changes here)
- serverless (New target aimed at compiling pages to serverless handlers)
The serverless target will output a single file per `page` in the `pages` directory:
- `pages/index.js` => `.next/serverless/index.js`
- `pages/about.js` => `.next/serverless/about.js`
So what is inside `.next/serverless/about.js`? All the code needed to render that specific page. It has the Node.js `http.Server` request handler function signature:
```ts
(req: http.IncomingMessage, res: http.ServerResponse) => void
```
So how do you use it? Generally you **don't** want to use the below example, but for illustration purposes it's shown how the handler is called using a plain `http.Server`:
```js
const http = require('http')
// Note that `.default` is needed because the exported module is an esmodule
const handler = require('./.next/serverless/about.js').default
const server = new http.Server((req, res) => handler(req, res))
server.listen(3000, () => console.log('Listening on http://localhost:3000'))
```
Generally you'll upload this handler function to an external service like [Now v2](https://zeit.co/now-2), the `@now/next` builder will be updated to reflect these changes. This means that it'll be no longer neccesary for `@now/next` to do some of the guesswork in creating smaller handler functions. As Next.js will output the smallest possible serverless handler function automatically.
The function has 0 dependencies so no node_modules are required to run it, and is generally very small. 45Kb zipped is the baseline, but I'm sure we can make it even smaller in the future.
One important thing to note is that the function won't try to load `next.config.js`, so `publicRuntimeConfig` / `serverRuntimeConfig` are not supported. Reasons are outlined here: #5846
So to summarize:
- every page becomes a serverless function
- the serverless function has 0 dependencies (they're all inlined)
- "just" uses the `req` and `res` coming from Node.js
- opt-in using `target: 'serverless'` in `next.config.js`
- Does not load next.config.js when executing the function
TODO:
- [x] Compile next/dynamic / `import()` into the function file, so that no extra files have to be uploaded.
- [x] Setting `assetPrefix` at build time for serverless target
- [x] Support custom /_app
- [x] Support custom /_document
- [x] Support custom /_error
- [x] Add `next.config.js` property for `target`
Need discussion:
- [ ] Since the serverless target won't support `publicRuntimeConfig` / `serverRuntimeConfig` as they're runtime values. I think we should support build-time env var replacement with webpack.DefinePlugin or similar.
- [ ] Serving static files with the correct cache-control, as there is no static file serving in the serverless target
2018-12-28 11:39:12 +01:00
|
|
|
|
|
|
|
export type ServerlessLoaderQuery = {
|
2019-05-29 13:57:26 +02:00
|
|
|
page: string
|
|
|
|
distDir: string
|
|
|
|
absolutePagePath: string
|
|
|
|
absoluteAppPath: string
|
|
|
|
absoluteDocumentPath: string
|
|
|
|
absoluteErrorPath: string
|
2020-10-22 16:54:38 +02:00
|
|
|
absolute404Path: string
|
2019-08-20 18:38:14 +02:00
|
|
|
buildId: string
|
2019-05-29 13:57:26 +02:00
|
|
|
assetPrefix: string
|
Serverless Next.js (#5927)
**This does not change existing behavior.**
building to serverless is completely opt-in.
- Implements `target: 'serverless'` in `next.config.js`
- Removes `next build --lambdas` (was only available on next@canary so far)
This implements the concept of build targets. Currently there will be 2 build targets:
- server (This is the target that already existed / the default, no changes here)
- serverless (New target aimed at compiling pages to serverless handlers)
The serverless target will output a single file per `page` in the `pages` directory:
- `pages/index.js` => `.next/serverless/index.js`
- `pages/about.js` => `.next/serverless/about.js`
So what is inside `.next/serverless/about.js`? All the code needed to render that specific page. It has the Node.js `http.Server` request handler function signature:
```ts
(req: http.IncomingMessage, res: http.ServerResponse) => void
```
So how do you use it? Generally you **don't** want to use the below example, but for illustration purposes it's shown how the handler is called using a plain `http.Server`:
```js
const http = require('http')
// Note that `.default` is needed because the exported module is an esmodule
const handler = require('./.next/serverless/about.js').default
const server = new http.Server((req, res) => handler(req, res))
server.listen(3000, () => console.log('Listening on http://localhost:3000'))
```
Generally you'll upload this handler function to an external service like [Now v2](https://zeit.co/now-2), the `@now/next` builder will be updated to reflect these changes. This means that it'll be no longer neccesary for `@now/next` to do some of the guesswork in creating smaller handler functions. As Next.js will output the smallest possible serverless handler function automatically.
The function has 0 dependencies so no node_modules are required to run it, and is generally very small. 45Kb zipped is the baseline, but I'm sure we can make it even smaller in the future.
One important thing to note is that the function won't try to load `next.config.js`, so `publicRuntimeConfig` / `serverRuntimeConfig` are not supported. Reasons are outlined here: #5846
So to summarize:
- every page becomes a serverless function
- the serverless function has 0 dependencies (they're all inlined)
- "just" uses the `req` and `res` coming from Node.js
- opt-in using `target: 'serverless'` in `next.config.js`
- Does not load next.config.js when executing the function
TODO:
- [x] Compile next/dynamic / `import()` into the function file, so that no extra files have to be uploaded.
- [x] Setting `assetPrefix` at build time for serverless target
- [x] Support custom /_app
- [x] Support custom /_document
- [x] Support custom /_error
- [x] Add `next.config.js` property for `target`
Need discussion:
- [ ] Since the serverless target won't support `publicRuntimeConfig` / `serverRuntimeConfig` as they're runtime values. I think we should support build-time env var replacement with webpack.DefinePlugin or similar.
- [ ] Serving static files with the correct cache-control, as there is no static file serving in the serverless target
2018-12-28 11:39:12 +01:00
|
|
|
generateEtags: string
|
2020-07-27 22:19:30 +02:00
|
|
|
poweredByHeader: string
|
2019-05-29 02:32:18 +02:00
|
|
|
canonicalBase: string
|
2019-12-29 20:03:12 +01:00
|
|
|
basePath: string
|
2020-02-01 14:24:22 +01:00
|
|
|
runtimeConfig: string
|
2020-02-12 02:16:42 +01:00
|
|
|
previewProps: string
|
2020-05-26 21:01:57 +02:00
|
|
|
loadedEnvFiles: string
|
2020-10-07 23:11:01 +02:00
|
|
|
i18n: string
|
Serverless Next.js (#5927)
**This does not change existing behavior.**
building to serverless is completely opt-in.
- Implements `target: 'serverless'` in `next.config.js`
- Removes `next build --lambdas` (was only available on next@canary so far)
This implements the concept of build targets. Currently there will be 2 build targets:
- server (This is the target that already existed / the default, no changes here)
- serverless (New target aimed at compiling pages to serverless handlers)
The serverless target will output a single file per `page` in the `pages` directory:
- `pages/index.js` => `.next/serverless/index.js`
- `pages/about.js` => `.next/serverless/about.js`
So what is inside `.next/serverless/about.js`? All the code needed to render that specific page. It has the Node.js `http.Server` request handler function signature:
```ts
(req: http.IncomingMessage, res: http.ServerResponse) => void
```
So how do you use it? Generally you **don't** want to use the below example, but for illustration purposes it's shown how the handler is called using a plain `http.Server`:
```js
const http = require('http')
// Note that `.default` is needed because the exported module is an esmodule
const handler = require('./.next/serverless/about.js').default
const server = new http.Server((req, res) => handler(req, res))
server.listen(3000, () => console.log('Listening on http://localhost:3000'))
```
Generally you'll upload this handler function to an external service like [Now v2](https://zeit.co/now-2), the `@now/next` builder will be updated to reflect these changes. This means that it'll be no longer neccesary for `@now/next` to do some of the guesswork in creating smaller handler functions. As Next.js will output the smallest possible serverless handler function automatically.
The function has 0 dependencies so no node_modules are required to run it, and is generally very small. 45Kb zipped is the baseline, but I'm sure we can make it even smaller in the future.
One important thing to note is that the function won't try to load `next.config.js`, so `publicRuntimeConfig` / `serverRuntimeConfig` are not supported. Reasons are outlined here: #5846
So to summarize:
- every page becomes a serverless function
- the serverless function has 0 dependencies (they're all inlined)
- "just" uses the `req` and `res` coming from Node.js
- opt-in using `target: 'serverless'` in `next.config.js`
- Does not load next.config.js when executing the function
TODO:
- [x] Compile next/dynamic / `import()` into the function file, so that no extra files have to be uploaded.
- [x] Setting `assetPrefix` at build time for serverless target
- [x] Support custom /_app
- [x] Support custom /_document
- [x] Support custom /_error
- [x] Add `next.config.js` property for `target`
Need discussion:
- [ ] Since the serverless target won't support `publicRuntimeConfig` / `serverRuntimeConfig` as they're runtime values. I think we should support build-time env var replacement with webpack.DefinePlugin or similar.
- [ ] Serving static files with the correct cache-control, as there is no static file serving in the serverless target
2018-12-28 11:39:12 +01:00
|
|
|
}
|
|
|
|
|
2020-06-23 07:31:32 +02:00
|
|
|
const vercelHeader = 'x-vercel-id'
|
|
|
|
|
2020-05-18 21:24:37 +02:00
|
|
|
const nextServerlessLoader: loader.Loader = function () {
|
Serverless Next.js (#5927)
**This does not change existing behavior.**
building to serverless is completely opt-in.
- Implements `target: 'serverless'` in `next.config.js`
- Removes `next build --lambdas` (was only available on next@canary so far)
This implements the concept of build targets. Currently there will be 2 build targets:
- server (This is the target that already existed / the default, no changes here)
- serverless (New target aimed at compiling pages to serverless handlers)
The serverless target will output a single file per `page` in the `pages` directory:
- `pages/index.js` => `.next/serverless/index.js`
- `pages/about.js` => `.next/serverless/about.js`
So what is inside `.next/serverless/about.js`? All the code needed to render that specific page. It has the Node.js `http.Server` request handler function signature:
```ts
(req: http.IncomingMessage, res: http.ServerResponse) => void
```
So how do you use it? Generally you **don't** want to use the below example, but for illustration purposes it's shown how the handler is called using a plain `http.Server`:
```js
const http = require('http')
// Note that `.default` is needed because the exported module is an esmodule
const handler = require('./.next/serverless/about.js').default
const server = new http.Server((req, res) => handler(req, res))
server.listen(3000, () => console.log('Listening on http://localhost:3000'))
```
Generally you'll upload this handler function to an external service like [Now v2](https://zeit.co/now-2), the `@now/next` builder will be updated to reflect these changes. This means that it'll be no longer neccesary for `@now/next` to do some of the guesswork in creating smaller handler functions. As Next.js will output the smallest possible serverless handler function automatically.
The function has 0 dependencies so no node_modules are required to run it, and is generally very small. 45Kb zipped is the baseline, but I'm sure we can make it even smaller in the future.
One important thing to note is that the function won't try to load `next.config.js`, so `publicRuntimeConfig` / `serverRuntimeConfig` are not supported. Reasons are outlined here: #5846
So to summarize:
- every page becomes a serverless function
- the serverless function has 0 dependencies (they're all inlined)
- "just" uses the `req` and `res` coming from Node.js
- opt-in using `target: 'serverless'` in `next.config.js`
- Does not load next.config.js when executing the function
TODO:
- [x] Compile next/dynamic / `import()` into the function file, so that no extra files have to be uploaded.
- [x] Setting `assetPrefix` at build time for serverless target
- [x] Support custom /_app
- [x] Support custom /_document
- [x] Support custom /_error
- [x] Add `next.config.js` property for `target`
Need discussion:
- [ ] Since the serverless target won't support `publicRuntimeConfig` / `serverRuntimeConfig` as they're runtime values. I think we should support build-time env var replacement with webpack.DefinePlugin or similar.
- [ ] Serving static files with the correct cache-control, as there is no static file serving in the serverless target
2018-12-28 11:39:12 +01:00
|
|
|
const {
|
|
|
|
distDir,
|
|
|
|
absolutePagePath,
|
|
|
|
page,
|
2019-08-20 18:38:14 +02:00
|
|
|
buildId,
|
2019-05-29 02:32:18 +02:00
|
|
|
canonicalBase,
|
Serverless Next.js (#5927)
**This does not change existing behavior.**
building to serverless is completely opt-in.
- Implements `target: 'serverless'` in `next.config.js`
- Removes `next build --lambdas` (was only available on next@canary so far)
This implements the concept of build targets. Currently there will be 2 build targets:
- server (This is the target that already existed / the default, no changes here)
- serverless (New target aimed at compiling pages to serverless handlers)
The serverless target will output a single file per `page` in the `pages` directory:
- `pages/index.js` => `.next/serverless/index.js`
- `pages/about.js` => `.next/serverless/about.js`
So what is inside `.next/serverless/about.js`? All the code needed to render that specific page. It has the Node.js `http.Server` request handler function signature:
```ts
(req: http.IncomingMessage, res: http.ServerResponse) => void
```
So how do you use it? Generally you **don't** want to use the below example, but for illustration purposes it's shown how the handler is called using a plain `http.Server`:
```js
const http = require('http')
// Note that `.default` is needed because the exported module is an esmodule
const handler = require('./.next/serverless/about.js').default
const server = new http.Server((req, res) => handler(req, res))
server.listen(3000, () => console.log('Listening on http://localhost:3000'))
```
Generally you'll upload this handler function to an external service like [Now v2](https://zeit.co/now-2), the `@now/next` builder will be updated to reflect these changes. This means that it'll be no longer neccesary for `@now/next` to do some of the guesswork in creating smaller handler functions. As Next.js will output the smallest possible serverless handler function automatically.
The function has 0 dependencies so no node_modules are required to run it, and is generally very small. 45Kb zipped is the baseline, but I'm sure we can make it even smaller in the future.
One important thing to note is that the function won't try to load `next.config.js`, so `publicRuntimeConfig` / `serverRuntimeConfig` are not supported. Reasons are outlined here: #5846
So to summarize:
- every page becomes a serverless function
- the serverless function has 0 dependencies (they're all inlined)
- "just" uses the `req` and `res` coming from Node.js
- opt-in using `target: 'serverless'` in `next.config.js`
- Does not load next.config.js when executing the function
TODO:
- [x] Compile next/dynamic / `import()` into the function file, so that no extra files have to be uploaded.
- [x] Setting `assetPrefix` at build time for serverless target
- [x] Support custom /_app
- [x] Support custom /_document
- [x] Support custom /_error
- [x] Add `next.config.js` property for `target`
Need discussion:
- [ ] Since the serverless target won't support `publicRuntimeConfig` / `serverRuntimeConfig` as they're runtime values. I think we should support build-time env var replacement with webpack.DefinePlugin or similar.
- [ ] Serving static files with the correct cache-control, as there is no static file serving in the serverless target
2018-12-28 11:39:12 +01:00
|
|
|
assetPrefix,
|
|
|
|
absoluteAppPath,
|
|
|
|
absoluteDocumentPath,
|
|
|
|
absoluteErrorPath,
|
2020-10-22 16:54:38 +02:00
|
|
|
absolute404Path,
|
2019-04-04 23:54:01 +02:00
|
|
|
generateEtags,
|
2020-07-27 22:19:30 +02:00
|
|
|
poweredByHeader,
|
2019-12-29 20:03:12 +01:00
|
|
|
basePath,
|
2020-02-01 14:24:22 +01:00
|
|
|
runtimeConfig,
|
2020-02-12 02:16:42 +01:00
|
|
|
previewProps,
|
2020-05-26 21:01:57 +02:00
|
|
|
loadedEnvFiles,
|
2020-10-07 23:11:01 +02:00
|
|
|
i18n,
|
2019-05-29 13:57:26 +02:00
|
|
|
}: ServerlessLoaderQuery =
|
|
|
|
typeof this.query === 'string' ? parse(this.query.substr(1)) : this.query
|
2019-12-29 20:03:12 +01:00
|
|
|
|
Serverless Next.js (#5927)
**This does not change existing behavior.**
building to serverless is completely opt-in.
- Implements `target: 'serverless'` in `next.config.js`
- Removes `next build --lambdas` (was only available on next@canary so far)
This implements the concept of build targets. Currently there will be 2 build targets:
- server (This is the target that already existed / the default, no changes here)
- serverless (New target aimed at compiling pages to serverless handlers)
The serverless target will output a single file per `page` in the `pages` directory:
- `pages/index.js` => `.next/serverless/index.js`
- `pages/about.js` => `.next/serverless/about.js`
So what is inside `.next/serverless/about.js`? All the code needed to render that specific page. It has the Node.js `http.Server` request handler function signature:
```ts
(req: http.IncomingMessage, res: http.ServerResponse) => void
```
So how do you use it? Generally you **don't** want to use the below example, but for illustration purposes it's shown how the handler is called using a plain `http.Server`:
```js
const http = require('http')
// Note that `.default` is needed because the exported module is an esmodule
const handler = require('./.next/serverless/about.js').default
const server = new http.Server((req, res) => handler(req, res))
server.listen(3000, () => console.log('Listening on http://localhost:3000'))
```
Generally you'll upload this handler function to an external service like [Now v2](https://zeit.co/now-2), the `@now/next` builder will be updated to reflect these changes. This means that it'll be no longer neccesary for `@now/next` to do some of the guesswork in creating smaller handler functions. As Next.js will output the smallest possible serverless handler function automatically.
The function has 0 dependencies so no node_modules are required to run it, and is generally very small. 45Kb zipped is the baseline, but I'm sure we can make it even smaller in the future.
One important thing to note is that the function won't try to load `next.config.js`, so `publicRuntimeConfig` / `serverRuntimeConfig` are not supported. Reasons are outlined here: #5846
So to summarize:
- every page becomes a serverless function
- the serverless function has 0 dependencies (they're all inlined)
- "just" uses the `req` and `res` coming from Node.js
- opt-in using `target: 'serverless'` in `next.config.js`
- Does not load next.config.js when executing the function
TODO:
- [x] Compile next/dynamic / `import()` into the function file, so that no extra files have to be uploaded.
- [x] Setting `assetPrefix` at build time for serverless target
- [x] Support custom /_app
- [x] Support custom /_document
- [x] Support custom /_error
- [x] Add `next.config.js` property for `target`
Need discussion:
- [ ] Since the serverless target won't support `publicRuntimeConfig` / `serverRuntimeConfig` as they're runtime values. I think we should support build-time env var replacement with webpack.DefinePlugin or similar.
- [ ] Serving static files with the correct cache-control, as there is no static file serving in the serverless target
2018-12-28 11:39:12 +01:00
|
|
|
const buildManifest = join(distDir, BUILD_MANIFEST).replace(/\\/g, '/')
|
2019-05-29 13:57:26 +02:00
|
|
|
const reactLoadableManifest = join(distDir, REACT_LOADABLE_MANIFEST).replace(
|
|
|
|
/\\/g,
|
|
|
|
'/'
|
|
|
|
)
|
2019-12-23 22:20:17 +01:00
|
|
|
const routesManifest = join(distDir, ROUTES_MANIFEST).replace(/\\/g, '/')
|
|
|
|
|
2020-01-25 00:27:39 +01:00
|
|
|
const escapedBuildId = escapeRegexp(buildId)
|
2019-12-23 22:20:17 +01:00
|
|
|
const pageIsDynamicRoute = isDynamicRoute(page)
|
2019-07-07 23:45:40 +02:00
|
|
|
|
2020-02-12 02:16:42 +01:00
|
|
|
const encodedPreviewProps = devalue(
|
|
|
|
JSON.parse(previewProps) as __ApiPreviewProps
|
|
|
|
)
|
|
|
|
|
2020-10-07 23:11:01 +02:00
|
|
|
const i18nEnabled = !!i18n
|
|
|
|
|
2020-08-05 21:29:38 +02:00
|
|
|
const defaultRouteRegex = pageIsDynamicRoute
|
|
|
|
? `
|
|
|
|
const defaultRouteRegex = getRouteRegex("${page}")
|
|
|
|
`
|
|
|
|
: ''
|
|
|
|
|
2020-08-21 20:13:24 +02:00
|
|
|
const normalizeDynamicRouteParams = pageIsDynamicRoute
|
2020-06-23 07:31:32 +02:00
|
|
|
? `
|
2020-08-21 20:13:24 +02:00
|
|
|
function normalizeDynamicRouteParams(query) {
|
2020-08-05 21:29:38 +02:00
|
|
|
return Object.keys(defaultRouteRegex.groups)
|
2020-06-23 07:31:32 +02:00
|
|
|
.reduce((prev, key) => {
|
|
|
|
let value = query[key]
|
|
|
|
|
2020-11-01 05:49:48 +01:00
|
|
|
// if the value matches the default value we can't rely
|
|
|
|
// on the parsed params, this is used to signal if we need
|
|
|
|
// to parse x-now-route-matches or not
|
|
|
|
const isDefaultValue = Array.isArray(value)
|
|
|
|
? value.every((val, idx) => val === defaultRouteMatches[key][idx])
|
|
|
|
: value === defaultRouteMatches[key]
|
|
|
|
|
|
|
|
if (isDefaultValue || typeof value === 'undefined') {
|
|
|
|
hasValidParams = false
|
|
|
|
}
|
|
|
|
|
2020-07-29 16:19:25 +02:00
|
|
|
${
|
|
|
|
''
|
|
|
|
// non-provided optional values should be undefined so normalize
|
|
|
|
// them to undefined
|
|
|
|
}
|
2020-08-21 20:13:24 +02:00
|
|
|
if(
|
|
|
|
defaultRouteRegex.groups[key].optional &&
|
|
|
|
(!value || (
|
|
|
|
Array.isArray(value) &&
|
|
|
|
value.length === 1 &&
|
2020-10-05 09:34:50 +02:00
|
|
|
${
|
|
|
|
''
|
|
|
|
// fallback optional catch-all SSG pages have
|
|
|
|
// [[...paramName]] for the root path on Vercel
|
|
|
|
}
|
|
|
|
(value[0] === 'index' || value[0] === \`[[...\${key}]]\`)
|
2020-08-21 20:13:24 +02:00
|
|
|
))
|
|
|
|
) {
|
2020-07-29 16:19:25 +02:00
|
|
|
value = undefined
|
|
|
|
delete query[key]
|
|
|
|
}
|
2020-06-23 07:31:32 +02:00
|
|
|
${
|
|
|
|
''
|
|
|
|
// query values from the proxy aren't already split into arrays
|
|
|
|
// so make sure to normalize catch-all values
|
|
|
|
}
|
2020-07-29 16:19:25 +02:00
|
|
|
if (
|
|
|
|
value &&
|
|
|
|
typeof value === 'string' &&
|
2020-08-05 21:29:38 +02:00
|
|
|
defaultRouteRegex.groups[key].repeat
|
2020-07-29 16:19:25 +02:00
|
|
|
) {
|
2020-06-23 07:31:32 +02:00
|
|
|
value = value.split('/')
|
|
|
|
}
|
|
|
|
|
2020-07-29 16:19:25 +02:00
|
|
|
if (value) {
|
|
|
|
prev[key] = value
|
|
|
|
}
|
2020-06-23 07:31:32 +02:00
|
|
|
return prev
|
|
|
|
}, {})
|
|
|
|
}
|
|
|
|
`
|
|
|
|
: ''
|
2020-11-01 05:49:48 +01:00
|
|
|
|
2020-05-26 21:01:57 +02:00
|
|
|
const envLoading = `
|
2020-09-25 20:14:28 +02:00
|
|
|
const { processEnv } = require('@next/env')
|
2020-06-30 23:33:37 +02:00
|
|
|
processEnv(${Buffer.from(loadedEnvFiles, 'base64').toString()})
|
2020-05-26 21:01:57 +02:00
|
|
|
`
|
|
|
|
|
2020-02-01 14:24:22 +01:00
|
|
|
const runtimeConfigImports = runtimeConfig
|
|
|
|
? `
|
2020-03-02 18:38:16 +01:00
|
|
|
const { setConfig } = require('next/config')
|
2020-02-01 14:24:22 +01:00
|
|
|
`
|
|
|
|
: ''
|
|
|
|
|
|
|
|
const runtimeConfigSetter = runtimeConfig
|
|
|
|
? `
|
|
|
|
const runtimeConfig = ${runtimeConfig}
|
|
|
|
setConfig(runtimeConfig)
|
|
|
|
`
|
|
|
|
: 'const runtimeConfig = {}'
|
|
|
|
|
2019-12-23 22:20:17 +01:00
|
|
|
const dynamicRouteImports = pageIsDynamicRoute
|
|
|
|
? `
|
2020-02-03 04:33:53 +01:00
|
|
|
const { getRouteMatcher } = require('next/dist/next-server/lib/router/utils/route-matcher');
|
|
|
|
const { getRouteRegex } = require('next/dist/next-server/lib/router/utils/route-regex');
|
2019-12-23 22:20:17 +01:00
|
|
|
`
|
|
|
|
: ''
|
|
|
|
|
|
|
|
const dynamicRouteMatcher = pageIsDynamicRoute
|
|
|
|
? `
|
|
|
|
const dynamicRouteMatcher = getRouteMatcher(getRouteRegex("${page}"))
|
2020-11-01 05:49:48 +01:00
|
|
|
const defaultRouteMatches = dynamicRouteMatcher("${page}")
|
2019-12-23 22:20:17 +01:00
|
|
|
`
|
|
|
|
: ''
|
|
|
|
|
|
|
|
const rewriteImports = `
|
2020-02-03 04:33:53 +01:00
|
|
|
const { rewrites } = require('${routesManifest}')
|
2020-08-21 21:11:25 +02:00
|
|
|
const { pathToRegexp, default: pathMatch } = require('next/dist/next-server/lib/router/utils/path-match')
|
2019-12-23 22:20:17 +01:00
|
|
|
`
|
|
|
|
|
|
|
|
const handleRewrites = `
|
|
|
|
const getCustomRouteMatcher = pathMatch(true)
|
2020-08-13 14:39:36 +02:00
|
|
|
const prepareDestination = require('next/dist/next-server/lib/router/utils/prepare-destination').default
|
2019-12-23 22:20:17 +01:00
|
|
|
|
|
|
|
function handleRewrites(parsedUrl) {
|
|
|
|
for (const rewrite of rewrites) {
|
|
|
|
const matcher = getCustomRouteMatcher(rewrite.source)
|
|
|
|
const params = matcher(parsedUrl.pathname)
|
|
|
|
|
|
|
|
if (params) {
|
2020-02-26 19:14:34 +01:00
|
|
|
const { parsedDestination } = prepareDestination(
|
|
|
|
rewrite.destination,
|
2020-04-11 12:57:52 +02:00
|
|
|
params,
|
2020-07-12 21:03:49 +02:00
|
|
|
parsedUrl.query,
|
|
|
|
true,
|
|
|
|
"${basePath}"
|
2019-12-23 22:20:17 +01:00
|
|
|
)
|
2020-06-23 07:31:32 +02:00
|
|
|
|
2020-08-14 20:51:58 +02:00
|
|
|
Object.assign(parsedUrl.query, parsedDestination.query)
|
2020-02-26 19:14:34 +01:00
|
|
|
delete parsedDestination.query
|
2019-12-23 22:20:17 +01:00
|
|
|
|
2020-02-26 19:14:34 +01:00
|
|
|
Object.assign(parsedUrl, parsedDestination)
|
2019-12-23 22:20:17 +01:00
|
|
|
|
|
|
|
if (parsedUrl.pathname === '${page}'){
|
|
|
|
break
|
|
|
|
}
|
|
|
|
${
|
|
|
|
pageIsDynamicRoute
|
|
|
|
? `
|
|
|
|
const dynamicParams = dynamicRouteMatcher(parsedUrl.pathname);\
|
|
|
|
if (dynamicParams) {
|
|
|
|
parsedUrl.query = {
|
|
|
|
...parsedUrl.query,
|
|
|
|
...dynamicParams
|
|
|
|
}
|
|
|
|
break
|
|
|
|
}
|
|
|
|
`
|
|
|
|
: ''
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return parsedUrl
|
2019-07-07 23:45:40 +02:00
|
|
|
}
|
2019-12-23 22:20:17 +01:00
|
|
|
`
|
|
|
|
|
2020-06-11 16:06:06 +02:00
|
|
|
const handleBasePath = basePath
|
|
|
|
? `
|
|
|
|
// always strip the basePath if configured since it is required
|
2020-07-07 07:24:38 +02:00
|
|
|
req.url = req.url.replace(new RegExp('^${basePath}'), '') || '/'
|
2020-07-12 21:03:49 +02:00
|
|
|
parsedUrl.pathname = parsedUrl.pathname.replace(new RegExp('^${basePath}'), '') || '/'
|
2020-06-11 16:06:06 +02:00
|
|
|
`
|
|
|
|
: ''
|
|
|
|
|
2020-10-07 23:11:01 +02:00
|
|
|
const handleLocale = i18nEnabled
|
|
|
|
? `
|
|
|
|
// get pathname from URL with basePath stripped for locale detection
|
|
|
|
const i18n = ${i18n}
|
|
|
|
const accept = require('@hapi/accept')
|
2020-10-14 23:02:38 +02:00
|
|
|
const cookie = require('next/dist/compiled/cookie')
|
2020-10-07 23:11:01 +02:00
|
|
|
const { detectLocaleCookie } = require('next/dist/next-server/lib/i18n/detect-locale-cookie')
|
2020-10-14 11:56:58 +02:00
|
|
|
const { detectDomainLocale } = require('next/dist/next-server/lib/i18n/detect-domain-locale')
|
2020-10-07 23:11:01 +02:00
|
|
|
const { normalizeLocalePath } = require('next/dist/next-server/lib/i18n/normalize-locale-path')
|
2020-10-14 11:56:58 +02:00
|
|
|
let locales = i18n.locales
|
|
|
|
let defaultLocale = i18n.defaultLocale
|
2020-10-07 23:11:01 +02:00
|
|
|
let detectedLocale = detectLocaleCookie(req, i18n.locales)
|
2020-11-02 22:02:15 +01:00
|
|
|
let acceptPreferredLocale = i18n.localeDetection !== false
|
|
|
|
? accept.language(
|
|
|
|
req.headers['accept-language'],
|
|
|
|
i18n.locales
|
|
|
|
)
|
|
|
|
: detectedLocale
|
2020-10-07 23:11:01 +02:00
|
|
|
|
2020-10-20 12:23:11 +02:00
|
|
|
const { host } = req.headers || {}
|
|
|
|
// remove port from host and remove port if present
|
|
|
|
const hostname = host && host.split(':')[0].toLowerCase()
|
|
|
|
|
2020-10-14 11:56:58 +02:00
|
|
|
const detectedDomain = detectDomainLocale(
|
2020-10-10 12:22:45 +02:00
|
|
|
i18n.domains,
|
2020-10-20 12:23:11 +02:00
|
|
|
hostname,
|
2020-10-10 12:22:45 +02:00
|
|
|
)
|
2020-10-14 11:56:58 +02:00
|
|
|
if (detectedDomain) {
|
|
|
|
defaultLocale = detectedDomain.defaultLocale
|
|
|
|
detectedLocale = defaultLocale
|
|
|
|
}
|
2020-10-10 12:22:45 +02:00
|
|
|
|
2020-10-14 23:02:38 +02:00
|
|
|
// if not domain specific locale use accept-language preferred
|
|
|
|
detectedLocale = detectedLocale || acceptPreferredLocale
|
2020-10-07 23:11:01 +02:00
|
|
|
|
2020-10-14 11:56:58 +02:00
|
|
|
let localeDomainRedirect
|
|
|
|
const localePathResult = normalizeLocalePath(parsedUrl.pathname, i18n.locales)
|
|
|
|
|
2020-10-16 11:27:34 +02:00
|
|
|
routeNoAssetPath = normalizeLocalePath(routeNoAssetPath, i18n.locales).pathname
|
|
|
|
|
2020-10-14 11:56:58 +02:00
|
|
|
if (localePathResult.detectedLocale) {
|
|
|
|
detectedLocale = localePathResult.detectedLocale
|
|
|
|
req.url = formatUrl({
|
|
|
|
...parsedUrl,
|
|
|
|
pathname: localePathResult.pathname,
|
|
|
|
})
|
2020-10-27 09:45:39 +01:00
|
|
|
req.__nextStrippedLocale = true
|
2020-10-14 11:56:58 +02:00
|
|
|
parsedUrl.pathname = localePathResult.pathname
|
2020-10-27 09:45:39 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// If a detected locale is a domain specific locale and we aren't already
|
|
|
|
// on that domain and path prefix redirect to it to prevent duplicate
|
|
|
|
// content from multiple domains
|
|
|
|
if (detectedDomain) {
|
|
|
|
const localeToCheck = localePathResult.detectedLocale
|
|
|
|
? detectedLocale
|
|
|
|
: acceptPreferredLocale
|
2020-10-14 11:56:58 +02:00
|
|
|
|
2020-10-21 11:35:01 +02:00
|
|
|
const matchedDomain = detectDomainLocale(
|
|
|
|
i18n.domains,
|
|
|
|
undefined,
|
2020-10-27 09:45:39 +01:00
|
|
|
localeToCheck
|
2020-10-21 11:35:01 +02:00
|
|
|
)
|
2020-10-14 11:56:58 +02:00
|
|
|
|
2020-10-21 11:35:01 +02:00
|
|
|
if (matchedDomain && matchedDomain.domain !== detectedDomain.domain) {
|
|
|
|
localeDomainRedirect = \`http\${matchedDomain.http ? '' : 's'}://\${
|
|
|
|
matchedDomain.domain
|
2020-10-27 09:45:39 +01:00
|
|
|
}/\${
|
|
|
|
localeToCheck === matchedDomain.defaultLocale ? '' : localeToCheck
|
2020-10-21 11:35:01 +02:00
|
|
|
}\`
|
2020-10-14 11:56:58 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-10-08 13:12:17 +02:00
|
|
|
const denormalizedPagePath = denormalizePagePath(parsedUrl.pathname || '/')
|
2020-10-14 11:56:58 +02:00
|
|
|
const detectedDefaultLocale =
|
|
|
|
!detectedLocale ||
|
|
|
|
detectedLocale.toLowerCase() === defaultLocale.toLowerCase()
|
2020-10-21 11:35:01 +02:00
|
|
|
const shouldStripDefaultLocale = false
|
|
|
|
// detectedDefaultLocale &&
|
|
|
|
// denormalizedPagePath.toLowerCase() === \`/\${i18n.defaultLocale.toLowerCase()}\`
|
2020-10-14 23:02:38 +02:00
|
|
|
|
2020-10-08 13:12:17 +02:00
|
|
|
const shouldAddLocalePrefix =
|
|
|
|
!detectedDefaultLocale && denormalizedPagePath === '/'
|
2020-10-10 12:22:45 +02:00
|
|
|
|
2020-10-14 11:56:58 +02:00
|
|
|
detectedLocale = detectedLocale || i18n.defaultLocale
|
2020-10-08 13:12:17 +02:00
|
|
|
|
2020-10-07 23:11:01 +02:00
|
|
|
if (
|
2020-10-09 11:13:05 +02:00
|
|
|
!fromExport &&
|
2020-10-07 23:11:01 +02:00
|
|
|
!nextStartMode &&
|
2020-10-20 12:23:11 +02:00
|
|
|
!req.headers["${vercelHeader}"] &&
|
2020-10-07 23:11:01 +02:00
|
|
|
i18n.localeDetection !== false &&
|
2020-10-14 11:56:58 +02:00
|
|
|
(
|
|
|
|
localeDomainRedirect ||
|
|
|
|
shouldAddLocalePrefix ||
|
|
|
|
shouldStripDefaultLocale
|
|
|
|
)
|
2020-10-07 23:11:01 +02:00
|
|
|
) {
|
2020-10-14 23:02:38 +02:00
|
|
|
// set the NEXT_LOCALE cookie when a user visits the default locale
|
|
|
|
// with the locale prefix so that they aren't redirected back to
|
|
|
|
// their accept-language preferred locale
|
|
|
|
if (
|
|
|
|
shouldStripDefaultLocale &&
|
|
|
|
acceptPreferredLocale !== defaultLocale
|
|
|
|
) {
|
|
|
|
const previous = res.getHeader('set-cookie')
|
|
|
|
|
|
|
|
res.setHeader(
|
|
|
|
'set-cookie',
|
|
|
|
[
|
|
|
|
...(typeof previous === 'string'
|
|
|
|
? [previous]
|
|
|
|
: Array.isArray(previous)
|
|
|
|
? previous
|
|
|
|
: []),
|
|
|
|
cookie.serialize('NEXT_LOCALE', defaultLocale, {
|
|
|
|
httpOnly: true,
|
|
|
|
path: '/',
|
|
|
|
})
|
|
|
|
])
|
|
|
|
}
|
|
|
|
|
2020-10-07 23:11:01 +02:00
|
|
|
res.setHeader(
|
|
|
|
'Location',
|
|
|
|
formatUrl({
|
|
|
|
// make sure to include any query values when redirecting
|
|
|
|
...parsedUrl,
|
2020-10-14 11:56:58 +02:00
|
|
|
pathname:
|
|
|
|
localeDomainRedirect
|
|
|
|
? localeDomainRedirect
|
|
|
|
: shouldStripDefaultLocale
|
|
|
|
? '/'
|
|
|
|
: \`/\${detectedLocale}\`,
|
2020-10-07 23:11:01 +02:00
|
|
|
})
|
|
|
|
)
|
|
|
|
res.statusCode = 307
|
|
|
|
res.end()
|
2020-10-08 13:12:17 +02:00
|
|
|
return
|
2020-10-07 23:11:01 +02:00
|
|
|
}
|
2020-10-16 11:27:34 +02:00
|
|
|
|
2020-11-03 00:00:41 +01:00
|
|
|
detectedLocale =
|
|
|
|
localePathResult.detectedLocale ||
|
|
|
|
(detectedDomain && detectedDomain.defaultLocale) ||
|
|
|
|
defaultLocale
|
2020-10-07 23:11:01 +02:00
|
|
|
`
|
|
|
|
: `
|
|
|
|
const i18n = {}
|
|
|
|
const detectedLocale = undefined
|
2020-10-10 12:22:45 +02:00
|
|
|
const defaultLocale = undefined
|
|
|
|
const locales = undefined
|
2020-10-07 23:11:01 +02:00
|
|
|
`
|
|
|
|
|
2019-12-23 22:20:17 +01:00
|
|
|
if (page.match(API_ROUTE)) {
|
|
|
|
return `
|
2019-11-01 20:13:13 +01:00
|
|
|
import initServer from 'next-plugin-loader?middleware=on-init-server!'
|
|
|
|
import onError from 'next-plugin-loader?middleware=on-error-server!'
|
2020-05-12 21:58:21 +02:00
|
|
|
import 'next/dist/next-server/server/node-polyfill-fetch'
|
|
|
|
|
2020-05-26 21:01:57 +02:00
|
|
|
${envLoading}
|
2020-02-01 14:24:22 +01:00
|
|
|
${runtimeConfigImports}
|
|
|
|
${
|
2020-02-03 04:33:53 +01:00
|
|
|
/*
|
|
|
|
this needs to be called first so its available for any other imports
|
|
|
|
*/
|
2020-02-01 14:24:22 +01:00
|
|
|
runtimeConfigSetter
|
|
|
|
}
|
2020-02-03 04:33:53 +01:00
|
|
|
${dynamicRouteImports}
|
2020-08-05 21:29:38 +02:00
|
|
|
const { parse: parseUrl } = require('url')
|
2020-02-03 04:33:53 +01:00
|
|
|
const { apiResolver } = require('next/dist/next-server/server/api-utils')
|
|
|
|
${rewriteImports}
|
|
|
|
|
|
|
|
${dynamicRouteMatcher}
|
2020-08-05 21:29:38 +02:00
|
|
|
|
|
|
|
${defaultRouteRegex}
|
|
|
|
|
2020-02-03 04:33:53 +01:00
|
|
|
${handleRewrites}
|
2019-07-10 21:23:28 +02:00
|
|
|
|
2019-11-01 20:13:13 +01:00
|
|
|
export default async (req, res) => {
|
|
|
|
try {
|
|
|
|
await initServer()
|
2019-12-29 20:03:12 +01:00
|
|
|
|
2020-06-23 07:31:32 +02:00
|
|
|
// We need to trust the dynamic route params from the proxy
|
|
|
|
// to ensure we are using the correct values
|
|
|
|
const trustQuery = req.headers['${vercelHeader}']
|
2020-08-05 21:29:38 +02:00
|
|
|
const parsedUrl = handleRewrites(parseUrl(req.url, true))
|
2020-11-01 05:49:48 +01:00
|
|
|
let hasValidParams = true
|
2019-12-23 22:20:17 +01:00
|
|
|
|
2020-11-01 05:49:48 +01:00
|
|
|
${normalizeDynamicRouteParams}
|
2020-07-12 21:03:49 +02:00
|
|
|
${handleBasePath}
|
|
|
|
|
2019-11-01 20:13:13 +01:00
|
|
|
const params = ${
|
2019-12-23 22:20:17 +01:00
|
|
|
pageIsDynamicRoute
|
2020-06-23 07:31:32 +02:00
|
|
|
? `
|
2020-08-21 20:13:24 +02:00
|
|
|
normalizeDynamicRouteParams(
|
|
|
|
trustQuery
|
|
|
|
? parsedUrl.query
|
|
|
|
: dynamicRouteMatcher(parsedUrl.pathname)
|
|
|
|
)
|
2020-06-23 07:31:32 +02:00
|
|
|
`
|
2019-11-01 20:13:13 +01:00
|
|
|
: `{}`
|
|
|
|
}
|
2019-12-23 22:20:17 +01:00
|
|
|
|
2020-10-14 11:55:42 +02:00
|
|
|
const resolver = await require('${absolutePagePath}')
|
2020-04-14 17:43:46 +02:00
|
|
|
await apiResolver(
|
2019-12-23 22:20:17 +01:00
|
|
|
req,
|
|
|
|
res,
|
|
|
|
Object.assign({}, parsedUrl.query, params ),
|
|
|
|
resolver,
|
2020-02-12 02:16:42 +01:00
|
|
|
${encodedPreviewProps},
|
2020-06-02 01:12:45 +02:00
|
|
|
true,
|
2019-12-23 22:20:17 +01:00
|
|
|
onError
|
|
|
|
)
|
2019-11-16 03:00:24 +01:00
|
|
|
} catch (err) {
|
2019-11-01 20:13:13 +01:00
|
|
|
console.error(err)
|
2019-11-16 03:00:24 +01:00
|
|
|
await onError(err)
|
2020-04-02 09:24:32 +02:00
|
|
|
|
2020-06-02 01:12:45 +02:00
|
|
|
// TODO: better error for DECODE_FAILED?
|
2020-04-02 09:24:32 +02:00
|
|
|
if (err.code === 'DECODE_FAILED') {
|
|
|
|
res.statusCode = 400
|
|
|
|
res.end('Bad Request')
|
|
|
|
} else {
|
2020-06-02 01:12:45 +02:00
|
|
|
// Throw the error to crash the serverless function
|
|
|
|
throw err
|
2020-04-02 09:24:32 +02:00
|
|
|
}
|
2019-07-07 23:45:40 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
`
|
|
|
|
} else {
|
|
|
|
return `
|
2019-11-01 20:13:13 +01:00
|
|
|
import initServer from 'next-plugin-loader?middleware=on-init-server!'
|
|
|
|
import onError from 'next-plugin-loader?middleware=on-error-server!'
|
2020-05-12 21:58:21 +02:00
|
|
|
import 'next/dist/next-server/server/node-polyfill-fetch'
|
2020-06-02 01:12:45 +02:00
|
|
|
const {isResSent} = require('next/dist/next-server/lib/utils');
|
2020-05-12 21:58:21 +02:00
|
|
|
|
2020-05-26 21:01:57 +02:00
|
|
|
${envLoading}
|
2020-02-01 14:24:22 +01:00
|
|
|
${runtimeConfigImports}
|
|
|
|
${
|
2020-02-03 04:33:53 +01:00
|
|
|
// this needs to be called first so its available for any other imports
|
2020-02-01 14:24:22 +01:00
|
|
|
runtimeConfigSetter
|
|
|
|
}
|
2020-08-05 21:29:38 +02:00
|
|
|
const {parse: parseUrl, format: formatUrl} = require('url')
|
2020-02-03 04:33:53 +01:00
|
|
|
const {parse: parseQs} = require('querystring')
|
2020-07-28 12:19:28 +02:00
|
|
|
const { renderToHTML } = require('next/dist/next-server/server/render');
|
2020-02-22 10:26:39 +01:00
|
|
|
const { tryGetPreviewData } = require('next/dist/next-server/server/api-utils');
|
2020-09-14 18:48:04 +02:00
|
|
|
const { denormalizePagePath } = require('next/dist/next-server/server/denormalize-page-path')
|
2020-10-07 23:11:01 +02:00
|
|
|
const { setLazyProp, getCookieParser } = require('next/dist/next-server/server/api-utils')
|
2020-03-13 10:40:10 +01:00
|
|
|
const {sendPayload} = require('next/dist/next-server/server/send-payload');
|
2020-11-04 23:18:44 +01:00
|
|
|
const {getRedirectStatus} = require('next/dist/lib/load-custom-routes');
|
|
|
|
const {PERMANENT_REDIRECT_STATUS} = require('next/dist/next-server/lib/constants')
|
2020-02-03 04:33:53 +01:00
|
|
|
const buildManifest = require('${buildManifest}');
|
|
|
|
const reactLoadableManifest = require('${reactLoadableManifest}');
|
2020-10-14 11:55:42 +02:00
|
|
|
|
|
|
|
const appMod = require('${absoluteAppPath}')
|
|
|
|
let App = appMod.default || appMod.then && appMod.then(mod => mod.default);
|
2020-07-28 12:19:28 +02:00
|
|
|
|
2020-02-03 04:33:53 +01:00
|
|
|
${dynamicRouteImports}
|
|
|
|
${rewriteImports}
|
2020-02-01 14:24:22 +01:00
|
|
|
|
2020-10-14 11:55:42 +02:00
|
|
|
const compMod = require('${absolutePagePath}')
|
2019-12-23 22:20:17 +01:00
|
|
|
|
2020-10-14 11:55:42 +02:00
|
|
|
let Component = compMod.default || compMod.then && compMod.then(mod => mod.default)
|
2019-05-22 18:36:53 +02:00
|
|
|
export default Component
|
2020-10-14 11:55:42 +02:00
|
|
|
export let getStaticProps = compMod['getStaticProp' + 's'] || compMod.then && compMod.then(mod => mod['getStaticProp' + 's'])
|
|
|
|
export let getStaticPaths = compMod['getStaticPath' + 's'] || compMod.then && compMod.then(mod => mod['getStaticPath' + 's'])
|
|
|
|
export let getServerSideProps = compMod['getServerSideProp' + 's'] || compMod.then && compMod.then(mod => mod['getServerSideProp' + 's'])
|
2020-02-27 18:57:39 +01:00
|
|
|
|
|
|
|
// kept for detecting legacy exports
|
2020-10-14 11:55:42 +02:00
|
|
|
export const unstable_getStaticParams = compMod['unstable_getStaticParam' + 's'] || compMod.then && compMod.then(mod => mod['unstable_getStaticParam' + 's'])
|
|
|
|
export const unstable_getStaticProps = compMod['unstable_getStaticProp' + 's'] || compMod.then && compMod.then(mod => mod['unstable_getStaticProp' + 's'])
|
|
|
|
export const unstable_getStaticPaths = compMod['unstable_getStaticPath' + 's'] || compMod.then && compMod.then(mod => mod['unstable_getStaticPath' + 's'])
|
|
|
|
export const unstable_getServerProps = compMod['unstable_getServerProp' + 's'] || compMod.then && compMod.then(mod => mod['unstable_getServerProp' + 's'])
|
2019-11-28 05:23:32 +01:00
|
|
|
|
2019-12-23 22:20:17 +01:00
|
|
|
${dynamicRouteMatcher}
|
2020-08-05 21:29:38 +02:00
|
|
|
${defaultRouteRegex}
|
2019-12-23 22:20:17 +01:00
|
|
|
${handleRewrites}
|
|
|
|
|
2020-10-14 11:55:42 +02:00
|
|
|
export let config = compMod['confi' + 'g'] || (compMod.then && compMod.then(mod => mod['confi' + 'g'])) || {}
|
2019-05-22 18:36:53 +02:00
|
|
|
export const _app = App
|
2020-03-09 18:30:44 +01:00
|
|
|
export async function renderReqToHTML(req, res, renderMode, _renderOpts, _params) {
|
2020-10-14 11:55:42 +02:00
|
|
|
let Document
|
|
|
|
let Error
|
2020-10-27 16:11:51 +01:00
|
|
|
let notFoundMod
|
2020-10-14 11:55:42 +02:00
|
|
|
;[
|
|
|
|
getStaticProps,
|
|
|
|
getServerSideProps,
|
|
|
|
getStaticPaths,
|
|
|
|
Component,
|
|
|
|
App,
|
|
|
|
config,
|
|
|
|
{ default: Document },
|
2020-10-22 16:54:38 +02:00
|
|
|
{ default: Error },
|
2020-10-27 16:11:51 +01:00
|
|
|
${absolute404Path ? `notFoundMod, ` : ''}
|
2020-10-14 11:55:42 +02:00
|
|
|
] = await Promise.all([
|
|
|
|
getStaticProps,
|
|
|
|
getServerSideProps,
|
|
|
|
getStaticPaths,
|
|
|
|
Component,
|
|
|
|
App,
|
|
|
|
config,
|
|
|
|
require('${absoluteDocumentPath}'),
|
2020-10-22 16:54:38 +02:00
|
|
|
require('${absoluteErrorPath}'),
|
|
|
|
${absolute404Path ? `require("${absolute404Path}"),` : ''}
|
2020-10-14 11:55:42 +02:00
|
|
|
])
|
|
|
|
|
2020-03-09 18:30:44 +01:00
|
|
|
const fromExport = renderMode === 'export' || renderMode === true;
|
2020-10-07 23:11:01 +02:00
|
|
|
const nextStartMode = renderMode === 'passthrough'
|
2020-11-01 05:49:48 +01:00
|
|
|
let hasValidParams = true
|
|
|
|
|
|
|
|
${normalizeDynamicRouteParams}
|
2020-10-07 23:11:01 +02:00
|
|
|
|
|
|
|
setLazyProp({ req }, 'cookies', getCookieParser(req))
|
2020-06-11 16:06:06 +02:00
|
|
|
|
Serverless Next.js (#5927)
**This does not change existing behavior.**
building to serverless is completely opt-in.
- Implements `target: 'serverless'` in `next.config.js`
- Removes `next build --lambdas` (was only available on next@canary so far)
This implements the concept of build targets. Currently there will be 2 build targets:
- server (This is the target that already existed / the default, no changes here)
- serverless (New target aimed at compiling pages to serverless handlers)
The serverless target will output a single file per `page` in the `pages` directory:
- `pages/index.js` => `.next/serverless/index.js`
- `pages/about.js` => `.next/serverless/about.js`
So what is inside `.next/serverless/about.js`? All the code needed to render that specific page. It has the Node.js `http.Server` request handler function signature:
```ts
(req: http.IncomingMessage, res: http.ServerResponse) => void
```
So how do you use it? Generally you **don't** want to use the below example, but for illustration purposes it's shown how the handler is called using a plain `http.Server`:
```js
const http = require('http')
// Note that `.default` is needed because the exported module is an esmodule
const handler = require('./.next/serverless/about.js').default
const server = new http.Server((req, res) => handler(req, res))
server.listen(3000, () => console.log('Listening on http://localhost:3000'))
```
Generally you'll upload this handler function to an external service like [Now v2](https://zeit.co/now-2), the `@now/next` builder will be updated to reflect these changes. This means that it'll be no longer neccesary for `@now/next` to do some of the guesswork in creating smaller handler functions. As Next.js will output the smallest possible serverless handler function automatically.
The function has 0 dependencies so no node_modules are required to run it, and is generally very small. 45Kb zipped is the baseline, but I'm sure we can make it even smaller in the future.
One important thing to note is that the function won't try to load `next.config.js`, so `publicRuntimeConfig` / `serverRuntimeConfig` are not supported. Reasons are outlined here: #5846
So to summarize:
- every page becomes a serverless function
- the serverless function has 0 dependencies (they're all inlined)
- "just" uses the `req` and `res` coming from Node.js
- opt-in using `target: 'serverless'` in `next.config.js`
- Does not load next.config.js when executing the function
TODO:
- [x] Compile next/dynamic / `import()` into the function file, so that no extra files have to be uploaded.
- [x] Setting `assetPrefix` at build time for serverless target
- [x] Support custom /_app
- [x] Support custom /_document
- [x] Support custom /_error
- [x] Add `next.config.js` property for `target`
Need discussion:
- [ ] Since the serverless target won't support `publicRuntimeConfig` / `serverRuntimeConfig` as they're runtime values. I think we should support build-time env var replacement with webpack.DefinePlugin or similar.
- [ ] Serving static files with the correct cache-control, as there is no static file serving in the serverless target
2018-12-28 11:39:12 +01:00
|
|
|
const options = {
|
|
|
|
App,
|
|
|
|
Document,
|
|
|
|
buildManifest,
|
2020-02-27 18:57:39 +01:00
|
|
|
getStaticProps,
|
|
|
|
getServerSideProps,
|
|
|
|
getStaticPaths,
|
Serverless Next.js (#5927)
**This does not change existing behavior.**
building to serverless is completely opt-in.
- Implements `target: 'serverless'` in `next.config.js`
- Removes `next build --lambdas` (was only available on next@canary so far)
This implements the concept of build targets. Currently there will be 2 build targets:
- server (This is the target that already existed / the default, no changes here)
- serverless (New target aimed at compiling pages to serverless handlers)
The serverless target will output a single file per `page` in the `pages` directory:
- `pages/index.js` => `.next/serverless/index.js`
- `pages/about.js` => `.next/serverless/about.js`
So what is inside `.next/serverless/about.js`? All the code needed to render that specific page. It has the Node.js `http.Server` request handler function signature:
```ts
(req: http.IncomingMessage, res: http.ServerResponse) => void
```
So how do you use it? Generally you **don't** want to use the below example, but for illustration purposes it's shown how the handler is called using a plain `http.Server`:
```js
const http = require('http')
// Note that `.default` is needed because the exported module is an esmodule
const handler = require('./.next/serverless/about.js').default
const server = new http.Server((req, res) => handler(req, res))
server.listen(3000, () => console.log('Listening on http://localhost:3000'))
```
Generally you'll upload this handler function to an external service like [Now v2](https://zeit.co/now-2), the `@now/next` builder will be updated to reflect these changes. This means that it'll be no longer neccesary for `@now/next` to do some of the guesswork in creating smaller handler functions. As Next.js will output the smallest possible serverless handler function automatically.
The function has 0 dependencies so no node_modules are required to run it, and is generally very small. 45Kb zipped is the baseline, but I'm sure we can make it even smaller in the future.
One important thing to note is that the function won't try to load `next.config.js`, so `publicRuntimeConfig` / `serverRuntimeConfig` are not supported. Reasons are outlined here: #5846
So to summarize:
- every page becomes a serverless function
- the serverless function has 0 dependencies (they're all inlined)
- "just" uses the `req` and `res` coming from Node.js
- opt-in using `target: 'serverless'` in `next.config.js`
- Does not load next.config.js when executing the function
TODO:
- [x] Compile next/dynamic / `import()` into the function file, so that no extra files have to be uploaded.
- [x] Setting `assetPrefix` at build time for serverless target
- [x] Support custom /_app
- [x] Support custom /_document
- [x] Support custom /_error
- [x] Add `next.config.js` property for `target`
Need discussion:
- [ ] Since the serverless target won't support `publicRuntimeConfig` / `serverRuntimeConfig` as they're runtime values. I think we should support build-time env var replacement with webpack.DefinePlugin or similar.
- [ ] Serving static files with the correct cache-control, as there is no static file serving in the serverless target
2018-12-28 11:39:12 +01:00
|
|
|
reactLoadableManifest,
|
2019-05-29 02:32:18 +02:00
|
|
|
canonicalBase: "${canonicalBase}",
|
2019-08-20 18:38:14 +02:00
|
|
|
buildId: "${buildId}",
|
2019-04-03 23:42:12 +02:00
|
|
|
assetPrefix: "${assetPrefix}",
|
2020-02-01 14:24:22 +01:00
|
|
|
runtimeConfig: runtimeConfig.publicRuntimeConfig || {},
|
2020-02-12 02:16:42 +01:00
|
|
|
previewProps: ${encodedPreviewProps},
|
2020-03-26 13:32:41 +01:00
|
|
|
env: process.env,
|
2020-04-14 09:50:39 +02:00
|
|
|
basePath: "${basePath}",
|
2019-12-14 07:31:48 +01:00
|
|
|
..._renderOpts
|
2019-09-24 10:50:04 +02:00
|
|
|
}
|
2020-01-15 02:22:15 +01:00
|
|
|
let _nextData = false
|
2020-04-02 09:24:32 +02:00
|
|
|
let parsedUrl
|
2019-09-24 10:50:04 +02:00
|
|
|
|
2020-04-02 09:24:32 +02:00
|
|
|
try {
|
2020-06-23 07:31:32 +02:00
|
|
|
// 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}']
|
2020-09-15 21:19:07 +02:00
|
|
|
let parsedUrl = parseUrl(req.url, true)
|
|
|
|
let routeNoAssetPath = parsedUrl.pathname${
|
|
|
|
basePath ? `.replace(new RegExp('^${basePath}'), '') || '/'` : ''
|
|
|
|
}
|
|
|
|
const origQuery = Object.assign({}, parsedUrl.query)
|
|
|
|
|
|
|
|
parsedUrl = handleRewrites(parsedUrl)
|
2020-01-25 05:34:00 +01:00
|
|
|
|
2020-07-12 21:03:49 +02:00
|
|
|
${handleBasePath}
|
|
|
|
|
2020-10-16 01:00:08 +02:00
|
|
|
// remove ?amp=1 from request URL if rendering for export
|
|
|
|
if (fromExport && parsedUrl.query.amp) {
|
|
|
|
const queryNoAmp = Object.assign({}, origQuery)
|
|
|
|
delete queryNoAmp.amp
|
|
|
|
|
|
|
|
req.url = formatUrl({
|
|
|
|
...parsedUrl,
|
|
|
|
search: undefined,
|
|
|
|
query: queryNoAmp
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2020-04-02 09:24:32 +02:00
|
|
|
if (parsedUrl.pathname.match(/_next\\/data/)) {
|
2020-07-14 20:58:02 +02:00
|
|
|
const {
|
2020-10-16 11:27:34 +02:00
|
|
|
default: getRouteNoAssetPath,
|
2020-07-14 20:58:02 +02:00
|
|
|
} = require('next/dist/next-server/lib/router/utils/get-route-from-asset-path');
|
|
|
|
_nextData = true;
|
2020-10-16 11:27:34 +02:00
|
|
|
parsedUrl.pathname = getRouteNoAssetPath(
|
2020-07-14 20:58:02 +02:00
|
|
|
parsedUrl.pathname.replace(
|
|
|
|
new RegExp('/_next/data/${escapedBuildId}/'),
|
|
|
|
'/'
|
|
|
|
),
|
|
|
|
'.json'
|
|
|
|
);
|
2020-09-15 21:19:07 +02:00
|
|
|
routeNoAssetPath = parsedUrl.pathname
|
2020-04-02 09:24:32 +02:00
|
|
|
}
|
|
|
|
|
2020-10-07 23:11:01 +02:00
|
|
|
${handleLocale}
|
|
|
|
|
2020-04-02 09:24:32 +02:00
|
|
|
const renderOpts = Object.assign(
|
|
|
|
{
|
|
|
|
Component,
|
|
|
|
pageConfig: config,
|
2020-05-26 19:50:06 +02:00
|
|
|
nextExport: fromExport,
|
|
|
|
isDataReq: _nextData,
|
2020-10-07 23:11:01 +02:00
|
|
|
locale: detectedLocale,
|
2020-10-10 12:22:45 +02:00
|
|
|
locales,
|
2020-10-15 10:58:26 +02:00
|
|
|
defaultLocale: i18n.defaultLocale,
|
2020-04-02 09:24:32 +02:00
|
|
|
},
|
|
|
|
options,
|
|
|
|
)
|
|
|
|
|
|
|
|
${
|
|
|
|
page === '/_error'
|
|
|
|
? `
|
|
|
|
if (!res.statusCode) {
|
|
|
|
res.statusCode = 404
|
|
|
|
}
|
|
|
|
`
|
|
|
|
: ''
|
|
|
|
}
|
2019-12-23 22:20:17 +01:00
|
|
|
|
2019-05-27 20:20:33 +02:00
|
|
|
${
|
2019-12-23 22:20:17 +01:00
|
|
|
pageIsDynamicRoute
|
2020-06-23 07:31:32 +02:00
|
|
|
? `
|
|
|
|
const params = (
|
2020-08-23 14:35:30 +02:00
|
|
|
fromExport
|
2020-06-23 07:31:32 +02:00
|
|
|
) ? {}
|
2020-08-21 20:13:24 +02:00
|
|
|
: normalizeDynamicRouteParams(
|
|
|
|
trustQuery
|
|
|
|
? parsedUrl.query
|
|
|
|
: dynamicRouteMatcher(parsedUrl.pathname)
|
|
|
|
)
|
2020-06-23 07:31:32 +02:00
|
|
|
`
|
2019-05-27 20:20:33 +02:00
|
|
|
: `const params = {};`
|
|
|
|
}
|
2020-11-01 05:49:48 +01:00
|
|
|
|
2019-10-15 20:44:50 +02:00
|
|
|
${
|
2019-10-16 20:54:07 +02:00
|
|
|
// Temporary work around: `x-now-route-matches` is a platform header
|
2019-10-15 20:44:50 +02:00
|
|
|
// _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).
|
2019-12-23 22:20:17 +01:00
|
|
|
pageIsDynamicRoute
|
2020-11-01 05:49:48 +01:00
|
|
|
? `const nowParams = !hasValidParams && req.headers && req.headers["x-now-route-matches"]
|
2019-10-15 22:30:10 +02:00
|
|
|
? getRouteMatcher(
|
|
|
|
(function() {
|
2020-10-16 11:27:34 +02:00
|
|
|
const { re, groups, routeKeys } = getRouteRegex("${page}");
|
2019-10-15 22:30:10 +02:00
|
|
|
return {
|
|
|
|
re: {
|
|
|
|
// Simulate a RegExp match from the \`req.url\` input
|
|
|
|
exec: str => {
|
|
|
|
const obj = parseQs(str);
|
2020-10-16 11:27:34 +02:00
|
|
|
|
|
|
|
// favor named matches if available
|
|
|
|
const routeKeyNames = Object.keys(routeKeys)
|
|
|
|
|
|
|
|
if (routeKeyNames.every(name => obj[name])) {
|
|
|
|
return routeKeyNames.reduce((prev, keyName) => {
|
|
|
|
const paramName = routeKeys[keyName]
|
|
|
|
prev[groups[paramName].pos] = obj[keyName]
|
|
|
|
return prev
|
|
|
|
}, {})
|
|
|
|
}
|
|
|
|
|
2019-10-15 22:30:10 +02:00
|
|
|
return Object.keys(obj).reduce(
|
|
|
|
(prev, key) =>
|
|
|
|
Object.assign(prev, {
|
2020-02-24 19:06:11 +01:00
|
|
|
[key]: obj[key]
|
2019-10-15 22:30:10 +02:00
|
|
|
}),
|
|
|
|
{}
|
|
|
|
);
|
|
|
|
}
|
|
|
|
},
|
|
|
|
groups
|
|
|
|
};
|
|
|
|
})()
|
2019-10-16 20:54:07 +02:00
|
|
|
)(req.headers["x-now-route-matches"])
|
2019-10-15 22:30:10 +02:00
|
|
|
: null;
|
|
|
|
`
|
2019-10-15 20:44:50 +02:00
|
|
|
: `const nowParams = null;`
|
|
|
|
}
|
2020-08-21 20:13:24 +02:00
|
|
|
|
2020-01-27 23:50:59 +01:00
|
|
|
// 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
|
|
|
|
|
2020-08-05 21:29:38 +02:00
|
|
|
// make sure to normalize req.url on Vercel to strip dynamic params
|
|
|
|
// from the query which are added during routing
|
2020-08-07 09:01:34 +02:00
|
|
|
${
|
|
|
|
pageIsDynamicRoute
|
|
|
|
? `
|
|
|
|
if (trustQuery) {
|
|
|
|
const _parsedUrl = parseUrl(req.url, true)
|
|
|
|
delete _parsedUrl.search
|
2020-08-05 21:29:38 +02:00
|
|
|
|
2020-08-07 09:01:34 +02:00
|
|
|
for (const param of Object.keys(defaultRouteRegex.groups)) {
|
|
|
|
delete _parsedUrl.query[param]
|
|
|
|
}
|
|
|
|
req.url = formatUrl(_parsedUrl)
|
2020-08-05 21:29:38 +02:00
|
|
|
}
|
2020-08-07 09:01:34 +02:00
|
|
|
`
|
|
|
|
: ''
|
2020-08-05 21:29:38 +02:00
|
|
|
}
|
|
|
|
|
2020-09-14 18:48:04 +02:00
|
|
|
// normalize request URL/asPath for fallback/revalidate pages since the
|
|
|
|
// proxy sets the request URL to the output's path for fallback pages
|
2020-08-19 17:23:02 +02:00
|
|
|
${
|
|
|
|
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)
|
|
|
|
}
|
|
|
|
}
|
2020-09-14 18:48:04 +02:00
|
|
|
parsedUrl.pathname = _parsedUrl.pathname
|
2020-08-19 17:23:02 +02:00
|
|
|
req.url = formatUrl(_parsedUrl)
|
|
|
|
}
|
|
|
|
`
|
|
|
|
: ``
|
|
|
|
}
|
|
|
|
|
2020-09-14 18:48:04 +02:00
|
|
|
// make sure to normalize asPath for revalidate and _next/data requests
|
|
|
|
// since the asPath should match what is shown on the client
|
|
|
|
if (
|
|
|
|
!fromExport &&
|
|
|
|
(getStaticProps || getServerSideProps)
|
|
|
|
) {
|
|
|
|
${
|
|
|
|
pageIsDynamicRoute
|
|
|
|
? `
|
|
|
|
// don't include dynamic route params in query while normalizing
|
|
|
|
// asPath
|
|
|
|
if (trustQuery) {
|
|
|
|
delete parsedUrl.search
|
|
|
|
|
|
|
|
for (const param of Object.keys(defaultRouteRegex.groups)) {
|
2020-09-14 23:01:04 +02:00
|
|
|
delete origQuery[param]
|
2020-09-14 18:48:04 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
`
|
|
|
|
: ``
|
|
|
|
}
|
|
|
|
|
|
|
|
parsedUrl.pathname = denormalizePagePath(parsedUrl.pathname)
|
2020-09-14 23:01:04 +02:00
|
|
|
renderOpts.resolvedUrl = formatUrl({
|
2020-09-14 18:48:04 +02:00
|
|
|
...parsedUrl,
|
2020-09-14 23:01:04 +02:00
|
|
|
query: origQuery
|
2020-09-14 18:48:04 +02:00
|
|
|
})
|
2020-09-15 21:19:07 +02:00
|
|
|
|
|
|
|
// For getServerSideProps we need to ensure we use the original URL
|
|
|
|
// and not the resolved URL to prevent a hydration mismatch on asPath
|
|
|
|
renderOpts.resolvedAsPath = getServerSideProps
|
|
|
|
? formatUrl({
|
|
|
|
...parsedUrl,
|
|
|
|
pathname: routeNoAssetPath,
|
|
|
|
query: origQuery,
|
|
|
|
})
|
|
|
|
: renderOpts.resolvedUrl
|
2020-09-14 18:48:04 +02:00
|
|
|
}
|
|
|
|
|
2020-02-07 14:09:06 +01:00
|
|
|
const isFallback = parsedUrl.query.__nextFallback
|
|
|
|
|
2020-02-22 10:26:39 +01:00
|
|
|
const previewData = tryGetPreviewData(req, res, options.previewProps)
|
|
|
|
const isPreviewMode = previewData !== false
|
2020-07-28 12:19:28 +02:00
|
|
|
if (process.env.__NEXT_OPTIMIZE_FONTS) {
|
|
|
|
renderOpts.optimizeFonts = true
|
2020-08-04 09:54:08 +02:00
|
|
|
/**
|
|
|
|
* __webpack_require__.__NEXT_FONT_MANIFEST__ is added by
|
|
|
|
* font-stylesheet-gathering-plugin
|
|
|
|
*/
|
|
|
|
renderOpts.fontManifest = __webpack_require__.__NEXT_FONT_MANIFEST__;
|
2020-07-28 12:19:28 +02:00
|
|
|
process.env['__NEXT_OPTIMIZE_FONT'+'S'] = true
|
|
|
|
}
|
2020-03-20 09:46:52 +01:00
|
|
|
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)
|
2019-10-16 23:24:28 +02:00
|
|
|
|
2020-03-13 10:40:10 +01:00
|
|
|
if (!renderMode) {
|
|
|
|
if (_nextData || getStaticProps || getServerSideProps) {
|
2020-10-27 06:42:12 +01:00
|
|
|
if (renderOpts.isNotFound) {
|
2020-10-22 16:54:38 +02:00
|
|
|
res.statusCode = 404
|
|
|
|
|
|
|
|
const NotFoundComponent = ${
|
2020-10-27 16:11:51 +01:00
|
|
|
absolute404Path ? 'notFoundMod.default' : 'Error'
|
2020-10-22 16:54:38 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
const errPathname = "${absolute404Path ? '/404' : '/_error'}"
|
|
|
|
|
|
|
|
const result = await renderToHTML(req, res, errPathname, parsedUrl.query, Object.assign({}, options, {
|
2020-10-27 16:11:51 +01:00
|
|
|
getStaticProps: ${
|
|
|
|
absolute404Path ? `notFoundMod.getStaticProps` : 'undefined'
|
|
|
|
},
|
2020-10-22 16:54:38 +02:00
|
|
|
getStaticPaths: undefined,
|
|
|
|
getServerSideProps: undefined,
|
|
|
|
Component: NotFoundComponent,
|
2020-10-30 02:42:28 +01:00
|
|
|
err: undefined,
|
|
|
|
locale: detectedLocale,
|
|
|
|
locales,
|
|
|
|
defaultLocale: i18n.defaultLocale,
|
2020-10-22 16:54:38 +02:00
|
|
|
}))
|
|
|
|
|
|
|
|
sendPayload(req, res, result, 'html', ${
|
|
|
|
generateEtags === 'true' ? true : false
|
|
|
|
}, {
|
|
|
|
private: isPreviewMode,
|
|
|
|
stateful: !!getServerSideProps,
|
|
|
|
revalidate: renderOpts.revalidate,
|
|
|
|
})
|
|
|
|
return null
|
2020-11-04 23:18:44 +01:00
|
|
|
} else if (renderOpts.isRedirect && !_nextData) {
|
|
|
|
const redirect = {
|
|
|
|
destination: renderOpts.pageData.pageProps.__N_REDIRECT,
|
|
|
|
statusCode: renderOpts.pageData.pageProps.__N_REDIRECT_STATUS
|
|
|
|
}
|
|
|
|
const statusCode = getRedirectStatus(redirect)
|
|
|
|
|
|
|
|
if (statusCode === PERMANENT_REDIRECT_STATUS) {
|
|
|
|
res.setHeader('Refresh', \`0;url=\${redirect.destination}\`)
|
|
|
|
}
|
|
|
|
|
|
|
|
res.statusCode = statusCode
|
|
|
|
res.setHeader('Location', redirect.destination)
|
|
|
|
res.end()
|
|
|
|
return null
|
2020-10-22 16:54:38 +02:00
|
|
|
} else {
|
|
|
|
sendPayload(req, res, _nextData ? JSON.stringify(renderOpts.pageData) : result, _nextData ? 'json' : 'html', ${
|
|
|
|
generateEtags === 'true' ? true : false
|
|
|
|
}, {
|
|
|
|
private: isPreviewMode,
|
|
|
|
stateful: !!getServerSideProps,
|
|
|
|
revalidate: renderOpts.revalidate,
|
|
|
|
})
|
|
|
|
return null
|
|
|
|
}
|
2020-03-13 10:40:10 +01:00
|
|
|
}
|
2020-02-22 10:26:39 +01:00
|
|
|
} else if (isPreviewMode) {
|
|
|
|
res.setHeader(
|
|
|
|
'Cache-Control',
|
|
|
|
'private, no-cache, no-store, max-age=0, must-revalidate'
|
|
|
|
)
|
2019-10-16 23:24:28 +02:00
|
|
|
}
|
2019-05-22 18:36:53 +02:00
|
|
|
|
2020-03-09 18:30:44 +01:00
|
|
|
if (renderMode) return { html: result, renderOpts }
|
Serverless Next.js (#5927)
**This does not change existing behavior.**
building to serverless is completely opt-in.
- Implements `target: 'serverless'` in `next.config.js`
- Removes `next build --lambdas` (was only available on next@canary so far)
This implements the concept of build targets. Currently there will be 2 build targets:
- server (This is the target that already existed / the default, no changes here)
- serverless (New target aimed at compiling pages to serverless handlers)
The serverless target will output a single file per `page` in the `pages` directory:
- `pages/index.js` => `.next/serverless/index.js`
- `pages/about.js` => `.next/serverless/about.js`
So what is inside `.next/serverless/about.js`? All the code needed to render that specific page. It has the Node.js `http.Server` request handler function signature:
```ts
(req: http.IncomingMessage, res: http.ServerResponse) => void
```
So how do you use it? Generally you **don't** want to use the below example, but for illustration purposes it's shown how the handler is called using a plain `http.Server`:
```js
const http = require('http')
// Note that `.default` is needed because the exported module is an esmodule
const handler = require('./.next/serverless/about.js').default
const server = new http.Server((req, res) => handler(req, res))
server.listen(3000, () => console.log('Listening on http://localhost:3000'))
```
Generally you'll upload this handler function to an external service like [Now v2](https://zeit.co/now-2), the `@now/next` builder will be updated to reflect these changes. This means that it'll be no longer neccesary for `@now/next` to do some of the guesswork in creating smaller handler functions. As Next.js will output the smallest possible serverless handler function automatically.
The function has 0 dependencies so no node_modules are required to run it, and is generally very small. 45Kb zipped is the baseline, but I'm sure we can make it even smaller in the future.
One important thing to note is that the function won't try to load `next.config.js`, so `publicRuntimeConfig` / `serverRuntimeConfig` are not supported. Reasons are outlined here: #5846
So to summarize:
- every page becomes a serverless function
- the serverless function has 0 dependencies (they're all inlined)
- "just" uses the `req` and `res` coming from Node.js
- opt-in using `target: 'serverless'` in `next.config.js`
- Does not load next.config.js when executing the function
TODO:
- [x] Compile next/dynamic / `import()` into the function file, so that no extra files have to be uploaded.
- [x] Setting `assetPrefix` at build time for serverless target
- [x] Support custom /_app
- [x] Support custom /_document
- [x] Support custom /_error
- [x] Add `next.config.js` property for `target`
Need discussion:
- [ ] Since the serverless target won't support `publicRuntimeConfig` / `serverRuntimeConfig` as they're runtime values. I think we should support build-time env var replacement with webpack.DefinePlugin or similar.
- [ ] Serving static files with the correct cache-control, as there is no static file serving in the serverless target
2018-12-28 11:39:12 +01:00
|
|
|
return result
|
|
|
|
} catch (err) {
|
2020-04-02 09:24:32 +02:00
|
|
|
if (!parsedUrl) {
|
2020-08-05 21:29:38 +02:00
|
|
|
parsedUrl = parseUrl(req.url, true)
|
2020-04-02 09:24:32 +02:00
|
|
|
}
|
|
|
|
|
Serverless Next.js (#5927)
**This does not change existing behavior.**
building to serverless is completely opt-in.
- Implements `target: 'serverless'` in `next.config.js`
- Removes `next build --lambdas` (was only available on next@canary so far)
This implements the concept of build targets. Currently there will be 2 build targets:
- server (This is the target that already existed / the default, no changes here)
- serverless (New target aimed at compiling pages to serverless handlers)
The serverless target will output a single file per `page` in the `pages` directory:
- `pages/index.js` => `.next/serverless/index.js`
- `pages/about.js` => `.next/serverless/about.js`
So what is inside `.next/serverless/about.js`? All the code needed to render that specific page. It has the Node.js `http.Server` request handler function signature:
```ts
(req: http.IncomingMessage, res: http.ServerResponse) => void
```
So how do you use it? Generally you **don't** want to use the below example, but for illustration purposes it's shown how the handler is called using a plain `http.Server`:
```js
const http = require('http')
// Note that `.default` is needed because the exported module is an esmodule
const handler = require('./.next/serverless/about.js').default
const server = new http.Server((req, res) => handler(req, res))
server.listen(3000, () => console.log('Listening on http://localhost:3000'))
```
Generally you'll upload this handler function to an external service like [Now v2](https://zeit.co/now-2), the `@now/next` builder will be updated to reflect these changes. This means that it'll be no longer neccesary for `@now/next` to do some of the guesswork in creating smaller handler functions. As Next.js will output the smallest possible serverless handler function automatically.
The function has 0 dependencies so no node_modules are required to run it, and is generally very small. 45Kb zipped is the baseline, but I'm sure we can make it even smaller in the future.
One important thing to note is that the function won't try to load `next.config.js`, so `publicRuntimeConfig` / `serverRuntimeConfig` are not supported. Reasons are outlined here: #5846
So to summarize:
- every page becomes a serverless function
- the serverless function has 0 dependencies (they're all inlined)
- "just" uses the `req` and `res` coming from Node.js
- opt-in using `target: 'serverless'` in `next.config.js`
- Does not load next.config.js when executing the function
TODO:
- [x] Compile next/dynamic / `import()` into the function file, so that no extra files have to be uploaded.
- [x] Setting `assetPrefix` at build time for serverless target
- [x] Support custom /_app
- [x] Support custom /_document
- [x] Support custom /_error
- [x] Add `next.config.js` property for `target`
Need discussion:
- [ ] Since the serverless target won't support `publicRuntimeConfig` / `serverRuntimeConfig` as they're runtime values. I think we should support build-time env var replacement with webpack.DefinePlugin or similar.
- [ ] Serving static files with the correct cache-control, as there is no static file serving in the serverless target
2018-12-28 11:39:12 +01:00
|
|
|
if (err.code === 'ENOENT') {
|
|
|
|
res.statusCode = 404
|
2020-04-02 09:24:32 +02:00
|
|
|
} else if (err.code === 'DECODE_FAILED') {
|
2020-06-02 01:12:45 +02:00
|
|
|
// TODO: better error?
|
2020-04-02 09:24:32 +02:00
|
|
|
res.statusCode = 400
|
Serverless Next.js (#5927)
**This does not change existing behavior.**
building to serverless is completely opt-in.
- Implements `target: 'serverless'` in `next.config.js`
- Removes `next build --lambdas` (was only available on next@canary so far)
This implements the concept of build targets. Currently there will be 2 build targets:
- server (This is the target that already existed / the default, no changes here)
- serverless (New target aimed at compiling pages to serverless handlers)
The serverless target will output a single file per `page` in the `pages` directory:
- `pages/index.js` => `.next/serverless/index.js`
- `pages/about.js` => `.next/serverless/about.js`
So what is inside `.next/serverless/about.js`? All the code needed to render that specific page. It has the Node.js `http.Server` request handler function signature:
```ts
(req: http.IncomingMessage, res: http.ServerResponse) => void
```
So how do you use it? Generally you **don't** want to use the below example, but for illustration purposes it's shown how the handler is called using a plain `http.Server`:
```js
const http = require('http')
// Note that `.default` is needed because the exported module is an esmodule
const handler = require('./.next/serverless/about.js').default
const server = new http.Server((req, res) => handler(req, res))
server.listen(3000, () => console.log('Listening on http://localhost:3000'))
```
Generally you'll upload this handler function to an external service like [Now v2](https://zeit.co/now-2), the `@now/next` builder will be updated to reflect these changes. This means that it'll be no longer neccesary for `@now/next` to do some of the guesswork in creating smaller handler functions. As Next.js will output the smallest possible serverless handler function automatically.
The function has 0 dependencies so no node_modules are required to run it, and is generally very small. 45Kb zipped is the baseline, but I'm sure we can make it even smaller in the future.
One important thing to note is that the function won't try to load `next.config.js`, so `publicRuntimeConfig` / `serverRuntimeConfig` are not supported. Reasons are outlined here: #5846
So to summarize:
- every page becomes a serverless function
- the serverless function has 0 dependencies (they're all inlined)
- "just" uses the `req` and `res` coming from Node.js
- opt-in using `target: 'serverless'` in `next.config.js`
- Does not load next.config.js when executing the function
TODO:
- [x] Compile next/dynamic / `import()` into the function file, so that no extra files have to be uploaded.
- [x] Setting `assetPrefix` at build time for serverless target
- [x] Support custom /_app
- [x] Support custom /_document
- [x] Support custom /_error
- [x] Add `next.config.js` property for `target`
Need discussion:
- [ ] Since the serverless target won't support `publicRuntimeConfig` / `serverRuntimeConfig` as they're runtime values. I think we should support build-time env var replacement with webpack.DefinePlugin or similar.
- [ ] Serving static files with the correct cache-control, as there is no static file serving in the serverless target
2018-12-28 11:39:12 +01:00
|
|
|
} else {
|
2020-06-02 01:12:45 +02:00
|
|
|
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
|
Serverless Next.js (#5927)
**This does not change existing behavior.**
building to serverless is completely opt-in.
- Implements `target: 'serverless'` in `next.config.js`
- Removes `next build --lambdas` (was only available on next@canary so far)
This implements the concept of build targets. Currently there will be 2 build targets:
- server (This is the target that already existed / the default, no changes here)
- serverless (New target aimed at compiling pages to serverless handlers)
The serverless target will output a single file per `page` in the `pages` directory:
- `pages/index.js` => `.next/serverless/index.js`
- `pages/about.js` => `.next/serverless/about.js`
So what is inside `.next/serverless/about.js`? All the code needed to render that specific page. It has the Node.js `http.Server` request handler function signature:
```ts
(req: http.IncomingMessage, res: http.ServerResponse) => void
```
So how do you use it? Generally you **don't** want to use the below example, but for illustration purposes it's shown how the handler is called using a plain `http.Server`:
```js
const http = require('http')
// Note that `.default` is needed because the exported module is an esmodule
const handler = require('./.next/serverless/about.js').default
const server = new http.Server((req, res) => handler(req, res))
server.listen(3000, () => console.log('Listening on http://localhost:3000'))
```
Generally you'll upload this handler function to an external service like [Now v2](https://zeit.co/now-2), the `@now/next` builder will be updated to reflect these changes. This means that it'll be no longer neccesary for `@now/next` to do some of the guesswork in creating smaller handler functions. As Next.js will output the smallest possible serverless handler function automatically.
The function has 0 dependencies so no node_modules are required to run it, and is generally very small. 45Kb zipped is the baseline, but I'm sure we can make it even smaller in the future.
One important thing to note is that the function won't try to load `next.config.js`, so `publicRuntimeConfig` / `serverRuntimeConfig` are not supported. Reasons are outlined here: #5846
So to summarize:
- every page becomes a serverless function
- the serverless function has 0 dependencies (they're all inlined)
- "just" uses the `req` and `res` coming from Node.js
- opt-in using `target: 'serverless'` in `next.config.js`
- Does not load next.config.js when executing the function
TODO:
- [x] Compile next/dynamic / `import()` into the function file, so that no extra files have to be uploaded.
- [x] Setting `assetPrefix` at build time for serverless target
- [x] Support custom /_app
- [x] Support custom /_document
- [x] Support custom /_error
- [x] Add `next.config.js` property for `target`
Need discussion:
- [ ] Since the serverless target won't support `publicRuntimeConfig` / `serverRuntimeConfig` as they're runtime values. I think we should support build-time env var replacement with webpack.DefinePlugin or similar.
- [ ] Serving static files with the correct cache-control, as there is no static file serving in the serverless target
2018-12-28 11:39:12 +01:00
|
|
|
}
|
2020-04-02 09:24:32 +02:00
|
|
|
|
|
|
|
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
|
Serverless Next.js (#5927)
**This does not change existing behavior.**
building to serverless is completely opt-in.
- Implements `target: 'serverless'` in `next.config.js`
- Removes `next build --lambdas` (was only available on next@canary so far)
This implements the concept of build targets. Currently there will be 2 build targets:
- server (This is the target that already existed / the default, no changes here)
- serverless (New target aimed at compiling pages to serverless handlers)
The serverless target will output a single file per `page` in the `pages` directory:
- `pages/index.js` => `.next/serverless/index.js`
- `pages/about.js` => `.next/serverless/about.js`
So what is inside `.next/serverless/about.js`? All the code needed to render that specific page. It has the Node.js `http.Server` request handler function signature:
```ts
(req: http.IncomingMessage, res: http.ServerResponse) => void
```
So how do you use it? Generally you **don't** want to use the below example, but for illustration purposes it's shown how the handler is called using a plain `http.Server`:
```js
const http = require('http')
// Note that `.default` is needed because the exported module is an esmodule
const handler = require('./.next/serverless/about.js').default
const server = new http.Server((req, res) => handler(req, res))
server.listen(3000, () => console.log('Listening on http://localhost:3000'))
```
Generally you'll upload this handler function to an external service like [Now v2](https://zeit.co/now-2), the `@now/next` builder will be updated to reflect these changes. This means that it'll be no longer neccesary for `@now/next` to do some of the guesswork in creating smaller handler functions. As Next.js will output the smallest possible serverless handler function automatically.
The function has 0 dependencies so no node_modules are required to run it, and is generally very small. 45Kb zipped is the baseline, but I'm sure we can make it even smaller in the future.
One important thing to note is that the function won't try to load `next.config.js`, so `publicRuntimeConfig` / `serverRuntimeConfig` are not supported. Reasons are outlined here: #5846
So to summarize:
- every page becomes a serverless function
- the serverless function has 0 dependencies (they're all inlined)
- "just" uses the `req` and `res` coming from Node.js
- opt-in using `target: 'serverless'` in `next.config.js`
- Does not load next.config.js when executing the function
TODO:
- [x] Compile next/dynamic / `import()` into the function file, so that no extra files have to be uploaded.
- [x] Setting `assetPrefix` at build time for serverless target
- [x] Support custom /_app
- [x] Support custom /_document
- [x] Support custom /_error
- [x] Add `next.config.js` property for `target`
Need discussion:
- [ ] Since the serverless target won't support `publicRuntimeConfig` / `serverRuntimeConfig` as they're runtime values. I think we should support build-time env var replacement with webpack.DefinePlugin or similar.
- [ ] Serving static files with the correct cache-control, as there is no static file serving in the serverless target
2018-12-28 11:39:12 +01:00
|
|
|
}
|
|
|
|
}
|
2019-01-02 14:59:28 +01:00
|
|
|
export async function render (req, res) {
|
Serverless Next.js (#5927)
**This does not change existing behavior.**
building to serverless is completely opt-in.
- Implements `target: 'serverless'` in `next.config.js`
- Removes `next build --lambdas` (was only available on next@canary so far)
This implements the concept of build targets. Currently there will be 2 build targets:
- server (This is the target that already existed / the default, no changes here)
- serverless (New target aimed at compiling pages to serverless handlers)
The serverless target will output a single file per `page` in the `pages` directory:
- `pages/index.js` => `.next/serverless/index.js`
- `pages/about.js` => `.next/serverless/about.js`
So what is inside `.next/serverless/about.js`? All the code needed to render that specific page. It has the Node.js `http.Server` request handler function signature:
```ts
(req: http.IncomingMessage, res: http.ServerResponse) => void
```
So how do you use it? Generally you **don't** want to use the below example, but for illustration purposes it's shown how the handler is called using a plain `http.Server`:
```js
const http = require('http')
// Note that `.default` is needed because the exported module is an esmodule
const handler = require('./.next/serverless/about.js').default
const server = new http.Server((req, res) => handler(req, res))
server.listen(3000, () => console.log('Listening on http://localhost:3000'))
```
Generally you'll upload this handler function to an external service like [Now v2](https://zeit.co/now-2), the `@now/next` builder will be updated to reflect these changes. This means that it'll be no longer neccesary for `@now/next` to do some of the guesswork in creating smaller handler functions. As Next.js will output the smallest possible serverless handler function automatically.
The function has 0 dependencies so no node_modules are required to run it, and is generally very small. 45Kb zipped is the baseline, but I'm sure we can make it even smaller in the future.
One important thing to note is that the function won't try to load `next.config.js`, so `publicRuntimeConfig` / `serverRuntimeConfig` are not supported. Reasons are outlined here: #5846
So to summarize:
- every page becomes a serverless function
- the serverless function has 0 dependencies (they're all inlined)
- "just" uses the `req` and `res` coming from Node.js
- opt-in using `target: 'serverless'` in `next.config.js`
- Does not load next.config.js when executing the function
TODO:
- [x] Compile next/dynamic / `import()` into the function file, so that no extra files have to be uploaded.
- [x] Setting `assetPrefix` at build time for serverless target
- [x] Support custom /_app
- [x] Support custom /_document
- [x] Support custom /_error
- [x] Add `next.config.js` property for `target`
Need discussion:
- [ ] Since the serverless target won't support `publicRuntimeConfig` / `serverRuntimeConfig` as they're runtime values. I think we should support build-time env var replacement with webpack.DefinePlugin or similar.
- [ ] Serving static files with the correct cache-control, as there is no static file serving in the serverless target
2018-12-28 11:39:12 +01:00
|
|
|
try {
|
2019-11-01 20:13:13 +01:00
|
|
|
await initServer()
|
2019-01-02 14:59:28 +01:00
|
|
|
const html = await renderReqToHTML(req, res)
|
2019-10-16 23:24:28 +02:00
|
|
|
if (html) {
|
2020-07-27 22:19:30 +02:00
|
|
|
sendPayload(req, res, html, 'html', {generateEtags: ${JSON.stringify(
|
|
|
|
generateEtags === 'true'
|
|
|
|
)}, poweredByHeader: ${JSON.stringify(poweredByHeader === 'true')}})
|
2019-10-16 23:24:28 +02:00
|
|
|
}
|
Serverless Next.js (#5927)
**This does not change existing behavior.**
building to serverless is completely opt-in.
- Implements `target: 'serverless'` in `next.config.js`
- Removes `next build --lambdas` (was only available on next@canary so far)
This implements the concept of build targets. Currently there will be 2 build targets:
- server (This is the target that already existed / the default, no changes here)
- serverless (New target aimed at compiling pages to serverless handlers)
The serverless target will output a single file per `page` in the `pages` directory:
- `pages/index.js` => `.next/serverless/index.js`
- `pages/about.js` => `.next/serverless/about.js`
So what is inside `.next/serverless/about.js`? All the code needed to render that specific page. It has the Node.js `http.Server` request handler function signature:
```ts
(req: http.IncomingMessage, res: http.ServerResponse) => void
```
So how do you use it? Generally you **don't** want to use the below example, but for illustration purposes it's shown how the handler is called using a plain `http.Server`:
```js
const http = require('http')
// Note that `.default` is needed because the exported module is an esmodule
const handler = require('./.next/serverless/about.js').default
const server = new http.Server((req, res) => handler(req, res))
server.listen(3000, () => console.log('Listening on http://localhost:3000'))
```
Generally you'll upload this handler function to an external service like [Now v2](https://zeit.co/now-2), the `@now/next` builder will be updated to reflect these changes. This means that it'll be no longer neccesary for `@now/next` to do some of the guesswork in creating smaller handler functions. As Next.js will output the smallest possible serverless handler function automatically.
The function has 0 dependencies so no node_modules are required to run it, and is generally very small. 45Kb zipped is the baseline, but I'm sure we can make it even smaller in the future.
One important thing to note is that the function won't try to load `next.config.js`, so `publicRuntimeConfig` / `serverRuntimeConfig` are not supported. Reasons are outlined here: #5846
So to summarize:
- every page becomes a serverless function
- the serverless function has 0 dependencies (they're all inlined)
- "just" uses the `req` and `res` coming from Node.js
- opt-in using `target: 'serverless'` in `next.config.js`
- Does not load next.config.js when executing the function
TODO:
- [x] Compile next/dynamic / `import()` into the function file, so that no extra files have to be uploaded.
- [x] Setting `assetPrefix` at build time for serverless target
- [x] Support custom /_app
- [x] Support custom /_document
- [x] Support custom /_error
- [x] Add `next.config.js` property for `target`
Need discussion:
- [ ] Since the serverless target won't support `publicRuntimeConfig` / `serverRuntimeConfig` as they're runtime values. I think we should support build-time env var replacement with webpack.DefinePlugin or similar.
- [ ] Serving static files with the correct cache-control, as there is no static file serving in the serverless target
2018-12-28 11:39:12 +01:00
|
|
|
} catch(err) {
|
|
|
|
console.error(err)
|
2020-06-02 01:12:45 +02:00
|
|
|
await onError(err)
|
|
|
|
// Throw the error to crash the serverless function
|
|
|
|
throw err
|
Serverless Next.js (#5927)
**This does not change existing behavior.**
building to serverless is completely opt-in.
- Implements `target: 'serverless'` in `next.config.js`
- Removes `next build --lambdas` (was only available on next@canary so far)
This implements the concept of build targets. Currently there will be 2 build targets:
- server (This is the target that already existed / the default, no changes here)
- serverless (New target aimed at compiling pages to serverless handlers)
The serverless target will output a single file per `page` in the `pages` directory:
- `pages/index.js` => `.next/serverless/index.js`
- `pages/about.js` => `.next/serverless/about.js`
So what is inside `.next/serverless/about.js`? All the code needed to render that specific page. It has the Node.js `http.Server` request handler function signature:
```ts
(req: http.IncomingMessage, res: http.ServerResponse) => void
```
So how do you use it? Generally you **don't** want to use the below example, but for illustration purposes it's shown how the handler is called using a plain `http.Server`:
```js
const http = require('http')
// Note that `.default` is needed because the exported module is an esmodule
const handler = require('./.next/serverless/about.js').default
const server = new http.Server((req, res) => handler(req, res))
server.listen(3000, () => console.log('Listening on http://localhost:3000'))
```
Generally you'll upload this handler function to an external service like [Now v2](https://zeit.co/now-2), the `@now/next` builder will be updated to reflect these changes. This means that it'll be no longer neccesary for `@now/next` to do some of the guesswork in creating smaller handler functions. As Next.js will output the smallest possible serverless handler function automatically.
The function has 0 dependencies so no node_modules are required to run it, and is generally very small. 45Kb zipped is the baseline, but I'm sure we can make it even smaller in the future.
One important thing to note is that the function won't try to load `next.config.js`, so `publicRuntimeConfig` / `serverRuntimeConfig` are not supported. Reasons are outlined here: #5846
So to summarize:
- every page becomes a serverless function
- the serverless function has 0 dependencies (they're all inlined)
- "just" uses the `req` and `res` coming from Node.js
- opt-in using `target: 'serverless'` in `next.config.js`
- Does not load next.config.js when executing the function
TODO:
- [x] Compile next/dynamic / `import()` into the function file, so that no extra files have to be uploaded.
- [x] Setting `assetPrefix` at build time for serverless target
- [x] Support custom /_app
- [x] Support custom /_document
- [x] Support custom /_error
- [x] Add `next.config.js` property for `target`
Need discussion:
- [ ] Since the serverless target won't support `publicRuntimeConfig` / `serverRuntimeConfig` as they're runtime values. I think we should support build-time env var replacement with webpack.DefinePlugin or similar.
- [ ] Serving static files with the correct cache-control, as there is no static file serving in the serverless target
2018-12-28 11:39:12 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
`
|
2019-07-07 23:45:40 +02:00
|
|
|
}
|
Serverless Next.js (#5927)
**This does not change existing behavior.**
building to serverless is completely opt-in.
- Implements `target: 'serverless'` in `next.config.js`
- Removes `next build --lambdas` (was only available on next@canary so far)
This implements the concept of build targets. Currently there will be 2 build targets:
- server (This is the target that already existed / the default, no changes here)
- serverless (New target aimed at compiling pages to serverless handlers)
The serverless target will output a single file per `page` in the `pages` directory:
- `pages/index.js` => `.next/serverless/index.js`
- `pages/about.js` => `.next/serverless/about.js`
So what is inside `.next/serverless/about.js`? All the code needed to render that specific page. It has the Node.js `http.Server` request handler function signature:
```ts
(req: http.IncomingMessage, res: http.ServerResponse) => void
```
So how do you use it? Generally you **don't** want to use the below example, but for illustration purposes it's shown how the handler is called using a plain `http.Server`:
```js
const http = require('http')
// Note that `.default` is needed because the exported module is an esmodule
const handler = require('./.next/serverless/about.js').default
const server = new http.Server((req, res) => handler(req, res))
server.listen(3000, () => console.log('Listening on http://localhost:3000'))
```
Generally you'll upload this handler function to an external service like [Now v2](https://zeit.co/now-2), the `@now/next` builder will be updated to reflect these changes. This means that it'll be no longer neccesary for `@now/next` to do some of the guesswork in creating smaller handler functions. As Next.js will output the smallest possible serverless handler function automatically.
The function has 0 dependencies so no node_modules are required to run it, and is generally very small. 45Kb zipped is the baseline, but I'm sure we can make it even smaller in the future.
One important thing to note is that the function won't try to load `next.config.js`, so `publicRuntimeConfig` / `serverRuntimeConfig` are not supported. Reasons are outlined here: #5846
So to summarize:
- every page becomes a serverless function
- the serverless function has 0 dependencies (they're all inlined)
- "just" uses the `req` and `res` coming from Node.js
- opt-in using `target: 'serverless'` in `next.config.js`
- Does not load next.config.js when executing the function
TODO:
- [x] Compile next/dynamic / `import()` into the function file, so that no extra files have to be uploaded.
- [x] Setting `assetPrefix` at build time for serverless target
- [x] Support custom /_app
- [x] Support custom /_document
- [x] Support custom /_error
- [x] Add `next.config.js` property for `target`
Need discussion:
- [ ] Since the serverless target won't support `publicRuntimeConfig` / `serverRuntimeConfig` as they're runtime values. I think we should support build-time env var replacement with webpack.DefinePlugin or similar.
- [ ] Serving static files with the correct cache-control, as there is no static file serving in the serverless target
2018-12-28 11:39:12 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
export default nextServerlessLoader
|