Unverified Commit d3e41fb4 authored by Niklas Mischkulnig's avatar Niklas Mischkulnig Committed by GitHub

Move outputHashSalt out of experimental (#95840)

Keep reading `config.experimental.outputHashSalt` for now to not break
existing adapters until they are migrated.
parent 756d6dc9
...@@ -149,6 +149,10 @@ pub struct NextConfig { ...@@ -149,6 +149,10 @@ pub struct NextConfig {
/// [API Reference](https://nextjs.org/docs/app/api-reference/next-config-js/serverExternalPackages) /// [API Reference](https://nextjs.org/docs/app/api-reference/next-config-js/serverExternalPackages)
server_external_packages: Option<Vec<RcStr>>, server_external_packages: Option<Vec<RcStr>>,
/// A salt to mix into chunk and asset content hashes. Empty string means
/// no salt.
output_hash_salt: Option<RcStr>,
#[serde(rename = "_originalRedirects")] #[serde(rename = "_originalRedirects")]
original_redirects: Option<Vec<Redirect>>, original_redirects: Option<Vec<Redirect>>,
...@@ -1294,10 +1298,6 @@ pub struct ExperimentalConfig { ...@@ -1294,10 +1298,6 @@ pub struct ExperimentalConfig {
runtime_server_deployment_id: Option<bool>, runtime_server_deployment_id: Option<bool>,
expose_testing_api_in_production_build: Option<bool>, expose_testing_api_in_production_build: Option<bool>,
/// A salt to mix into chunk and asset content hashes. Empty string means
/// no salt.
output_hash_salt: Option<RcStr>,
/// CSS chunking strategy. See [`CssChunkingConfig`] for the accepted shapes. /// CSS chunking strategy. See [`CssChunkingConfig`] for the accepted shapes.
css_chunking: Option<CssChunkingConfig>, css_chunking: Option<CssChunkingConfig>,
...@@ -2749,12 +2749,7 @@ impl NextConfig { ...@@ -2749,12 +2749,7 @@ impl NextConfig {
#[turbo_tasks::function] #[turbo_tasks::function]
pub fn output_hash_salt(&self) -> Vc<RcStr> { pub fn output_hash_salt(&self) -> Vc<RcStr> {
Vc::cell( Vc::cell(self.output_hash_salt.clone().unwrap_or_default())
self.experimental
.output_hash_salt
.clone()
.unwrap_or_default(),
)
} }
} }
......
--- ---
title: outputHashSalt title: outputHashSalt
description: Learn how to incorporate a custom salt string into content-addressed output filenames. description: Learn how to incorporate a custom salt string into content-addressed output filenames.
version: experimental
--- ---
`outputHashSalt` is an experimental option that incorporates a configurable salt string into every content-addressed output filename (chunks, assets). Changing this value forces all output hashes to change, which is useful for invalidating cached assets across deployments without modifying source files. `outputHashSalt` is an option that incorporates a configurable salt string into every content-addressed output filename (chunks, assets). Changing this value forces all output hashes to change, which is useful for invalidating cached assets across deployments without modifying source files.
To configure the output hash salt, set `experimental.outputHashSalt` in `next.config.js`: To configure the output hash salt, set `outputHashSalt` in `next.config.js`:
```js filename="next.config.js" ```js filename="next.config.js"
/** @type {import('next').NextConfig} */ /** @type {import('next').NextConfig} */
const nextConfig = { const nextConfig = {
experimental: {
outputHashSalt: 'my-deployment-salt', outputHashSalt: 'my-deployment-salt',
},
} }
module.exports = nextConfig module.exports = nextConfig
...@@ -21,7 +18,7 @@ module.exports = nextConfig ...@@ -21,7 +18,7 @@ module.exports = nextConfig
This works with both Webpack and Turbopack bundlers. This works with both Webpack and Turbopack bundlers.
The `NEXT_HASH_SALT` environment variable can also be used for the same purpose. When both are set, the values are **concatenated** (`experimental.outputHashSalt + NEXT_HASH_SALT`) to form the effective salt. This lets you combine a per-project salt baked into the config with a per-deployment salt injected at build time via environment variable. The `NEXT_HASH_SALT` environment variable can also be used for the same purpose. When both are set, the values are **concatenated** (`outputHashSalt + NEXT_HASH_SALT`) to form the effective salt. This lets you combine a per-project salt baked into the config with a per-deployment salt injected at build time via environment variable.
```bash filename="Terminal" ```bash filename="Terminal"
NEXT_HASH_SALT=my-deployment-salt next build NEXT_HASH_SALT=my-deployment-salt next build
...@@ -30,5 +27,5 @@ NEXT_HASH_SALT=my-deployment-salt next build ...@@ -30,5 +27,5 @@ NEXT_HASH_SALT=my-deployment-salt next build
## Version History ## Version History
| Version | Changes | | Version | Changes |
| -------- | ---------------------------------------- | | -------- | --------------------------- |
| `16.3.0` | `experimental.outputHashSalt` was added. | | `16.3.0` | `outputHashSalt` was added. |
...@@ -9,7 +9,7 @@ When `config.supportsImmutableAssets` is enabled, Next.js outputs immutable cont ...@@ -9,7 +9,7 @@ When `config.supportsImmutableAssets` is enabled, Next.js outputs immutable cont
At runtime, these immutable static assets are requested without the `?dpl` query parameter and thus live in a shared namespace across deployments. You must ensure that these assets are immutable and not changed (even after a new deployment) or deleted (for as long as there are active deployments using them) . Next.js may use a truncated shorter content hash as the filename, so `outputs.staticFiles[].immutableHash` contains the full content hash which can be used to validate that no hash collision occurred. At runtime, these immutable static assets are requested without the `?dpl` query parameter and thus live in a shared namespace across deployments. You must ensure that these assets are immutable and not changed (even after a new deployment) or deleted (for as long as there are active deployments using them) . Next.js may use a truncated shorter content hash as the filename, so `outputs.staticFiles[].immutableHash` contains the full content hash which can be used to validate that no hash collision occurred.
You can use `config.experimental.outputHashSalt` to set a salt for the content hashes, if you want to rotate the hashes for any reason (e.g. after a detected hash collision). You can use `config.outputHashSalt` to set a salt for the content hashes, if you want to rotate the hashes for any reason (e.g. after a detected hash collision).
Note that you need to continue supporting non-immutable static assets (which may change between deployments and continue to be requested with the `?dpl` query parameter), e.g. for the `public` folder or for older Next.js versions. Note that you need to continue supporting non-immutable static assets (which may change between deployments and continue to be requested with the `?dpl` query parameter), e.g. for the `public` folder or for older Next.js versions.
...@@ -32,7 +32,7 @@ const adapter = { ...@@ -32,7 +32,7 @@ const adapter = {
config.supportsImmutableAssets ?? true config.supportsImmutableAssets ?? true
// Optionally, pass a salt for the content hashes // Optionally, pass a salt for the content hashes
// config.experimental.outputHashSalt = getSaltForCurrentProject() // config.outputHashSalt = getSaltForCurrentProject()
} }
return config return config
}, },
......
...@@ -1046,7 +1046,7 @@ export async function handleBuildComplete({ ...@@ -1046,7 +1046,7 @@ export async function handleBuildComplete({
path.relative(repoRoot, pageFile), path.relative(repoRoot, pageFile),
pageFile, pageFile,
bundler, bundler,
config.experimental.outputHashSalt || '' config.outputHashSalt || ''
) )
continue continue
} }
...@@ -2170,7 +2170,7 @@ async function getSharedNodeAssets({ ...@@ -2170,7 +2170,7 @@ async function getSharedNodeAssets({
const pagesSharedNodeAssetsHashes: Record<string, string> = {} const pagesSharedNodeAssetsHashes: Record<string, string> = {}
const appPagesSharedNodeAssets: Record<string, string> = {} const appPagesSharedNodeAssets: Record<string, string> = {}
const appPagesSharedNodeAssetsHashes: Record<string, string> = {} const appPagesSharedNodeAssetsHashes: Record<string, string> = {}
const salt = config.experimental.outputHashSalt || '' const salt = config.outputHashSalt || ''
const moduleTypes = ['app-page', 'pages'] as const const moduleTypes = ['app-page', 'pages'] as const
......
...@@ -1371,9 +1371,7 @@ export default async function getBaseWebpackConfig( ...@@ -1371,9 +1371,7 @@ export default async function getBaseWebpackConfig(
hashDigestLength: 16, hashDigestLength: 16,
// Webpack requires hashSalt to be a non-empty string; omit it entirely // Webpack requires hashSalt to be a non-empty string; omit it entirely
// when no salt is configured. // when no salt is configured.
...(config.experimental?.outputHashSalt ...(config.outputHashSalt ? { hashSalt: config.outputHashSalt } : {}),
? { hashSalt: config.experimental.outputHashSalt }
: {}),
}, },
performance: false, performance: false,
resolve: resolveConfig, resolve: resolveConfig,
...@@ -1821,7 +1819,7 @@ export default async function getBaseWebpackConfig( ...@@ -1821,7 +1819,7 @@ export default async function getBaseWebpackConfig(
compilerType, compilerType,
basePath: config.basePath, basePath: config.basePath,
assetPrefix: config.assetPrefix, assetPrefix: config.assetPrefix,
outputHashSalt: config.experimental?.outputHashSalt, outputHashSalt: config.outputHashSalt,
}, },
}, },
] ]
......
...@@ -595,6 +595,7 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() => ...@@ -595,6 +595,7 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
.optional(), .optional(),
deploymentId: z.string().optional(), deploymentId: z.string().optional(),
supportsImmutableAssets: z.boolean().optional(), supportsImmutableAssets: z.boolean().optional(),
outputHashSalt: z.string().optional(),
devIndicators: z devIndicators: z
.union([ .union([
z.object({ z.object({
......
...@@ -467,13 +467,7 @@ export function resolveCssChunkingMode( ...@@ -467,13 +467,7 @@ export function resolveCssChunkingMode(
export interface ExperimentalConfig { export interface ExperimentalConfig {
/** /**
* A string that is incorporated into content-addressed output filenames * @deprecated Use the top-level `outputHashSalt` option instead.
* (chunks, assets) for both Webpack and Turbopack. Changing this value
* forces all output hashes to change, which is useful for invalidating
* cached assets across deployments without modifying source files.
*
* When `NEXT_HASH_SALT` environment variable is also set, the two values are
* concatenated (`outputHashSalt + NEXT_HASH_SALT`) to form the effective salt.
*/ */
outputHashSalt?: string outputHashSalt?: string
...@@ -1972,6 +1966,17 @@ export interface NextConfig { ...@@ -1972,6 +1966,17 @@ export interface NextConfig {
*/ */
outputFileTracingIncludes?: Record<string, string[]> outputFileTracingIncludes?: Record<string, string[]>
/**
* A string that is incorporated into content-addressed output filenames
* (chunks, assets) for both Webpack and Turbopack. Changing this value
* forces all output hashes to change, which is useful for invalidating
* cached assets across deployments without modifying source files.
*
* When `NEXT_HASH_SALT` environment variable is also set, the two values are
* concatenated (`outputHashSalt + NEXT_HASH_SALT`) to form the effective salt.
*/
outputHashSalt?: string
watchOptions?: { watchOptions?: {
pollIntervalMs?: number pollIntervalMs?: number
} }
......
...@@ -1150,8 +1150,8 @@ function assignDefaultsAndValidate( ...@@ -1150,8 +1150,8 @@ function assignDefaultsAndValidate(
} }
if (process.env.NEXT_HASH_SALT) { if (process.env.NEXT_HASH_SALT) {
result.experimental.outputHashSalt = result.outputHashSalt =
(result.experimental.outputHashSalt ?? '') + process.env.NEXT_HASH_SALT (result.outputHashSalt ?? '') + (process.env.NEXT_HASH_SALT ?? '')
} }
const tracingRoot = result?.outputFileTracingRoot const tracingRoot = result?.outputFileTracingRoot
...@@ -1681,6 +1681,11 @@ function finalizeConfig( ...@@ -1681,6 +1681,11 @@ function finalizeConfig(
config.supportsImmutableAssets = false config.supportsImmutableAssets = false
} }
if (config.experimental.outputHashSalt !== undefined) {
config.outputHashSalt =
(config.outputHashSalt ?? '') + config.experimental.outputHashSalt
}
return config return config
} }
......
...@@ -72,7 +72,7 @@ describe('NEXT_HASH_SALT', () => { ...@@ -72,7 +72,7 @@ describe('NEXT_HASH_SALT', () => {
}) })
}) })
describe('experimental.outputHashSalt', () => { describe('outputHashSalt', () => {
// Uses the fixture's next.config.js which reads OUTPUT_HASH_SALT_CONFIG from env, // Uses the fixture's next.config.js which reads OUTPUT_HASH_SALT_CONFIG from env,
// allowing multiple builds with different config salts from a single next instance. // allowing multiple builds with different config salts from a single next instance.
const { next } = nextTestSetup({ const { next } = nextTestSetup({
...@@ -83,11 +83,14 @@ describe('experimental.outputHashSalt', () => { ...@@ -83,11 +83,14 @@ describe('experimental.outputHashSalt', () => {
async function buildWithSalts(opts: { async function buildWithSalts(opts: {
configSalt?: string configSalt?: string
envSalt?: string envSalt?: string
experimentalAdapterSalt?: string
adapterSalt?: string adapterSalt?: string
}) { }) {
const env: Record<string, string> = {} const env: Record<string, string> = {}
if (opts.configSalt) env.OUTPUT_HASH_SALT_CONFIG = opts.configSalt if (opts.configSalt) env.OUTPUT_HASH_SALT_CONFIG = opts.configSalt
if (opts.envSalt) env.NEXT_HASH_SALT = opts.envSalt if (opts.envSalt) env.NEXT_HASH_SALT = opts.envSalt
if (opts.experimentalAdapterSalt)
env.EXPERIMENTAL_OUTPUT_HASH_SALT_CONFIG = opts.experimentalAdapterSalt
if (opts.adapterSalt) env.ADAPTER_HASH_SALT = opts.adapterSalt if (opts.adapterSalt) env.ADAPTER_HASH_SALT = opts.adapterSalt
await next.clean() await next.clean()
await next.build({ env }) await next.build({ env })
...@@ -99,6 +102,7 @@ describe('experimental.outputHashSalt', () => { ...@@ -99,6 +102,7 @@ describe('experimental.outputHashSalt', () => {
let noSaltChunks: string[] let noSaltChunks: string[]
let configOnlyChunks: string[] let configOnlyChunks: string[]
let experimentalAdapterChunks: string[]
let envOnlyChunks: string[] let envOnlyChunks: string[]
let adapterEnvOnlyChunks: string[] let adapterEnvOnlyChunks: string[]
let configAndEnvChunks: string[] let configAndEnvChunks: string[]
...@@ -109,6 +113,9 @@ describe('experimental.outputHashSalt', () => { ...@@ -109,6 +113,9 @@ describe('experimental.outputHashSalt', () => {
async () => { async () => {
noSaltChunks = await buildWithSalts({}) noSaltChunks = await buildWithSalts({})
configOnlyChunks = await buildWithSalts({ configSalt: 'config-salt' }) configOnlyChunks = await buildWithSalts({ configSalt: 'config-salt' })
experimentalAdapterChunks = await buildWithSalts({
experimentalAdapterSalt: 'experimental-adapter-salt',
})
envOnlyChunks = await buildWithSalts({ envSalt: 'env-salt' }) envOnlyChunks = await buildWithSalts({ envSalt: 'env-salt' })
adapterEnvOnlyChunks = await buildWithSalts({ adapterEnvOnlyChunks = await buildWithSalts({
adapterSalt: 'adapter-salt', adapterSalt: 'adapter-salt',
...@@ -147,4 +154,8 @@ describe('experimental.outputHashSalt', () => { ...@@ -147,4 +154,8 @@ describe('experimental.outputHashSalt', () => {
expect(envAndAdapterEnvChunks).not.toEqual(envOnlyChunks) expect(envAndAdapterEnvChunks).not.toEqual(envOnlyChunks)
expect(envAndAdapterEnvChunks).not.toEqual(adapterEnvOnlyChunks) expect(envAndAdapterEnvChunks).not.toEqual(adapterEnvOnlyChunks)
}) })
it('adapter experimental config salt changes filenames compared to no salt', () => {
expect(experimentalAdapterChunks).not.toEqual(noSaltChunks)
})
}) })
...@@ -4,9 +4,13 @@ const myAdapter = { ...@@ -4,9 +4,13 @@ const myAdapter = {
name: 'my-custom-adapter', name: 'my-custom-adapter',
modifyConfig: (config) => { modifyConfig: (config) => {
if (process.env.ADAPTER_HASH_SALT != null) { if (process.env.ADAPTER_HASH_SALT != null) {
config.outputHashSalt =
(config.outputHashSalt ?? '') + process.env.ADAPTER_HASH_SALT
}
if (process.env.EXPERIMENTAL_OUTPUT_HASH_SALT_CONFIG != null) {
config.experimental.outputHashSalt = config.experimental.outputHashSalt =
(config.experimental.outputHashSalt ?? '') + (config.experimental.outputHashSalt ?? '') +
process.env.ADAPTER_HASH_SALT process.env.EXPERIMENTAL_OUTPUT_HASH_SALT_CONFIG
} }
return config return config
}, },
......
/** @type {import('next').NextConfig} */ /** @type {import('next').NextConfig} */
module.exports = { module.exports = {
experimental: {
// Allow tests to inject outputHashSalt via env var without touching source. // Allow tests to inject outputHashSalt via env var without touching source.
outputHashSalt: process.env.OUTPUT_HASH_SALT_CONFIG || undefined, outputHashSalt: process.env.OUTPUT_HASH_SALT_CONFIG || undefined,
experimental: {
outputHashSalt:
process.env.EXPERIMENTAL_OUTPUT_HASH_SALT_CONFIG || undefined,
}, },
adapterPath: require.resolve('./my-adapter.mjs'), adapterPath: require.resolve('./my-adapter.mjs'),
} }
...@@ -22006,9 +22006,9 @@ ...@@ -22006,9 +22006,9 @@
"NEXT_HASH_SALT should produce chunk files", "NEXT_HASH_SALT should produce chunk files",
"NEXT_HASH_SALT should produce css files", "NEXT_HASH_SALT should produce css files",
"NEXT_HASH_SALT should produce image files", "NEXT_HASH_SALT should produce image files",
"experimental.outputHashSalt combined salt differs from config-only salt", "outputHashSalt combined salt differs from config-only salt",
"experimental.outputHashSalt combined salt differs from env-var-only salt", "outputHashSalt combined salt differs from env-var-only salt",
"experimental.outputHashSalt config salt changes filenames compared to no salt" "outputHashSalt config salt changes filenames compared to no salt"
], ],
"failed": [], "failed": [],
"pending": [], "pending": [],
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