Unverified Commit 24c6e3e4 authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

Add CSS URL deployment ID suffix support (#89771)

## Summary

Adds deployment ID suffix (`?dpl=<deployment_id>`) to asset URLs referenced in CSS `url()` declarations (images, fonts) for both Turbopack and Webpack builds. This enables proper cache busting for CSS-referenced assets when using `deploymentId` in `next.config.js`.

### Turbopack
- Added `static_suffix` field to the existing `UrlBehavior` struct, providing a build-time constant suffix for contexts that cannot use dynamic JS expressions (e.g., CSS `url()` references)
- CSS URL resolution now calls `url_behavior(None)` and uses `static_suffix` instead of a separate method
- Wired the suffix from `next.config.js` `deploymentId` through `asset_suffix_path()` into all three chunking contexts (client, server, edge) via `default_url_behavior` and `url_behavior_override`

### Webpack
- Passed `deploymentId` through the CSS loader config pipeline (`webpack-config.ts` → `config/index.ts` → `css/loaders/` → `postcss-url-parser.ts`)
- Appended `?dpl=<id>` to resolved asset URLs in the PostCSS URL parser plugin, placed before any hash fragment so it remains a server-visible query parameter

### Test
- Added production test (`test/production/css-url-deployment-id/`) covering global CSS, CSS modules, and SCSS modules with image and font `url()` references
- Verifies all asset URLs contain the `dpl` query parameter in both Turbopack and Webpack modes
parent 2d185084
......@@ -1440,6 +1440,12 @@ impl Project {
pub(super) async fn client_chunking_context(
self: Vc<Self>,
) -> Result<Vc<Box<dyn ChunkingContext>>> {
let css_url_suffix = self
.next_config()
.asset_suffix_path()
.owned()
.await?
.clone();
Ok(get_client_chunking_context(ClientChunkingContextOptions {
mode: self.next_mode(),
root_path: self.project_root_path().owned().await?,
......@@ -1459,6 +1465,7 @@ impl Project {
.turbo_nested_async_chunking(self.next_mode(), true),
debug_ids: self.next_config().turbopack_debug_ids(),
should_use_absolute_url_references: self.next_config().inline_css(),
css_url_suffix,
}))
}
......@@ -1467,6 +1474,12 @@ impl Project {
self: Vc<Self>,
client_assets: bool,
) -> Result<Vc<NodeJsChunkingContext>> {
let css_url_suffix = self
.next_config()
.asset_suffix_path()
.owned()
.await?
.clone();
let options = ServerChunkingContextOptions {
mode: self.next_mode(),
root_path: self.project_root_path().owned().await?,
......@@ -1486,6 +1499,7 @@ impl Project {
debug_ids: self.next_config().turbopack_debug_ids(),
client_root: self.client_relative_path().owned().await?,
asset_prefix: self.next_config().computed_asset_prefix().owned().await?,
css_url_suffix,
};
Ok(if client_assets {
get_server_chunking_context_with_client_assets(options)
......@@ -1499,6 +1513,12 @@ impl Project {
self: Vc<Self>,
client_assets: bool,
) -> Result<Vc<Box<dyn ChunkingContext>>> {
let css_url_suffix = self
.next_config()
.asset_suffix_path()
.owned()
.await?
.clone();
let options = EdgeChunkingContextOptions {
mode: self.next_mode(),
root_path: self.project_root_path().owned().await?,
......@@ -1517,6 +1537,7 @@ impl Project {
.turbo_nested_async_chunking(self.next_mode(), false),
client_root: self.client_relative_path().owned().await?,
asset_prefix: self.next_config().computed_asset_prefix().owned().await?,
css_url_suffix,
};
Ok(if client_assets {
get_edge_chunking_context_with_client_assets(options)
......
......@@ -17,7 +17,7 @@ use turbopack_browser::{
use turbopack_core::{
chunk::{
AssetSuffix, ChunkingConfig, ChunkingContext, MangleType, MinifyType, SourceMapSourceType,
SourceMapsType, UnusedReferences, chunk_id_strategy::ModuleIdStrategy,
SourceMapsType, UnusedReferences, UrlBehavior, chunk_id_strategy::ModuleIdStrategy,
},
compile_time_info::{CompileTimeDefines, CompileTimeInfo, FreeVarReference, FreeVarReferences},
environment::{BrowserEnvironment, Environment, ExecutionEnvironment},
......@@ -449,6 +449,7 @@ pub struct ClientChunkingContextOptions {
pub nested_async_chunking: Vc<bool>,
pub debug_ids: Vc<bool>,
pub should_use_absolute_url_references: Vc<bool>,
pub css_url_suffix: Option<RcStr>,
}
#[turbo_tasks::function]
......@@ -472,6 +473,7 @@ pub async fn get_client_chunking_context(
nested_async_chunking,
debug_ids,
should_use_absolute_url_references,
css_url_suffix,
} = options;
let next_mode = mode.await?;
......@@ -504,7 +506,11 @@ pub async fn get_client_chunking_context(
.debug_ids(*debug_ids.await?)
.should_use_absolute_url_references(*should_use_absolute_url_references.await?)
.nested_async_availability(*nested_async_chunking.await?)
.worker_forwarded_globals(worker_forwarded_globals());
.worker_forwarded_globals(worker_forwarded_globals())
.default_url_behavior(UrlBehavior {
suffix: AssetSuffix::Inferred,
static_suffix: css_url_suffix,
});
if next_mode.is_development() {
builder = builder
......
......@@ -223,6 +223,7 @@ pub struct EdgeChunkingContextOptions {
pub nested_async_chunking: Vc<bool>,
pub client_root: FileSystemPath,
pub asset_prefix: RcStr,
pub css_url_suffix: Option<RcStr>,
}
/// Like `get_edge_chunking_context` but all assets are emitted as client assets (so `/_next`)
......@@ -246,6 +247,7 @@ pub async fn get_edge_chunking_context_with_client_assets(
nested_async_chunking,
client_root,
asset_prefix,
css_url_suffix,
} = options;
let output_root = node_root.join("server/edge")?;
let next_mode = mode.await?;
......@@ -260,6 +262,10 @@ pub async fn get_edge_chunking_context_with_client_assets(
next_mode.runtime_type(),
)
.asset_base_path(Some(asset_prefix))
.default_url_behavior(UrlBehavior {
suffix: AssetSuffix::Inferred,
static_suffix: css_url_suffix,
})
.minify_type(if *turbo_minify.await? {
MinifyType::Minify {
// React needs deterministic function names to work correctly.
......@@ -318,6 +324,7 @@ pub async fn get_edge_chunking_context(
nested_async_chunking,
client_root,
asset_prefix,
css_url_suffix,
} = options;
let output_root = node_root.join("server/edge")?;
let next_mode = mode.await?;
......@@ -338,8 +345,13 @@ pub async fn get_edge_chunking_context(
rcstr!("client"),
UrlBehavior {
suffix: AssetSuffix::FromGlobal(rcstr!("NEXT_CLIENT_ASSET_SUFFIX")),
static_suffix: css_url_suffix.clone(),
},
)
.default_url_behavior(UrlBehavior {
suffix: AssetSuffix::Inferred,
static_suffix: css_url_suffix,
})
// Since one can't read files in edge directly, any asset need to be fetched
// instead. This special blob url is handled by the custom fetch
// implementation in the edge sandbox. It will respond with the
......
......@@ -1035,6 +1035,7 @@ pub struct ServerChunkingContextOptions {
pub debug_ids: Vc<bool>,
pub client_root: FileSystemPath,
pub asset_prefix: RcStr,
pub css_url_suffix: Option<RcStr>,
}
/// Like `get_server_chunking_context` but all assets are emitted as client assets (so `/_next`)
......@@ -1059,6 +1060,7 @@ pub async fn get_server_chunking_context_with_client_assets(
debug_ids,
client_root,
asset_prefix,
css_url_suffix,
} = options;
let next_mode = mode.await?;
......@@ -1080,8 +1082,13 @@ pub async fn get_server_chunking_context_with_client_assets(
rcstr!("client"),
UrlBehavior {
suffix: AssetSuffix::FromGlobal(rcstr!("NEXT_CLIENT_ASSET_SUFFIX")),
static_suffix: css_url_suffix.clone(),
},
)
.default_url_behavior(UrlBehavior {
suffix: AssetSuffix::Inferred,
static_suffix: css_url_suffix,
})
.minify_type(if *minify.await? {
MinifyType::Minify {
// React needs deterministic function names to work correctly.
......@@ -1150,6 +1157,7 @@ pub async fn get_server_chunking_context(
debug_ids,
client_root,
asset_prefix,
css_url_suffix,
} = options;
let next_mode = mode.await?;
// TODO(alexkirsz) This should return a trait that can be implemented by the
......@@ -1172,8 +1180,13 @@ pub async fn get_server_chunking_context(
rcstr!("client"),
UrlBehavior {
suffix: AssetSuffix::FromGlobal(rcstr!("NEXT_CLIENT_ASSET_SUFFIX")),
static_suffix: css_url_suffix.clone(),
},
)
.default_url_behavior(UrlBehavior {
suffix: AssetSuffix::Inferred,
static_suffix: css_url_suffix,
})
.minify_type(if *minify.await? {
MinifyType::Minify {
mangle: (!*no_mangling.await?).then_some(MangleType::OptimalSize),
......
......@@ -2526,6 +2526,7 @@ export default async function getBaseWebpackConfig(
disableStaticImages: config.images.disableStaticImages,
transpilePackages: config.transpilePackages,
serverSourceMaps: config.experimental.serverSourceMaps,
deploymentId: config.deploymentId,
})
// @ts-ignore Cache exists
......
......@@ -52,6 +52,7 @@ export function getGlobalCssLoader(
cssFileResolve(url, resourcePath, ctx.experimental.urlImports),
import: (url: string, _: any, resourcePath: string) =>
cssFileResolve(url, resourcePath, ctx.experimental.urlImports),
deploymentId: ctx.deploymentId,
},
})
......
......@@ -72,6 +72,7 @@ export function getCssModuleLoader(
// character?
getLocalIdent: getCssModuleLocalIdent,
},
deploymentId: ctx.deploymentId,
},
})
......
......@@ -26,6 +26,7 @@ export async function buildConfiguration(
experimental,
disableStaticImages,
serverSourceMaps,
deploymentId,
}: {
hasAppDir: boolean
supportedBrowsers: string[] | undefined
......@@ -44,6 +45,7 @@ export async function buildConfiguration(
experimental: NextConfigComplete['experimental']
disableStaticImages: NextConfigComplete['images']['disableStaticImages']
serverSourceMaps: NextConfigComplete['experimental']['serverSourceMaps']
deploymentId?: string
}
): Promise<webpack.Configuration> {
const ctx: ConfigurationContext = {
......@@ -68,6 +70,7 @@ export async function buildConfiguration(
future,
experimental,
serverSourceMaps: serverSourceMaps ?? false,
deploymentId,
}
let fns = [base(ctx), css(ctx)]
......
......@@ -29,6 +29,8 @@ export type ConfigurationContext = {
// @ts-expect-error TODO: remove any
future: NextConfigComplete['future']
experimental: NextConfigComplete['experimental']
deploymentId?: string
}
export type ConfigurationFn = (
......
......@@ -229,6 +229,7 @@ export default async function loader(
filter: getFilter(options.url, this.resourcePath),
resolver: urlResolver,
urlHandler: (url: string) => stringifyRequest(this, url),
deploymentId: rawOptions.deploymentId,
})
)
}
......
......@@ -315,7 +315,15 @@ const plugin = (options: any = {}) => {
const [pathname, query, hashOrQuery] = url.split(/(\?)?#/, 3)
let hash = query ? '?' : ''
let hash = ''
// Build query string with deployment ID before the hash fragment
if (query || options.deploymentId) {
hash += '?'
}
if (options.deploymentId) {
hash += `dpl=${options.deploymentId}`
}
hash += hashOrQuery ? `#${hashOrQuery}` : ''
const { needToResolveURL, rootContext } = options
......
.global-with-image {
background-image: url('./test-image.png');
}
@font-face {
font-family: 'TestFontGlobal';
src: url('./test-font.woff2') format('woff2');
}
import './global.css'
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html>
<body>{children}</body>
</html>
)
}
.moduleWithImage {
background-image: url('./test-image.png');
}
@font-face {
font-family: 'TestFontModule';
src: url('./test-font.woff2') format('woff2');
}
.scssWithImage {
background-image: url('./test-image.png');
}
@font-face {
font-family: 'TestFontScss';
src: url('./test-font.woff2') format('woff2');
}
import cssModuleStyles from './page.module.css'
import scssModuleStyles from './page.module.scss'
export default function Page() {
return (
<div>
<h1>CSS URL Deployment ID Test</h1>
<div className={cssModuleStyles.moduleWithImage}>CSS Module</div>
<div className={scssModuleStyles.scssWithImage}>SCSS Module</div>
<div className="global-with-image">Global CSS</div>
</div>
)
}
import { nextTestSetup } from 'e2e-utils'
describe('css-url-deployment-id', () => {
const deploymentId = 'test-deployment-id'
const { next } = nextTestSetup({
files: __dirname,
skipDeployment: true,
dependencies: { sass: '1.54.0' },
})
it('should include dpl query in CSS url() references for images and fonts', async () => {
const $ = await next.render$('/')
// Collect all CSS file URLs from link tags
const cssUrls: string[] = []
const links = Array.from($('link'))
for (const link of links) {
const href = link.attribs.href
if (href && href.includes('.css')) {
cssUrls.push(href)
}
}
// Also check for inline styles that may contain CSS
const styles = Array.from($('style'))
// Fetch all CSS files and collect their contents
let allCssContent = ''
for (const cssUrl of cssUrls) {
const res = await next.fetch(cssUrl.split('?')[0])
const cssText = await res.text()
allCssContent += cssText + '\n'
}
// Also collect inline style content
for (const style of styles) {
const children = style.children
if (children && children.length > 0) {
for (const child of children) {
if ('data' in child) {
allCssContent += child.data + '\n'
}
}
}
}
// Extract all url() references from the CSS
const urlMatches = allCssContent.match(/url\([^)]+\)/g) || []
// Filter to only asset URLs (images and fonts), excluding data URIs
const assetUrls = urlMatches.filter(
(u) =>
!u.includes('data:') && (u.includes('.png') || u.includes('.woff2'))
)
expect(assetUrls.length).toBeGreaterThanOrEqual(1)
for (const assetUrl of assetUrls) {
expect(assetUrl).toContain('dpl=' + deploymentId)
}
})
it('should include dpl query in CSS module url() references', async () => {
const $ = await next.render$('/')
const cssUrls: string[] = []
const links = Array.from($('link'))
for (const link of links) {
const href = link.attribs.href
if (href && href.includes('.css')) {
cssUrls.push(href)
}
}
const styles = Array.from($('style'))
let allCssContent = ''
for (const cssUrl of cssUrls) {
const res = await next.fetch(cssUrl.split('?')[0])
const cssText = await res.text()
allCssContent += cssText + '\n'
}
for (const style of styles) {
const children = style.children
if (children && children.length > 0) {
for (const child of children) {
if ('data' in child) {
allCssContent += child.data + '\n'
}
}
}
}
// Find image references from CSS modules (page.module.css)
const imageUrls = allCssContent.match(/url\([^)]+\.png[^)]*\)/g) || []
expect(imageUrls.length).toBeGreaterThanOrEqual(1)
for (const imageUrl of imageUrls) {
expect(imageUrl).toContain('dpl=' + deploymentId)
}
// Find font references from CSS modules
const fontUrls = allCssContent.match(/url\([^)]+\.woff2[^)]*\)/g) || []
expect(fontUrls.length).toBeGreaterThanOrEqual(1)
for (const fontUrl of fontUrls) {
expect(fontUrl).toContain('dpl=' + deploymentId)
}
})
})
/** @type {import('next').NextConfig} */
module.exports = {
deploymentId: 'test-deployment-id',
}
......@@ -680,6 +680,7 @@ impl ChunkingContext for BrowserChunkingContext {
.or_else(|| self.default_url_behavior.clone())
.unwrap_or(UrlBehavior {
suffix: AssetSuffix::Inferred,
static_suffix: None,
})
.cell()
}
......
......@@ -98,6 +98,9 @@ pub enum AssetSuffix {
#[derive(Debug, Clone)]
pub struct UrlBehavior {
pub suffix: AssetSuffix,
/// Static suffix for contexts that cannot use dynamic JS expressions (e.g., CSS `url()`
/// references). Must be a constant string known at build time (e.g., `?dpl=<deployment_id>`).
pub static_suffix: Option<RcStr>,
}
#[derive(
......@@ -358,6 +361,7 @@ pub trait ChunkingContext {
fn url_behavior(self: Vc<Self>, _tag: Option<RcStr>) -> Vc<UrlBehavior> {
UrlBehavior {
suffix: AssetSuffix::Inferred,
static_suffix: None,
}
.cell()
}
......
......@@ -112,7 +112,7 @@ pub async fn resolve_url_reference(
if let ReferencedAsset::Some(asset) = &*url.get_referenced_asset(chunking_context).await? {
let path = asset.path().await?;
let url_path = if *chunking_context
let url_path: RcStr = if *chunking_context
.should_use_absolute_url_references()
.await?
{
......@@ -124,7 +124,15 @@ pub async fn resolve_url_reference(
.unwrap_or_else(|| format!("/{}", path.path).into())
};
return Ok(Vc::cell(Some(url_path)));
// Append the static suffix from UrlBehavior if configured (e.g., ?dpl=<deployment_id>).
let url_behavior = chunking_context.url_behavior(None).await?;
let url_with_suffix = if let Some(ref suffix) = url_behavior.static_suffix {
format!("{}{}", url_path, suffix).into()
} else {
url_path
};
return Ok(Vc::cell(Some(url_with_suffix)));
}
Ok(Vc::cell(None))
......
......@@ -488,6 +488,7 @@ impl ChunkingContext for NodeJsChunkingContext {
.or_else(|| self.default_url_behavior.clone())
.unwrap_or(UrlBehavior {
suffix: AssetSuffix::Inferred,
static_suffix: None,
})
.cell()
}
......
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