Commit 84c944c4 authored by Josh Story's avatar Josh Story

Introduce __NEXT_INVARIANTS__ for process-level config values

Builds on the loadConfigFromFile/loadConfigForBuildWorker refactor to add __NEXT_INVARIANTS__ — a flat, frozen global object of pre-processed config values that never change after startup. This eliminates the pattern of threading values like trailingSlash through renderOpts → closures → function parameters when they're actually process-level constants.

__NEXT_INVARIANTS__ works identically in all contexts without the author needing to think about which one they're in. In client and server bundles, __NEXT_INVARIANTS__.trailingSlash is statically replaced with the literal value by defineEnv at compile time, enabling dead code elimination. In external (non-bundled) server code, the bare identifier resolves to the real frozen object on globalThis at runtime.

A Proxy sentinel is installed in node-environment-baseline.ts that throws if any property is accessed before config is resolved, catching ordering bugs early.

Initialization happens inside loadConfigFromFile and loadConfigForBuildWorker — no consumer needs to call it manually. It's idempotent (first call wins) so redundant calls are harmless.

The defineEnv entries are generated automatically by iterating Object.keys(__NEXT_INVARIANTS__). Adding a new invariant property to NextInvariants and initializeNextInvariants is sufficient — no manual defineEnv wiring needed.

All values must be JSON-serializable. The NextInvariants interface has an index signature constraint that produces a compile error if someone adds a non-serializable property like RegExp or Map.

The type declaration is in an internal-only src/next-invariants.d.ts included in the framework's tsconfig but not published to users via the next package types.

Initial properties: isDevServer, trailingSlash, experimentalOptimisticRouting.

As a first consumer, trailingSlash is migrated out of MetadataContext. resolve-url.ts reads __NEXT_INVARIANTS__.trailingSlash directly instead of receiving it through the closure chain, removing trailingSlash from MetadataContext, createMetadataContext, and the renderOpts dependency.

Tests:

Unit tests verify: Proxy sentinel throws on read/write before initialization, initialization produces correct frozen values, idempotency.

E2e tests with non-default config (trailingSlash: true, experimental.optimisticRouting: true) verify:
  - Self-enforcing fixture parity — client component files in app/invariants/ must exactly match the keys of NextInvariants, so adding a new invariant without a test component fails
  - SSR and browser hydration render correct values in client components (proves client bundle defineEnv replacement)
  - SSR renders correct values in server components (proves server bundle defineEnv replacement)
  - An external package using destructuring reads correct values from the runtime global (proves the globalThis path works for non-bundled code)
  - Production bundle scan confirms no __NEXT_INVARIANTS__ string survives in any client or server JS file
parent d75ddba2
......@@ -1068,5 +1068,7 @@
"1067": "The Next.js unhandled rejection filter is being installed more than once. This is a bug in Next.js.",
"1068": "Expected workStore to be initialized",
"1069": "Invariant: cache entry \"%s\" not found in dir \"%s\"",
"1070": "image of size %s could not be tracked by lru cache"
"1070": "image of size %s could not be tracked by lru cache",
"1071": "Cannot assign to __NEXT_INVARIANTS__.%s directly, use initializeNextInvariants()",
"1072": "__NEXT_INVARIANTS__.%s was accessed before initialization"
}
......@@ -371,6 +371,17 @@ export function getDefineEnv({
'process.env.__NEXT_CACHE_LIFE': config.cacheLife,
'process.env.__NEXT_CLIENT_PARAM_PARSING_ORIGINS':
config.experimental.clientParamParsingOrigins || [],
// __NEXT_INVARIANTS__ — automatically generate defineEnv entries for
// every property on the initialized global. Adding a new property to
// NextInvariants and initializeNextInvariants is sufficient — no manual
// defineEnv wiring needed.
...Object.fromEntries(
Object.keys(__NEXT_INVARIANTS__).map((key) => [
`__NEXT_INVARIANTS__.${key}`,
__NEXT_INVARIANTS__[key as keyof typeof __NEXT_INVARIANTS__],
])
),
}
const userDefines = config.compiler?.define ?? {}
......
import type { AppRenderContext } from '../../server/app-render/app-render'
import type { MetadataContext } from './types/resolvers'
export function createMetadataContext(
renderOpts: AppRenderContext['renderOpts']
): MetadataContext {
export function createMetadataContext(): MetadataContext {
return {
trailingSlash: renderOpts.trailingSlash,
isStaticMetadataRouteFile: false,
}
}
......@@ -4,6 +4,11 @@ import {
} from './resolve-metadata'
import type { MetadataItems as FullMetadataItems } from './resolve-metadata'
import type { Metadata, Viewport } from './types/metadata-interface'
import { setNextInvariantsForTest } from './test-utils'
beforeAll(() => {
setNextInvariantsForTest()
})
type FullMetadataItem = FullMetadataItems[number]
type MetadataItems = [FullMetadataItem[0], FullMetadataItem[1]][]
......@@ -16,7 +21,6 @@ function accumulateMetadata(metadataItems: MetadataItems) {
const route = '/test'
const pathname = Promise.resolve('/test')
return originAccumulateMetadata(route, fullMetadataItems, pathname, {
trailingSlash: false,
isStaticMetadataRouteFile: false,
})
}
......
import { resolveImages, resolveOpenGraph } from './resolve-opengraph'
import { setNextInvariantsForTest } from '../test-utils'
beforeAll(() => {
setNextInvariantsForTest()
})
describe('resolveImages', () => {
const image1 = 'https://www.example.com/image1.jpg'
......@@ -47,7 +52,6 @@ describe('resolveOpenGraph', () => {
null,
pathname,
{
trailingSlash: false,
isStaticMetadataRouteFile: false,
},
''
......@@ -71,7 +75,6 @@ describe('resolveOpenGraph', () => {
null,
pathname,
{
trailingSlash: false,
isStaticMetadataRouteFile: false,
},
''
......
......@@ -3,6 +3,7 @@ import {
resolveAbsoluteUrlWithPathname,
getSocialImageMetadataBaseFallback,
} from './resolve-url'
import { setNextInvariantsForTest } from '../test-utils'
// required to be resolved as URL with resolveUrl()
describe('metadata: resolveUrl', () => {
......@@ -52,9 +53,13 @@ describe('resolveAbsoluteUrlWithPathname', () => {
const metadataBase = new URL('https://example.com/')
const pathname = '/'
const opts = {
trailingSlash: false,
isStaticMetadataRouteFile: false,
}
beforeEach(() => {
setNextInvariantsForTest({ trailingSlash: false })
})
const resolver = (url: string | URL) =>
resolveAbsoluteUrlWithPathname(url, metadataBase, pathname, opts)
it('should resolve absolute internal url', () => {
......@@ -74,9 +79,13 @@ describe('resolveAbsoluteUrlWithPathname', () => {
const metadataBase = new URL('https://example.com/')
const pathname = '/'
const opts = {
trailingSlash: true,
isStaticMetadataRouteFile: false,
}
beforeEach(() => {
setNextInvariantsForTest({ trailingSlash: true })
})
const resolver = (url: string | URL) =>
resolveAbsoluteUrlWithPathname(url, metadataBase, pathname, opts)
it('should add trailing slash to relative url', () => {
......
......@@ -104,7 +104,7 @@ function resolveAbsoluteUrlWithPathname(
url: string | URL,
metadataBase: MetadataBaseURL,
pathname: string,
{ trailingSlash }: MetadataContext
_metadataContext: MetadataContext
): string {
// Resolve url with pathname that always starts with `/`
url = resolveRelativeUrl(url, pathname)
......@@ -125,7 +125,7 @@ function resolveAbsoluteUrlWithPathname(
// Add trailing slash if it's enabled for urls matches the condition
// - Not external, same origin with metadataBase
// - Doesn't have query
if (trailingSlash && !resolvedUrl.endsWith('/')) {
if (__NEXT_INVARIANTS__.trailingSlash && !resolvedUrl.endsWith('/')) {
let isRelative = resolvedUrl.startsWith('/')
let hasQuery = resolvedUrl.includes('?')
let isExternal = false
......
import type { NextInvariants } from '../../server/next-invariants'
export function setNextInvariantsForTest(
overrides?: Partial<NextInvariants>
): void {
;(globalThis as any).__NEXT_INVARIANTS__ = Object.freeze({
isDevServer: false,
trailingSlash: false,
experimentalOptimisticRouting: false,
...overrides,
})
}
......@@ -21,6 +21,5 @@ export type AsyncFieldResolverExtraArgs<
> = (T: Data[Key], ...args: ExtraArgs) => Promise<ResolvedData[Key]>
export type MetadataContext = {
trailingSlash: boolean
isStaticMetadataRouteFile: boolean
}
// Internal type declaration for __NEXT_INVARIANTS__. This is NOT published to
// users — it's only included in the framework's tsconfig.build.json so that
// framework source code can access the typed global.
declare global {
var __NEXT_INVARIANTS__: import('./server/next-invariants').NextInvariants
}
export {}
......@@ -551,7 +551,7 @@ async function generateDynamicRSCPayload(
tree: loaderTree,
parsedQuery: query,
pathname: url.pathname,
metadataContext: createMetadataContext(ctx.renderOpts),
metadataContext: createMetadataContext(),
interpolatedParams: ctx.interpolatedParams,
serveStreamingMetadata,
isRuntimePrefetchable: metadataIsRuntimePrefetchable,
......@@ -1449,7 +1449,7 @@ async function getRSCPayload(
errorType: is404 && !hasGlobalNotFound ? 'not-found' : undefined,
parsedQuery: query,
pathname: url.pathname,
metadataContext: createMetadataContext(ctx.renderOpts),
metadataContext: createMetadataContext(),
interpolatedParams: ctx.interpolatedParams,
serveStreamingMetadata,
isRuntimePrefetchable: metadataIsRuntimePrefetchable,
......@@ -1571,7 +1571,7 @@ async function getErrorRSCPayload(
tree,
parsedQuery: query,
pathname: url.pathname,
metadataContext: createMetadataContext(ctx.renderOpts),
metadataContext: createMetadataContext(),
errorType,
interpolatedParams: ctx.interpolatedParams,
serveStreamingMetadata: serveStreamingMetadata,
......
......@@ -13,6 +13,7 @@ import {
type PHASE_TYPE,
} from '../shared/lib/constants'
import { defaultConfig, normalizeConfig } from './config-shared'
import { initializeNextInvariants } from './next-invariants'
import type {
ExperimentalConfig,
NextConfigComplete,
......@@ -1502,6 +1503,7 @@ export default async function loadConfigFromFile(
opts: LoadConfigOptions = {}
): Promise<NextConfigComplete> {
const config = await loadConfigImpl(phase, dir, opts)
initializeNextInvariants(config, phase === PHASE_DEVELOPMENT_SERVER)
const { installGlobalBehaviors } =
require('./node-environment-extensions/global-behaviors') as typeof import('./node-environment-extensions/global-behaviors')
installGlobalBehaviors(config)
......@@ -1509,13 +1511,14 @@ export default async function loadConfigFromFile(
}
/**
* Initialize global behaviors from a pre-resolved config received via IPC
* in a build worker process. The parent process already loaded and serialized
* the config — this sets up the worker's globals.
* Initialize invariants and global behaviors from a pre-resolved config
* received via IPC in a build worker process. The parent process already
* loaded and serialized the config — this sets up the worker's globals.
*/
export function loadConfigForBuildWorker(
config: NextConfigComplete
): NextConfigComplete {
initializeNextInvariants(config, false)
const { installGlobalBehaviors } =
require('./node-environment-extensions/global-behaviors') as typeof import('./node-environment-extensions/global-behaviors')
installGlobalBehaviors(config)
......
/**
* @jest-environment node
*/
describe('__NEXT_INVARIANTS__', () => {
function loadFreshModules() {
let invariantsMod: typeof import('./next-invariants')
jest.isolateModules(() => {
// Install the real Proxy sentinel from node-environment-baseline
delete (globalThis as any).__NEXT_INVARIANTS__
// eslint-disable-next-line @next/internal/typechecked-require -- side-effect-only module, no exports to type
require('./node-environment-baseline')
invariantsMod =
require('./next-invariants') as typeof import('./next-invariants')
})
return invariantsMod!
}
afterEach(() => {
delete (globalThis as any).__NEXT_INVARIANTS__
})
describe('Proxy sentinel', () => {
it('throws when reading a property before initialization', () => {
loadFreshModules()
expect(() => {
// eslint-disable-next-line @typescript-eslint/no-unused-expressions
;(globalThis as any).__NEXT_INVARIANTS__.trailingSlash
}).toThrow('trailingSlash was accessed before initialization')
})
it('throws when writing a property before initialization', () => {
loadFreshModules()
expect(() => {
;(globalThis as any).__NEXT_INVARIANTS__.trailingSlash = true
}).toThrow('Cannot assign to __NEXT_INVARIANTS__.trailingSlash directly')
})
})
describe('initializeNextInvariants', () => {
it('replaces the sentinel with the real frozen object', () => {
const { initializeNextInvariants } = loadFreshModules()
initializeNextInvariants(
{
trailingSlash: true,
experimental: { optimisticRouting: true },
} as any,
false
)
const invariants = (globalThis as any).__NEXT_INVARIANTS__
expect(invariants.isDevServer).toBe(false)
expect(invariants.trailingSlash).toBe(true)
expect(invariants.experimentalOptimisticRouting).toBe(true)
})
it('freezes the resulting object', () => {
const { initializeNextInvariants } = loadFreshModules()
initializeNextInvariants(
{ trailingSlash: false, experimental: {} } as any,
false
)
const invariants = (globalThis as any).__NEXT_INVARIANTS__
expect(Object.isFrozen(invariants)).toBe(true)
})
it('is idempotent — first call wins, subsequent calls are no-ops', () => {
const { initializeNextInvariants } = loadFreshModules()
initializeNextInvariants(
{ trailingSlash: true, experimental: {} } as any,
true
)
// Second call with different values should be a no-op
initializeNextInvariants(
{ trailingSlash: false, experimental: {} } as any,
false
)
const invariants = (globalThis as any).__NEXT_INVARIANTS__
// First call's values should win
expect(invariants.isDevServer).toBe(true)
expect(invariants.trailingSlash).toBe(true)
})
})
})
/**
* Process-level configuration values that are set once at startup and never
* change. In bundled code, `__NEXT_INVARIANTS__.trailingSlash` etc. are
* statically replaced by defineEnv at compile time. In external (non-bundled)
* server code, the bare identifier resolves to the frozen object on globalThis.
*
* A Proxy sentinel is installed early in node-environment-baseline.ts that
* throws if any property is accessed before `initializeNextInvariants` is
* called. This catches ordering bugs where external code tries to read config
* before the server or build has resolved it.
*/
import type { NextConfigRuntime } from './config-shared'
// All invariant values must be JSON-serializable so defineEnv can statically
// replace them in bundled code. The index signature enforces this at compile
// time — adding a non-serializable property (RegExp, Map, function, etc.)
// will produce a type error.
type JsonSerializableValue =
| string
| number
| boolean
| null
| JsonSerializableValue[]
| { readonly [key: string]: JsonSerializableValue }
export interface NextInvariants {
readonly [key: string]: JsonSerializableValue
readonly isDevServer: boolean
readonly trailingSlash: boolean
readonly experimentalOptimisticRouting: boolean
}
let initialized = false
/**
* Replace the Proxy sentinel on globalThis with the real frozen config object.
* Idempotent — the first call wins, subsequent calls are no-ops. This allows
* multiple entry points (getDefineEnv, NextNodeServer, export worker) to call
* it without worrying about ordering.
*/
export function initializeNextInvariants(
config: NextConfigRuntime,
isDevServer: boolean
): void {
if (initialized) {
return
}
initialized = true
;(globalThis as any).__NEXT_INVARIANTS__ = Object.freeze({
isDevServer,
trailingSlash: config.trailingSlash,
experimentalOptimisticRouting:
config.experimental.optimisticRouting ?? false,
})
}
......@@ -8,6 +8,25 @@ if (typeof (globalThis as any).AsyncLocalStorage !== 'function') {
;(globalThis as any).AsyncLocalStorage = AsyncLocalStorage
}
// Install a Proxy sentinel for __NEXT_INVARIANTS__ that throws if any property
// is accessed before the config values are initialized. This catches too-early
// access during module loading before the server or build has resolved config.
;(globalThis as any).__NEXT_INVARIANTS__ = new Proxy(
{},
{
get(_target, prop) {
throw new Error(
`__NEXT_INVARIANTS__.${String(prop)} was accessed before initialization`
)
},
set(_target, prop) {
throw new Error(
`Cannot assign to __NEXT_INVARIANTS__.${String(prop)} directly, use initializeNextInvariants()`
)
},
}
)
if (typeof (globalThis as any).WebSocket !== 'function') {
Object.defineProperty(globalThis, 'WebSocket', {
configurable: true,
......
// @ts-expect-error -- local test package, no types
import { getInvariants } from 'invariants-external-package'
// Server component that reads invariants from an external (non-bundled) package.
// The external package reads from the runtime global on globalThis, not via
// defineEnv static replacement.
export default function ExternalPage() {
const invariants = getInvariants()
return (
<dl>
<dt>isDevServer</dt>
<dd id="external-isDevServer">{String(invariants.isDevServer)}</dd>
<dt>trailingSlash</dt>
<dd id="external-trailingSlash">{String(invariants.trailingSlash)}</dd>
<dt>experimentalOptimisticRouting</dt>
<dd id="external-experimentalOptimisticRouting">
{String(invariants.experimentalOptimisticRouting)}
</dd>
</dl>
)
}
'use client'
export default function ExperimentalOptimisticRouting() {
return (
<dd id="experimentalOptimisticRouting">
{String(__NEXT_INVARIANTS__.experimentalOptimisticRouting)}
</dd>
)
}
'use client'
export default function IsDevServer() {
return <dd id="isDevServer">{String(__NEXT_INVARIANTS__.isDevServer)}</dd>
}
'use client'
export default function TrailingSlash() {
return <dd id="trailingSlash">{String(__NEXT_INVARIANTS__.trailingSlash)}</dd>
}
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import IsDevServer from './invariants/isDevServer'
import TrailingSlash from './invariants/trailingSlash'
import ExperimentalOptimisticRouting from './invariants/experimentalOptimisticRouting'
export default function Page() {
return (
<dl>
<IsDevServer />
<TrailingSlash />
<ExperimentalOptimisticRouting />
</dl>
)
}
// Server component that references every __NEXT_INVARIANTS__ property.
// Used by the test to verify defineEnv replacement in server bundles.
export default function ServerPage() {
return (
<dl>
<dt>isDevServer</dt>
<dd id="server-isDevServer">{String(__NEXT_INVARIANTS__.isDevServer)}</dd>
<dt>trailingSlash</dt>
<dd id="server-trailingSlash">
{String(__NEXT_INVARIANTS__.trailingSlash)}
</dd>
<dt>experimentalOptimisticRouting</dt>
<dd id="server-experimentalOptimisticRouting">
{String(__NEXT_INVARIANTS__.experimentalOptimisticRouting)}
</dd>
</dl>
)
}
// Type declaration for the test fixture. This is normally internal to the
// Next.js framework and not exposed to user code.
interface NextInvariants {
readonly [key: string]: string | number | boolean | null
readonly isDevServer: boolean
readonly trailingSlash: boolean
readonly experimentalOptimisticRouting: boolean
}
declare var __NEXT_INVARIANTS__: NextInvariants
import path from 'path'
import fs from 'fs'
import { nextTestSetup } from 'e2e-utils'
import { recursiveReadDir } from 'next/dist/lib/recursive-readdir'
import { initializeNextInvariants } from 'next/dist/server/next-invariants'
describe('next-invariants', () => {
const { next, isNextDev, isNextStart } = nextTestSetup({
files: __dirname,
})
// Initialize invariants in the test process to get the canonical key set.
// This is the source of truth — if a new key is added to NextInvariants,
// it will appear here and the test will fail until a corresponding client
// component file is created in app/invariants/.
initializeNextInvariants(
{ trailingSlash: false, experimental: {} } as any,
false
)
const invariantKeys = Object.keys(
(globalThis as any).__NEXT_INVARIANTS__
).sort()
it('should have a client component for every invariant key and no extras', () => {
const invariantsDir = path.join(__dirname, 'app', 'invariants')
const files = fs.readdirSync(invariantsDir)
const componentKeys = files
.filter((f) => f.endsWith('.tsx'))
.map((f) => f.replace('.tsx', ''))
.sort()
expect(componentKeys).toEqual(invariantKeys)
})
// SSR verifies server-side rendering works for both component types.
it('should SSR the replaced values in client components', async () => {
const $ = await next.render$('/')
expect($('#isDevServer').text()).toBe(String(isNextDev))
expect($('#trailingSlash').text()).toBe('true')
expect($('#experimentalOptimisticRouting').text()).toBe('true')
})
it('should SSR the replaced values in server components', async () => {
const $ = await next.render$('/server')
expect($('#server-isDevServer').text()).toBe(String(isNextDev))
expect($('#server-trailingSlash').text()).toBe('true')
expect($('#server-experimentalOptimisticRouting').text()).toBe('true')
})
// Browser test verifies client JS hydrates without ReferenceError.
// If defineEnv didn't replace __NEXT_INVARIANTS__ in the client bundle,
// the browser would throw because the identifier doesn't exist on the
// client globalThis.
it('should hydrate client components in the browser', async () => {
const browser = await next.browser('/')
expect(await browser.elementByCss('#isDevServer').text()).toBe(
String(isNextDev)
)
expect(await browser.elementByCss('#trailingSlash').text()).toBe('true')
expect(
await browser.elementByCss('#experimentalOptimisticRouting').text()
).toBe('true')
})
// Verifies the runtime global works for non-bundled (external) server code.
// The external package reads __NEXT_INVARIANTS__ from globalThis, not via
// defineEnv replacement.
it('should read invariants from the runtime global in external packages', async () => {
const $ = await next.render$('/external')
expect($('#external-isDevServer').text()).toBe(String(isNextDev))
expect($('#external-trailingSlash').text()).toBe('true')
expect($('#external-experimentalOptimisticRouting').text()).toBe('true')
})
if (isNextStart) {
it('should not have any __NEXT_INVARIANTS__ references in client bundles', async () => {
const staticDir = path.join(next.testDir, '.next', 'static')
const allFiles = await recursiveReadDir(staticDir)
const jsFiles = allFiles.filter((file) => file.endsWith('.js'))
expect(jsFiles.length).toBeGreaterThan(0)
for (const file of jsFiles) {
const content = fs.readFileSync(path.join(staticDir, file), 'utf8')
expect(content).not.toContain('__NEXT_INVARIANTS__')
}
})
it('should not have any __NEXT_INVARIANTS__ references in server bundles', async () => {
// Load /server to ensure the server component bundle exists
await next.render$('/server')
const serverAppDir = path.join(next.testDir, '.next', 'server', 'app')
const allFiles = await recursiveReadDir(serverAppDir)
const jsFiles = allFiles.filter((file) => file.endsWith('.js'))
expect(jsFiles.length).toBeGreaterThan(0)
for (const file of jsFiles) {
const content = fs.readFileSync(path.join(serverAppDir, file), 'utf8')
expect(content).not.toContain('__NEXT_INVARIANTS__')
}
})
}
})
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
trailingSlash: true,
experimental: {
optimisticRouting: true,
},
serverExternalPackages: ['invariants-external-package'],
}
module.exports = nextConfig
// This module is configured as a serverExternalPackage so it is NOT processed
// by the bundler. It reads __NEXT_INVARIANTS__ from the runtime global on
// globalThis, not via defineEnv static replacement.
//
// Destructuring proves this is reading from the runtime global object — defineEnv
// only replaces full member expressions like __NEXT_INVARIANTS__.trailingSlash,
// not the bare __NEXT_INVARIANTS__ identifier used in destructuring.
module.exports.getInvariants = function getInvariants() {
const { isDevServer, trailingSlash, experimentalOptimisticRouting } =
__NEXT_INVARIANTS__
return { isDevServer, trailingSlash, experimentalOptimisticRouting }
}
{
"name": "invariants-external-package",
"version": "1.0.0",
"main": "index.js"
}
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