Unverified Commit d5e767b2 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

Add process env NEXT_RUNTIME (#36383)

* To help determine the current running environment is in server nodejs / edge runtime
* Remove usage of `process.browser`
parent 487f7aba
...@@ -2,8 +2,8 @@ ...@@ -2,8 +2,8 @@
#### Why This Error Occurred #### Why This Error Occurred
Next.js configures internal variables for replacement itself. These start with `__` or `NODE_`, for this reason they are not allowed as values for `env` in `next.config.js` Next.js configures internal variables for replacement itself. `NEXT_RUNTIME` along with variables starting with `__` or `NODE_` are currently internal, for this reason they are not allowed as values for `env` in `next.config.js`
#### Possible Ways to Fix It #### Possible Ways to Fix It
Rename the specified key so that it does not start with `__` or `NODE_`. Rename the specified key so that it does not start with `__` or `NODE_`, or pick other another name for `NEXT_RUNTIME`.
...@@ -104,6 +104,7 @@ if (process.env.NODE_ENV) { ...@@ -104,6 +104,7 @@ if (process.env.NODE_ENV) {
} }
;(process.env as any).NODE_ENV = process.env.NODE_ENV || defaultEnv ;(process.env as any).NODE_ENV = process.env.NODE_ENV || defaultEnv
;(process.env as any).NEXT_RUNTIME = 'nodejs'
// x-ref: https://github.com/vercel/next.js/pull/34688#issuecomment-1047994505 // x-ref: https://github.com/vercel/next.js/pull/34688#issuecomment-1047994505
if (process.versions.pnp === '3') { if (process.versions.pnp === '3') {
......
...@@ -1354,11 +1354,7 @@ export default async function getBaseWebpackConfig( ...@@ -1354,11 +1354,7 @@ export default async function getBaseWebpackConfig(
{} {}
), ),
...Object.keys(config.env).reduce((acc, key) => { ...Object.keys(config.env).reduce((acc, key) => {
if (/^(?:NODE_.+)|^(?:__.+)$/i.test(key)) { errorIfEnvConflicted(config, key)
throw new Error(
`The key "${key}" under "env" in ${config.configFileName} is not allowed. https://nextjs.org/docs/messages/env-key-not-allowed`
)
}
return { return {
...acc, ...acc,
...@@ -1369,11 +1365,16 @@ export default async function getBaseWebpackConfig( ...@@ -1369,11 +1365,16 @@ export default async function getBaseWebpackConfig(
'process.env.NODE_ENV': JSON.stringify( 'process.env.NODE_ENV': JSON.stringify(
dev ? 'development' : 'production' dev ? 'development' : 'production'
), ),
...(isServer && {
'process.env.NEXT_RUNTIME': JSON.stringify(
isEdgeRuntime ? 'edge' : 'nodejs'
),
}),
'process.env.__NEXT_NEW_LINK_BEHAVIOR': JSON.stringify( 'process.env.__NEXT_NEW_LINK_BEHAVIOR': JSON.stringify(
config.experimental.newNextLinkBehavior config.experimental.newNextLinkBehavior
), ),
'process.env.__NEXT_CROSS_ORIGIN': JSON.stringify(crossOrigin), 'process.env.__NEXT_CROSS_ORIGIN': JSON.stringify(crossOrigin),
'process.browser': JSON.stringify(targetWeb), 'process.browser': JSON.stringify(!isServer),
'process.env.__NEXT_TEST_MODE': JSON.stringify( 'process.env.__NEXT_TEST_MODE': JSON.stringify(
process.env.__NEXT_TEST_MODE process.env.__NEXT_TEST_MODE
), ),
...@@ -2182,3 +2183,14 @@ export default async function getBaseWebpackConfig( ...@@ -2182,3 +2183,14 @@ export default async function getBaseWebpackConfig(
return webpackConfig return webpackConfig
} }
function errorIfEnvConflicted(config: NextConfigComplete, key: string) {
const isPrivateKey = /^(?:NODE_.+)|^(?:__.+)$/i.test(key)
const hasNextRuntimeKey = key === 'NEXT_RUNTIME'
if (isPrivateKey || hasNextRuntimeKey) {
throw new Error(
`The key "${key}" under "env" in ${config.configFileName} is not allowed. https://nextjs.org/docs/messages/env-key-not-allowed`
)
}
}
let chalk: typeof import('next/dist/compiled/chalk') let chalk: typeof import('next/dist/compiled/chalk')
if (!process.browser) { if (process.env.NEXT_RUNTIME === 'edge') {
chalk = require('next/dist/compiled/chalk')
} else {
chalk = require('./web/chalk').default chalk = require('./web/chalk').default
} else {
chalk = require('next/dist/compiled/chalk')
} }
export default chalk export default chalk
...@@ -80,7 +80,7 @@ function getPreNextWorkerScripts(context: HtmlProps, props: OriginProps) { ...@@ -80,7 +80,7 @@ function getPreNextWorkerScripts(context: HtmlProps, props: OriginProps) {
const { assetPrefix, scriptLoader, crossOrigin, nextScriptWorkers } = context const { assetPrefix, scriptLoader, crossOrigin, nextScriptWorkers } = context
// disable `nextScriptWorkers` in edge runtime // disable `nextScriptWorkers` in edge runtime
if (!nextScriptWorkers || process.browser) return null if (!nextScriptWorkers || process.env.NEXT_RUNTIME === 'edge') return null
try { try {
let { let {
......
...@@ -1155,7 +1155,7 @@ export default abstract class Server { ...@@ -1155,7 +1155,7 @@ export default abstract class Server {
(isServerComponent && (isServerComponent &&
!hasServerProps && !hasServerProps &&
!hasGetInitialProps && !hasGetInitialProps &&
!process.browser) process.env.NEXT_RUNTIME !== 'edge')
// Toggle whether or not this is a Data request // Toggle whether or not this is a Data request
const isDataReq = const isDataReq =
...@@ -1240,7 +1240,7 @@ export default abstract class Server { ...@@ -1240,7 +1240,7 @@ export default abstract class Server {
if (hasServerProps || isSSG) { if (hasServerProps || isSSG) {
// For the edge runtime, we don't support preview mode in SSG. // For the edge runtime, we don't support preview mode in SSG.
if (!process.browser) { if (process.env.NEXT_RUNTIME !== 'edge') {
const { tryGetPreviewData } = const { tryGetPreviewData } =
require('./api-utils/node') as typeof import('./api-utils/node') require('./api-utils/node') as typeof import('./api-utils/node')
previewData = tryGetPreviewData(req, res, this.renderOpts.previewProps) previewData = tryGetPreviewData(req, res, this.renderOpts.previewProps)
...@@ -1758,7 +1758,10 @@ export default abstract class Server { ...@@ -1758,7 +1758,10 @@ export default abstract class Server {
) )
if (!isWrappedError) { if (!isWrappedError) {
if ((this.minimalMode && !process.browser) || this.renderOpts.dev) { if (
(this.minimalMode && process.env.NEXT_RUNTIME !== 'edge') ||
this.renderOpts.dev
) {
if (isError(err)) err.page = page if (isError(err)) err.page = page
throw err throw err
} }
......
...@@ -89,7 +89,7 @@ let postProcess: typeof import('../shared/lib/post-process').default ...@@ -89,7 +89,7 @@ let postProcess: typeof import('../shared/lib/post-process').default
const DOCTYPE = '<!DOCTYPE html>' const DOCTYPE = '<!DOCTYPE html>'
if (!process.browser) { if (process.env.NEXT_RUNTIME !== 'edge') {
require('./node-polyfill-web-streams') require('./node-polyfill-web-streams')
optimizeAmp = require('./optimize-amp').default optimizeAmp = require('./optimize-amp').default
getFontDefinitionFromManifest = getFontDefinitionFromManifest =
...@@ -518,7 +518,9 @@ export async function renderToHTML( ...@@ -518,7 +518,9 @@ export async function renderToHTML(
Uint8Array, Uint8Array,
Uint8Array Uint8Array
> | null = > | null =
isServerComponent && !process.browser ? new TransformStream() : null isServerComponent && process.env.NEXT_RUNTIME !== 'edge'
? new TransformStream()
: null
if (isServerComponent) { if (isServerComponent) {
serverComponentsInlinedTransformStream = new TransformStream() serverComponentsInlinedTransformStream = new TransformStream()
...@@ -700,7 +702,11 @@ export async function renderToHTML( ...@@ -700,7 +702,11 @@ export async function renderToHTML(
let isPreview let isPreview
let previewData: PreviewData let previewData: PreviewData
if ((isSSG || getServerSideProps) && !isFallback && !process.browser) { if (
(isSSG || getServerSideProps) &&
!isFallback &&
process.env.NEXT_RUNTIME !== 'edge'
) {
// Reads of this are cached on the `req` object, so this should resolve // Reads of this are cached on the `req` object, so this should resolve
// instantly. There's no need to pass this data down from a previous // instantly. There's no need to pass this data down from a previous
// invoke, where we'd have to consider server & serverless. // invoke, where we'd have to consider server & serverless.
...@@ -775,7 +781,7 @@ export async function renderToHTML( ...@@ -775,7 +781,7 @@ export async function renderToHTML(
} }
// Disable AMP under the web environment // Disable AMP under the web environment
const inAmpMode = !process.browser && isInAmpMode(ampState) const inAmpMode = process.env.NEXT_RUNTIME !== 'edge' && isInAmpMode(ampState)
const reactLoadableModules: string[] = [] const reactLoadableModules: string[] = []
...@@ -1313,7 +1319,7 @@ export async function renderToHTML( ...@@ -1313,7 +1319,7 @@ export async function renderToHTML(
| typeof Document | typeof Document
| undefined | undefined
if (process.browser && Document.getInitialProps) { if (process.env.NEXT_RUNTIME === 'edge' && Document.getInitialProps) {
// In the Edge runtime, `Document.getInitialProps` isn't supported. // In the Edge runtime, `Document.getInitialProps` isn't supported.
// We throw an error here if it's customized. // We throw an error here if it's customized.
if (!builtinDocument) { if (!builtinDocument) {
...@@ -1323,7 +1329,10 @@ export async function renderToHTML( ...@@ -1323,7 +1329,10 @@ export async function renderToHTML(
} }
} }
if ((isServerComponent || process.browser) && Document.getInitialProps) { if (
(isServerComponent || process.env.NEXT_RUNTIME === 'edge') &&
Document.getInitialProps
) {
if (builtinDocument) { if (builtinDocument) {
Document = builtinDocument Document = builtinDocument
} else { } else {
...@@ -1541,7 +1550,7 @@ export async function renderToHTML( ...@@ -1541,7 +1550,7 @@ export async function renderToHTML(
const hasDocumentGetInitialProps = !( const hasDocumentGetInitialProps = !(
isServerComponent || isServerComponent ||
process.browser || process.env.NEXT_RUNTIME === 'edge' ||
!Document.getInitialProps !Document.getInitialProps
) )
...@@ -1560,7 +1569,7 @@ export async function renderToHTML( ...@@ -1560,7 +1569,7 @@ export async function renderToHTML(
const { docProps } = (documentInitialPropsRes as any) || {} const { docProps } = (documentInitialPropsRes as any) || {}
const documentElement = () => { const documentElement = () => {
if (isServerComponent || process.browser) { if (isServerComponent || process.env.NEXT_RUNTIME === 'edge') {
return (Document as any)() return (Document as any)()
} }
...@@ -1751,7 +1760,8 @@ export async function renderToHTML( ...@@ -1751,7 +1760,8 @@ export async function renderToHTML(
return html return html
} }
: null, : null,
!process.browser && process.env.__NEXT_OPTIMIZE_FONTS process.env.NEXT_RUNTIME !== 'edge' &&
process.env.__NEXT_OPTIMIZE_FONTS
? async (html: string) => { ? async (html: string) => {
return await postProcess( return await postProcess(
html, html,
...@@ -1762,7 +1772,7 @@ export async function renderToHTML( ...@@ -1762,7 +1772,7 @@ export async function renderToHTML(
) )
} }
: null, : null,
!process.browser && renderOpts.optimizeCss process.env.NEXT_RUNTIME !== 'edge' && renderOpts.optimizeCss
? async (html: string) => { ? async (html: string) => {
// eslint-disable-next-line import/no-extraneous-dependencies // eslint-disable-next-line import/no-extraneous-dependencies
const Critters = require('critters') const Critters = require('critters')
......
...@@ -265,7 +265,9 @@ function buildEnvironmentVariablesFrom( ...@@ -265,7 +265,9 @@ function buildEnvironmentVariablesFrom(
keys: string[] keys: string[]
): Record<string, string | undefined> { ): Record<string, string | undefined> {
const pairs = keys.map((key) => [key, process.env[key]]) const pairs = keys.map((key) => [key, process.env[key]])
return Object.fromEntries(pairs) const env = Object.fromEntries(pairs)
env.NEXT_RUNTIME = 'edge'
return env
} }
async function loadWasm( async function loadWasm(
......
const path = process.browser const path =
? require('next/dist/compiled/path-browserify') process.env.NEXT_RUNTIME === 'edge'
: require('path') ? require('next/dist/compiled/path-browserify')
: require('path')
export default path export default path
...@@ -119,6 +119,7 @@ describe('Middleware base tests', () => { ...@@ -119,6 +119,7 @@ describe('Middleware base tests', () => {
context.app = await launchApp(context.appDir, context.appPort, { context.app = await launchApp(context.appDir, context.appPort, {
env: { env: {
MIDDLEWARE_TEST: 'asdf', MIDDLEWARE_TEST: 'asdf',
NEXT_RUNTIME: 'edge',
}, },
}) })
}) })
...@@ -130,6 +131,7 @@ describe('Middleware base tests', () => { ...@@ -130,6 +131,7 @@ describe('Middleware base tests', () => {
process: { process: {
env: { env: {
MIDDLEWARE_TEST: 'asdf', MIDDLEWARE_TEST: 'asdf',
NEXT_RUNTIME: 'edge',
}, },
// it's poflyfilled since there is the "process" module // it's poflyfilled since there is the "process" module
// as a devDepencies of the next package // as a devDepencies of the next package
......
...@@ -15,6 +15,11 @@ module.exports = { ...@@ -15,6 +15,11 @@ module.exports = {
SOME__ENV__VAR: '123', SOME__ENV__VAR: '123',
} }
: {}), : {}),
...(process.env.ENABLE_ENV_NEXT_PRESERVED
? {
NEXT_RUNTIME: 'nodejs',
}
: {}),
}, },
onDemandEntries: { onDemandEntries: {
// Make sure entries are not getting disposed. // Make sure entries are not getting disposed.
......
...@@ -56,6 +56,16 @@ describe('Production Config Usage', () => { ...@@ -56,6 +56,16 @@ describe('Production Config Usage', () => {
expect(result.stderr).toMatch(/The key "NODE_ENV" under/) expect(result.stderr).toMatch(/The key "NODE_ENV" under/)
}) })
it('should fail with NEXT_RUNTIME in env key', async () => {
const result = await runNextCommand(['build', appDir], {
env: { ENABLE_ENV_NEXT_PRESERVED: true },
stdout: true,
stderr: true,
})
expect(result.stderr).toMatch(/The key "NEXT_RUNTIME" under/)
})
it('should allow __ within env key', async () => { it('should allow __ within env key', async () => {
const result = await runNextCommand(['build', appDir], { const result = await runNextCommand(['build', appDir], {
env: { ENABLE_ENV_WITH_UNDERSCORES: true }, env: { ENABLE_ENV_WITH_UNDERSCORES: true },
......
export default function () { export default function () {
return process.version return process.env.NEXT_RUNTIME === 'nodejs'
? `Runtime: Node.js ${process.version}` ? `Runtime: Node.js ${process.version}`
: 'Runtime: Edge/Browser' : 'Runtime: Edge/Browser'
} }
......
...@@ -44,6 +44,7 @@ describe('middleware environment variables in node server reflect the usage infe ...@@ -44,6 +44,7 @@ describe('middleware environment variables in node server reflect the usage infe
rest: { rest: {
CAN_BE_INFERRED: 'can-be-inferred', CAN_BE_INFERRED: 'can-be-inferred',
X_CUSTOM_HEADER: 'x-custom-header', X_CUSTOM_HEADER: 'x-custom-header',
NEXT_RUNTIME: 'edge',
}, },
}) })
}) })
......
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