Unverified Commit 94b24646 authored by Will Binns-Smith's avatar Will Binns-Smith Committed by GitHub

next.config.ts: Implement `compiler.defineServer` for server-only constants (#79225)

Like `compiler.define`, this allows users to create compile-time
constants both Turbopack and webpack from a single API.
`compiler.defineServer` instead only makes these constants available for
server or edge environments, not the client environment.
parent b51d5551
......@@ -265,14 +265,17 @@ This option has been superseded by [`optimizePackageImports`](/docs/app/api-refe
The `define` option allows you to statically replace variables in your code at build-time.
The option takes an object as key-value pairs, where the keys are the variables that should be replaced with the corresponding values.
Use the `compiler.define` field in `next.config.js`:
Use the `compiler.define` field in `next.config.js` to define variables for all environments (server, edge, and client). Or, use `compiler.defineServer` to define variables only for server-side (server and edge) code:
```js filename="next.config.js"
module.exports = {
compiler: {
define: {
MY_STRING_VARIABLE: JSON.stringify('my-string'),
MY_NUMBER_VARIABLE: '42',
MY_VARIABLE: 'my-string',
'process.env.MY_ENV_VAR': 'my-env-var',
},
defineServer: {
MY_SERVER_VARIABLE: 'my-server-var',
},
},
}
......
......@@ -680,5 +680,7 @@
"679": "A CacheSignal cannot subscribe to itself",
"680": "CacheSignal cannot be used in the edge runtime, because `dynamicIO` does not support it.",
"681": "Dynamic imports should not be instrumented in the edge runtime, because `dynamicIO` doesn't support it",
"682": "\\`experimental.ppr\\` can not be \\`%s\\` when \\`experimental.dynamicIO\\` is \\`true\\`. PPR is implicitly enabled when Dynamic IO is enabled."
"682": "\\`experimental.ppr\\` can not be \\`%s\\` when \\`experimental.dynamicIO\\` is \\`true\\`. PPR is implicitly enabled when Dynamic IO is enabled.",
"683": "The \\`compiler.define\\` option is configured to replace the \\`%s\\` variable. This variable is either part of a Next.js built-in or is already configured.",
"684": "The \\`compiler.defineServer\\` option is configured to replace the \\`%s\\` variable. This variable is either part of a Next.js built-in or is already configured."
}
......@@ -24,7 +24,6 @@ export interface DefineEnvOptions {
hasRewrites: boolean
isClient: boolean
isEdgeServer: boolean
isNodeOrEdgeCompilation: boolean
isNodeServer: boolean
middlewareMatchers: MiddlewareMatcher[] | undefined
omitNonDeterministic?: boolean
......@@ -94,7 +93,6 @@ export function getDefineEnv({
hasRewrites,
isClient,
isEdgeServer,
isNodeOrEdgeCompilation,
isNodeServer,
middlewareMatchers,
omitNonDeterministic,
......@@ -250,7 +248,7 @@ export function getDefineEnv({
'process.env.__NEXT_TELEMETRY_DISABLED': Boolean(
process.env.NEXT_TELEMETRY_DISABLED
),
...(isNodeOrEdgeCompilation
...(isNodeServer || isEdgeServer
? {
// Fix bad-actors in the npm ecosystem (e.g. `node-formidable`)
// This is typically found in unmaintained modules from the
......@@ -258,7 +256,7 @@ export function getDefineEnv({
'global.GENTLY': false,
}
: undefined),
...(isNodeOrEdgeCompilation
...(isNodeServer || isEdgeServer
? {
'process.env.__NEXT_EXPERIMENTAL_REACT':
needsExperimentalReact(config),
......@@ -287,12 +285,24 @@ export function getDefineEnv({
for (const key in userDefines) {
if (defineEnv.hasOwnProperty(key)) {
throw new Error(
`The \`compiler.define\` option is configured to replace the \`${key}\` variable. This variable is either part of a Next.js built-in or is already configured via the \`env\` option.`
`The \`compiler.define\` option is configured to replace the \`${key}\` variable. This variable is either part of a Next.js built-in or is already configured.`
)
}
defineEnv[key] = userDefines[key]
}
if (isNodeServer || isEdgeServer) {
const userDefinesServer = config.compiler?.defineServer ?? {}
for (const key in userDefinesServer) {
if (defineEnv.hasOwnProperty(key)) {
throw new Error(
`The \`compiler.defineServer\` option is configured to replace the \`${key}\` variable. This variable is either part of a Next.js built-in or is already configured.`
)
}
defineEnv[key] = userDefinesServer[key]
}
}
const serializedDefineEnv = serializeDefineEnv(defineEnv)
// we delay inlining these values until after the build
......
......@@ -411,7 +411,6 @@ export function createDefineEnv({
hasRewrites,
isClient: variant === 'client',
isEdgeServer: variant === 'edge',
isNodeOrEdgeCompilation: variant === 'nodejs' || variant === 'edge',
isNodeServer: variant === 'nodejs',
middlewareMatchers,
})
......
......@@ -1937,7 +1937,6 @@ export default async function getBaseWebpackConfig(
hasRewrites,
isClient,
isEdgeServer,
isNodeOrEdgeCompilation,
isNodeServer,
middlewareMatchers,
omitNonDeterministic: isCompileMode,
......
......@@ -270,6 +270,7 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
}),
]),
define: z.record(z.string(), z.string()).optional(),
defineServer: z.record(z.string(), z.string()).optional(),
runAfterProductionCompile: z
.function()
.returns(z.promise(z.void()))
......
......@@ -1085,6 +1085,12 @@ export interface NextConfig extends Record<string, any> {
*/
define?: Record<string, string>
/**
* Replaces server-only (Node.js and Edge) variables in your code during compile time.
* Each key will be replaced with the respective values.
*/
defineServer?: Record<string, string>
/**
* A hook function that executes after production build compilation finishes,
* but before running post-compilation tasks such as type checking and
......
......@@ -738,7 +738,6 @@ async function startWatcher(opts: SetupOpts) {
hasRewrites,
isClient,
isEdgeServer,
isNodeOrEdgeCompilation: isNodeServer || isEdgeServer,
isNodeServer,
middlewareMatchers: undefined,
})
......
......@@ -6,3 +6,13 @@ export function ClientValue() {
<>{typeof MY_MAGIC_VARIABLE === 'string' ? MY_MAGIC_VARIABLE : 'not set'}</>
)
}
export function ClientExpr() {
return (
<>
{typeof process.env.MY_MAGIC_EXPR === 'string'
? process.env.MY_MAGIC_EXPR
: 'not set'}
</>
)
}
/* eslint-disable no-undef */
import { ClientValue } from './client-component'
import { ClientValue, ClientExpr } from './client-component'
export default function Page() {
return (
......@@ -11,6 +11,15 @@ export default function Page() {
<li>
Client value: <ClientValue />
</li>
<li>
Server expr:{' '}
{typeof process.env.MY_MAGIC_EXPR === 'string'
? process.env.MY_MAGIC_EXPR
: 'not set'}
</li>
<li>
Client expr: <ClientExpr />
</li>
</ul>
)
}
/* eslint-disable no-undef */
'use client'
import { useState, useEffect } from 'react'
export function ClientValue() {
const [serverVar, setServerVar] = useState('<loading>')
// Use `useEffect` to only evaluate this in the actual browser as client
// components are still SSRed
useEffect(() => {
setServerVar(
typeof MY_SERVER_VARIABLE === 'string' ? MY_SERVER_VARIABLE : 'not set'
)
}, [setServerVar])
return <>{serverVar}</>
}
export function ClientExpr() {
const [serverExpr, setServerExpr] = useState('<loading>')
useEffect(() => {
setServerExpr(
typeof process.env.MY_MAGIC_SERVER_EXPR === 'string'
? process.env.MY_MAGIC_SERVER_EXPR
: 'not set'
)
}, [setServerExpr])
return <>{serverExpr}</>
}
/* eslint-disable no-undef */
import { ClientValue, ClientExpr } from './client-component'
export default function Page() {
return (
<ul>
<li>
Server value:{' '}
{typeof MY_SERVER_VARIABLE === 'string'
? MY_SERVER_VARIABLE
: 'not set'}
</li>
<li>
Client value: <ClientValue />
</li>
<li>
Server expr:{' '}
{typeof process.env.MY_MAGIC_SERVER_EXPR === 'string'
? process.env.MY_MAGIC_SERVER_EXPR
: 'not set'}
</li>
<li>
Client expr: <ClientExpr />
</li>
</ul>
)
}
......@@ -5,17 +5,55 @@ describe('compiler.define', () => {
files: __dirname,
})
it('should render the magic variable on server side', async () => {
const res = await next.fetch('/')
const html = (await res.text()).replaceAll(/<!-- -->/g, '')
expect(html).toContain('Server value: foobar')
expect(html).toContain('Client value: foobar')
describe('compiler.define', () => {
let loadedText
beforeEach(async () => {
let browser = await next.browser('/')
loadedText = await browser.elementByCss('body').text()
})
it('should render the magic variable on server side', async () => {
expect(loadedText).toContain('Server value: foobar')
expect(loadedText).toContain('Client value: foobar')
})
it('should render the magic variable on client side', async () => {
expect(loadedText).toContain('Server value: foobar')
expect(loadedText).toContain('Client value: foobar')
})
it('should render the magic expression on server side', async () => {
expect(loadedText).toContain('Server expr: barbaz')
expect(loadedText).toContain('Client expr: barbaz')
})
it('should render the magic expression on client side', async () => {
expect(loadedText).toContain('Server expr: barbaz')
expect(loadedText).toContain('Client expr: barbaz')
})
})
it('should render the magic variable on client side', async () => {
const browser = await next.browser('/')
const text = await browser.elementByCss('body').text()
expect(text).toContain('Server value: foobar')
expect(text).toContain('Client value: foobar')
describe('compiler.defineServer', () => {
let loadedText
beforeEach(async () => {
let browser = await next.browser('/with-server-only')
loadedText = await browser.elementByCss('body').text()
})
it('should render the inlined variable on server side', async () => {
expect(loadedText).toContain('Server value: server')
})
it('should not render the inlined variable on client side', async () => {
expect(loadedText).toContain('Client value: not set')
})
it('should render the inlined expression on server side', async () => {
expect(loadedText).toContain('Server expr: serverbarbaz')
})
it('should not render the inlined expression on client side', async () => {
expect(loadedText).toContain('Client expr: not set')
})
})
})
......@@ -2,6 +2,11 @@ module.exports = {
compiler: {
define: {
MY_MAGIC_VARIABLE: 'foobar',
'process.env.MY_MAGIC_EXPR': 'barbaz',
},
defineServer: {
MY_SERVER_VARIABLE: 'server',
'process.env.MY_MAGIC_SERVER_EXPR': 'serverbarbaz',
},
},
}
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