Unverified Commit afc278f5 authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Add support for runtimeConfigs in serverless mode (#10365)

* Add support for runtimeConfigs in serverless mode

* Update test
parent e63d8221
# Using `publicRuntimeConfig` or `serverRuntimeConfig` with `target` set to `serverless`
#### Why This Error Occurred
In the `serverless` target environment `next.config.js` is not loaded, so we don't support `publicRuntimeConfig` or `serverRuntimeConfig`.
#### Possible Ways to Fix It
Use config option `env` to set **build time** variables like such:
```js
// next.config.js
module.exports = {
env: {
special: 'value',
},
}
```
```js
// pages/index.js
console.log(process.env.special) // value
```
...@@ -67,6 +67,10 @@ export function createEntrypoints( ...@@ -67,6 +67,10 @@ export function createEntrypoints(
const client: WebpackEntrypoints = {} const client: WebpackEntrypoints = {}
const server: WebpackEntrypoints = {} const server: WebpackEntrypoints = {}
const hasRuntimeConfig =
Object.keys(config.publicRuntimeConfig).length > 0 ||
Object.keys(config.serverRuntimeConfig).length > 0
const defaultServerlessOptions = { const defaultServerlessOptions = {
absoluteAppPath: pages['/_app'], absoluteAppPath: pages['/_app'],
absoluteDocumentPath: pages['/_document'], absoluteDocumentPath: pages['/_document'],
...@@ -77,6 +81,12 @@ export function createEntrypoints( ...@@ -77,6 +81,12 @@ export function createEntrypoints(
generateEtags: config.generateEtags, generateEtags: config.generateEtags,
canonicalBase: config.canonicalBase, canonicalBase: config.canonicalBase,
basePath: config.experimental.basePath, basePath: config.experimental.basePath,
runtimeConfig: hasRuntimeConfig
? JSON.stringify({
publicRuntimeConfig: config.publicRuntimeConfig,
serverRuntimeConfig: config.serverRuntimeConfig,
})
: '',
} }
Object.keys(pages).forEach(page => { Object.keys(pages).forEach(page => {
......
...@@ -22,6 +22,7 @@ export type ServerlessLoaderQuery = { ...@@ -22,6 +22,7 @@ export type ServerlessLoaderQuery = {
generateEtags: string generateEtags: string
canonicalBase: string canonicalBase: string
basePath: string basePath: string
runtimeConfig: string
} }
const nextServerlessLoader: loader.Loader = function() { const nextServerlessLoader: loader.Loader = function() {
...@@ -37,6 +38,7 @@ const nextServerlessLoader: loader.Loader = function() { ...@@ -37,6 +38,7 @@ const nextServerlessLoader: loader.Loader = function() {
absoluteErrorPath, absoluteErrorPath,
generateEtags, generateEtags,
basePath, basePath,
runtimeConfig,
}: ServerlessLoaderQuery = }: ServerlessLoaderQuery =
typeof this.query === 'string' ? parse(this.query.substr(1)) : this.query typeof this.query === 'string' ? parse(this.query.substr(1)) : this.query
...@@ -50,6 +52,19 @@ const nextServerlessLoader: loader.Loader = function() { ...@@ -50,6 +52,19 @@ const nextServerlessLoader: loader.Loader = function() {
const escapedBuildId = escapeRegexp(buildId) const escapedBuildId = escapeRegexp(buildId)
const pageIsDynamicRoute = isDynamicRoute(page) const pageIsDynamicRoute = isDynamicRoute(page)
const runtimeConfigImports = runtimeConfig
? `
import { setConfig } from 'next/dist/next-server/lib/runtime-config'
`
: ''
const runtimeConfigSetter = runtimeConfig
? `
const runtimeConfig = ${runtimeConfig}
setConfig(runtimeConfig)
`
: 'const runtimeConfig = {}'
const dynamicRouteImports = pageIsDynamicRoute const dynamicRouteImports = pageIsDynamicRoute
? ` ? `
import { getRouteMatcher } from 'next/dist/next-server/lib/router/utils/route-matcher'; import { getRouteMatcher } from 'next/dist/next-server/lib/router/utils/route-matcher';
...@@ -123,9 +138,14 @@ const nextServerlessLoader: loader.Loader = function() { ...@@ -123,9 +138,14 @@ const nextServerlessLoader: loader.Loader = function() {
import initServer from 'next-plugin-loader?middleware=on-init-server!' import initServer from 'next-plugin-loader?middleware=on-init-server!'
import onError from 'next-plugin-loader?middleware=on-error-server!' import onError from 'next-plugin-loader?middleware=on-error-server!'
${rewriteImports} ${rewriteImports}
${runtimeConfigImports}
${dynamicRouteMatcher} ${dynamicRouteMatcher}
${handleRewrites} ${handleRewrites}
${
/* this needs to be called before importing the API method */
runtimeConfigSetter
}
export default async (req, res) => { export default async (req, res) => {
try { try {
...@@ -177,9 +197,16 @@ const nextServerlessLoader: loader.Loader = function() { ...@@ -177,9 +197,16 @@ const nextServerlessLoader: loader.Loader = function() {
import Document from '${absoluteDocumentPath}'; import Document from '${absoluteDocumentPath}';
import Error from '${absoluteErrorPath}'; import Error from '${absoluteErrorPath}';
import App from '${absoluteAppPath}'; import App from '${absoluteAppPath}';
import * as ComponentInfo from '${absolutePagePath}';
${dynamicRouteImports} ${dynamicRouteImports}
${rewriteImports} ${rewriteImports}
${runtimeConfigImports}
${
/* this needs to be called before importing the component */
runtimeConfigSetter
}
const ComponentInfo = require('${absolutePagePath}')
const Component = ComponentInfo.default const Component = ComponentInfo.default
export default Component export default Component
...@@ -214,6 +241,7 @@ const nextServerlessLoader: loader.Loader = function() { ...@@ -214,6 +241,7 @@ const nextServerlessLoader: loader.Loader = function() {
canonicalBase: "${canonicalBase}", canonicalBase: "${canonicalBase}",
buildId: "${buildId}", buildId: "${buildId}",
assetPrefix: "${assetPrefix}", assetPrefix: "${assetPrefix}",
runtimeConfig: runtimeConfig.publicRuntimeConfig || {},
..._renderOpts ..._renderOpts
} }
let _nextData = false let _nextData = false
......
...@@ -254,20 +254,6 @@ export default function loadConfig( ...@@ -254,20 +254,6 @@ export default function loadConfig(
: canonicalBase) || '' : canonicalBase) || ''
} }
if (
userConfig.target &&
userConfig.target !== 'server' &&
((userConfig.publicRuntimeConfig &&
Object.keys(userConfig.publicRuntimeConfig).length !== 0) ||
(userConfig.serverRuntimeConfig &&
Object.keys(userConfig.serverRuntimeConfig).length !== 0))
) {
// TODO: change error message tone to "Only compatible with [fat] server mode"
throw new Error(
'Cannot use publicRuntimeConfig or serverRuntimeConfig with target=serverless https://err.sh/zeit/next.js/serverless-publicRuntimeConfig'
)
}
if ( if (
userConfig.experimental?.reactMode && userConfig.experimental?.reactMode &&
!reactModes.includes(userConfig.experimental.reactMode) !reactModes.includes(userConfig.experimental.reactMode)
......
...@@ -11,7 +11,7 @@ describe('Handle non-page in pages when target: serverless', () => { ...@@ -11,7 +11,7 @@ describe('Handle non-page in pages when target: serverless', () => {
const { stderr } = await nextBuild(appDir, [], { stderr: true }) const { stderr } = await nextBuild(appDir, [], { stderr: true })
expect(stderr).toMatch( expect(stderr).toMatch(
/webpack build failed: found page without a React Component as default export in/ /found page without a React Component as default export in/
) )
expect(stderr).toMatch(/pages\/invalid/) expect(stderr).toMatch(/pages\/invalid/)
}) })
......
import getConfig from 'next/config'
const config = getConfig()
export default () => <p id="config">{JSON.stringify(config)}</p>
...@@ -2,7 +2,15 @@ ...@@ -2,7 +2,15 @@
/* global jasmine */ /* global jasmine */
import fs from 'fs-extra' import fs from 'fs-extra'
import { join } from 'path' import { join } from 'path'
import { nextBuild } from 'next-test-utils' import {
nextBuild,
findPort,
nextStart,
killApp,
renderViaHTTP,
} from 'next-test-utils'
import cheerio from 'cheerio'
import webdriver from 'next-webdriver'
const appDir = join(__dirname, '../') const appDir = join(__dirname, '../')
const nextConfigPath = join(appDir, 'next.config.js') const nextConfigPath = join(appDir, 'next.config.js')
...@@ -14,7 +22,7 @@ describe('Serverless runtime configs', () => { ...@@ -14,7 +22,7 @@ describe('Serverless runtime configs', () => {
beforeAll(() => cleanUp()) beforeAll(() => cleanUp())
afterAll(() => cleanUp()) afterAll(() => cleanUp())
it('should error on usage of publicRuntimeConfig', async () => { it('should not error on usage of publicRuntimeConfig', async () => {
await fs.writeFile( await fs.writeFile(
nextConfigPath, nextConfigPath,
`module.exports = { `module.exports = {
...@@ -25,13 +33,16 @@ describe('Serverless runtime configs', () => { ...@@ -25,13 +33,16 @@ describe('Serverless runtime configs', () => {
}` }`
) )
const { stderr } = await nextBuild(appDir, undefined, { stderr: true }) const { stderr, code } = await nextBuild(appDir, undefined, {
expect(stderr).toMatch( stderr: true,
})
expect(code).toBe(0)
expect(stderr).not.toMatch(
/Cannot use publicRuntimeConfig or serverRuntimeConfig/ /Cannot use publicRuntimeConfig or serverRuntimeConfig/
) )
}) })
it('should error on usage of serverRuntimeConfig', async () => { it('should not error on usage of serverRuntimeConfig', async () => {
await fs.writeFile( await fs.writeFile(
nextConfigPath, nextConfigPath,
`module.exports = { `module.exports = {
...@@ -42,9 +53,63 @@ describe('Serverless runtime configs', () => { ...@@ -42,9 +53,63 @@ describe('Serverless runtime configs', () => {
}` }`
) )
const { stderr } = await nextBuild(appDir, undefined, { stderr: true }) const { stderr, code } = await nextBuild(appDir, undefined, {
expect(stderr).toMatch( stderr: true,
})
expect(code).toBe(0)
expect(stderr).not.toMatch(
/Cannot use publicRuntimeConfig or serverRuntimeConfig/ /Cannot use publicRuntimeConfig or serverRuntimeConfig/
) )
}) })
it('should support runtime configs in serverless mode', async () => {
await fs.writeFile(
nextConfigPath,
`module.exports = {
target: 'serverless',
serverRuntimeConfig: {
hello: 'world'
},
publicRuntimeConfig: {
another: 'thing'
}
}`
)
await nextBuild(appDir, [], { stderr: true, stdout: true })
const appPort = await findPort()
const app = await nextStart(appDir, appPort, {
onStdout: console.log,
onStderr: console.log,
})
const browser = await webdriver(appPort, '/config')
const clientHTML = await browser.eval(`document.documentElement.innerHTML`)
const ssrHTML = await renderViaHTTP(appPort, '/config')
await killApp(app)
await fs.remove(nextConfigPath)
const ssr$ = cheerio.load(ssrHTML)
const client$ = cheerio.load(clientHTML)
const ssrConfig = ssr$('#config').text()
const clientConfig = client$('#config').text()
expect(JSON.parse(ssrConfig)).toEqual({
publicRuntimeConfig: {
another: 'thing',
},
serverRuntimeConfig: {
hello: 'world',
},
})
expect(JSON.parse(clientConfig)).toEqual({
publicRuntimeConfig: {
another: 'thing',
},
serverRuntimeConfig: {},
})
})
}) })
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment