Unverified Commit 6c105133 authored by Jude Gao's avatar Jude Gao Committed by GitHub

Fix: CSS asset URLs broken with `experimental.inlineCss` (#85140)

This PR fixes a critical issue with the `experimental.inlineCss` feature
where CSS `url()` references to fonts and other assets would break when
CSS was inlined into `<style>` tags instead of being loaded via external
`<link>` tags. The problem occurred because relative URLs in CSS are
resolved relative to the CSS file's location when loaded externally, but
when the CSS is inlined directly into the HTML document, those same
relative URLs resolve relative to the HTML document instead, causing 404
errors for fonts and images. We fixed this by detecting when CSS is
being prepared for inlining and switching from relative URLs (like
`../_next/static/media/font.woff2`) to absolute URLs (like
`/_next/static/media/font.woff2`) in both the Webpack and Turbopack
bundlers. This ensures that asset references work correctly regardless
of whether the CSS is inlined or external, while maintaining the
existing optimization of using relative URLs for the default case where
CSS is loaded via external stylesheets. The fix is transparent to users
and requires no changes to application code—simply enabling
`experimental.inlineCss: true` will now work correctly with all CSS
asset references.


Fixes https://github.com/vercel/next.js/issues/83674

---------
Co-authored-by: 's avatarNiklas Mischkulnig <4586894+mischnic@users.noreply.github.com>
parent 08d679c2
...@@ -1078,6 +1078,7 @@ impl Project { ...@@ -1078,6 +1078,7 @@ impl Project {
no_mangling: self.no_mangling(), no_mangling: self.no_mangling(),
scope_hoisting: self.next_config().turbo_scope_hoisting(self.next_mode()), scope_hoisting: self.next_config().turbo_scope_hoisting(self.next_mode()),
debug_ids: self.next_config().turbopack_debug_ids(), debug_ids: self.next_config().turbopack_debug_ids(),
should_use_absolute_url_references: self.next_config().inline_css(),
})) }))
} }
......
...@@ -427,6 +427,7 @@ pub struct ClientChunkingContextOptions { ...@@ -427,6 +427,7 @@ pub struct ClientChunkingContextOptions {
pub no_mangling: Vc<bool>, pub no_mangling: Vc<bool>,
pub scope_hoisting: Vc<bool>, pub scope_hoisting: Vc<bool>,
pub debug_ids: Vc<bool>, pub debug_ids: Vc<bool>,
pub should_use_absolute_url_references: Vc<bool>,
} }
#[turbo_tasks::function] #[turbo_tasks::function]
...@@ -448,6 +449,7 @@ pub async fn get_client_chunking_context( ...@@ -448,6 +449,7 @@ pub async fn get_client_chunking_context(
no_mangling, no_mangling,
scope_hoisting, scope_hoisting,
debug_ids, debug_ids,
should_use_absolute_url_references,
} = options; } = options;
let next_mode = mode.await?; let next_mode = mode.await?;
...@@ -481,7 +483,8 @@ pub async fn get_client_chunking_context( ...@@ -481,7 +483,8 @@ pub async fn get_client_chunking_context(
.current_chunk_method(CurrentChunkMethod::DocumentCurrentScript) .current_chunk_method(CurrentChunkMethod::DocumentCurrentScript)
.export_usage(*export_usage.await?) .export_usage(*export_usage.await?)
.module_id_strategy(module_id_strategy.to_resolved().await?) .module_id_strategy(module_id_strategy.to_resolved().await?)
.debug_ids(*debug_ids.await?); .debug_ids(*debug_ids.await?)
.should_use_absolute_url_references(*should_use_absolute_url_references.await?);
if next_mode.is_development() { if next_mode.is_development() {
builder = builder builder = builder
......
...@@ -6,11 +6,13 @@ export function getClientStyleLoader({ ...@@ -6,11 +6,13 @@ export function getClientStyleLoader({
isAppDir, isAppDir,
isDevelopment, isDevelopment,
assetPrefix, assetPrefix,
experimentalInlineCss,
}: { }: {
hasAppDir: boolean hasAppDir: boolean
isAppDir?: boolean isAppDir?: boolean
isDevelopment: boolean isDevelopment: boolean
assetPrefix: string assetPrefix: string
experimentalInlineCss?: boolean
}): webpack.RuleSetUseItem { }): webpack.RuleSetUseItem {
const isRspack = Boolean(process.env.NEXT_RSPACK) const isRspack = Boolean(process.env.NEXT_RSPACK)
const shouldEnableApp = typeof isAppDir === 'boolean' ? isAppDir : hasAppDir const shouldEnableApp = typeof isAppDir === 'boolean' ? isAppDir : hasAppDir
...@@ -52,7 +54,7 @@ export function getClientStyleLoader({ ...@@ -52,7 +54,7 @@ export function getClientStyleLoader({
return { return {
loader: MiniCssExtractPlugin.loader, loader: MiniCssExtractPlugin.loader,
options: { options: {
publicPath: `${assetPrefix}/_next/`, publicPath: experimentalInlineCss ? '/' : `${assetPrefix}/_next/`,
esModule: false, esModule: false,
}, },
} }
......
...@@ -20,6 +20,7 @@ export function getGlobalCssLoader( ...@@ -20,6 +20,7 @@ export function getGlobalCssLoader(
isAppDir: ctx.isAppDir, isAppDir: ctx.isAppDir,
isDevelopment: ctx.isDevelopment, isDevelopment: ctx.isDevelopment,
assetPrefix: ctx.assetPrefix, assetPrefix: ctx.assetPrefix,
experimentalInlineCss: ctx.experimental.inlineCss,
}) })
) )
} }
......
...@@ -20,6 +20,7 @@ export function getCssModuleLoader( ...@@ -20,6 +20,7 @@ export function getCssModuleLoader(
isAppDir: ctx.isAppDir, isAppDir: ctx.isAppDir,
isDevelopment: ctx.isDevelopment, isDevelopment: ctx.isDevelopment,
assetPrefix: ctx.assetPrefix, assetPrefix: ctx.assetPrefix,
experimentalInlineCss: ctx.experimental.inlineCss,
}) })
) )
} }
......
import localFont from 'next/font/local'
export const font = localFont({
src: './font-noto-sans.woff2',
variable: '--font-1',
})
p { p {
color: yellow; color: yellow;
} }
body {
font-family: var(--font-1);
}
import Link from 'next/link' import Link from 'next/link'
import './global.css' import './global.css'
import { font } from './font'
export default function RootLayout({ children }) { export default function RootLayout({ children }) {
return ( return (
<html> <html className={font.variable}>
<body> <body>
<nav> <nav>
<Link href="/" prefetch={false}> <Link href="/" prefetch={false}>
......
import { font } from './font'
export default function Home() { export default function Home() {
return <p>Home</p> return (
<div>
<p>Home</p>
<p id="with-font" className={font.className}>
Text with custom font
</p>
</div>
)
} }
...@@ -52,5 +52,46 @@ describe('app dir - css - experimental inline css', () => { ...@@ -52,5 +52,46 @@ describe('app dir - css - experimental inline css', () => {
expect(styleTags).toHaveLength(1) expect(styleTags).toHaveLength(1)
expect(linkTags).toHaveLength(0) expect(linkTags).toHaveLength(0)
}) })
it('should apply font styles correctly via className', async () => {
const browser = await next.browser('/')
const fontElement = await browser.elementByCss('#with-font')
const computedFontFamily = await fontElement.getComputedCss('fontFamily')
expect(computedFontFamily).toBeTruthy()
expect(computedFontFamily).not.toBe('Times')
})
it('should apply font styles correctly via CSS variable', async () => {
const browser = await next.browser('/')
const bodyElement = await browser.elementByCss('body')
const computedFontFamily = await bodyElement.getComputedCss('fontFamily')
expect(computedFontFamily).toBeTruthy()
expect(computedFontFamily).not.toBe('Times')
})
it('should inline font-face with absolute src URL', async () => {
const $ = await next.render$('/')
const styleTag = $('style')
expect(styleTag.length).toBeGreaterThan(0)
const styleContent = styleTag.html()
expect(styleContent).toMatch(/@font-face/)
expect(styleContent).toMatch(/font-family/)
const srcMatch = styleContent.match(/src:\s*url\(([^)]+)\)/)
expect(srcMatch).toBeTruthy()
const fontUrl = srcMatch[1].replace(/['"]/g, '')
expect(fontUrl).toMatch(/^\//)
const res = await next.fetch(fontUrl)
expect(res.status).toBe(200)
expect(res.headers.get('content-type')).toContain('font')
})
}) })
}) })
...@@ -173,6 +173,15 @@ impl BrowserChunkingContextBuilder { ...@@ -173,6 +173,15 @@ impl BrowserChunkingContextBuilder {
self self
} }
pub fn should_use_absolute_url_references(
mut self,
should_use_absolute_url_references: bool,
) -> Self {
self.chunking_context.should_use_absolute_url_references =
should_use_absolute_url_references;
self
}
pub fn asset_root_path_override(mut self, tag: RcStr, path: FileSystemPath) -> Self { pub fn asset_root_path_override(mut self, tag: RcStr, path: FileSystemPath) -> Self {
self.chunking_context.asset_root_paths.insert(tag, path); self.chunking_context.asset_root_paths.insert(tag, path);
self self
...@@ -278,6 +287,8 @@ pub struct BrowserChunkingContext { ...@@ -278,6 +287,8 @@ pub struct BrowserChunkingContext {
export_usage: Option<ResolvedVc<ExportUsageInfo>>, export_usage: Option<ResolvedVc<ExportUsageInfo>>,
/// The chunking configs /// The chunking configs
chunking_configs: Vec<(ResolvedVc<Box<dyn ChunkType>>, ChunkingConfig)>, chunking_configs: Vec<(ResolvedVc<Box<dyn ChunkType>>, ChunkingConfig)>,
/// Whether to use absolute URLs for static assets (e.g. in CSS: `url("/absolute/path")`)
should_use_absolute_url_references: bool,
} }
impl BrowserChunkingContext { impl BrowserChunkingContext {
...@@ -322,6 +333,7 @@ impl BrowserChunkingContext { ...@@ -322,6 +333,7 @@ impl BrowserChunkingContext {
module_id_strategy: ResolvedVc::upcast(DevModuleIdStrategy::new_resolved()), module_id_strategy: ResolvedVc::upcast(DevModuleIdStrategy::new_resolved()),
export_usage: None, export_usage: None,
chunking_configs: Default::default(), chunking_configs: Default::default(),
should_use_absolute_url_references: false,
}, },
} }
} }
...@@ -629,6 +641,11 @@ impl ChunkingContext for BrowserChunkingContext { ...@@ -629,6 +641,11 @@ impl ChunkingContext for BrowserChunkingContext {
self.minify_type.cell() self.minify_type.cell()
} }
#[turbo_tasks::function]
fn should_use_absolute_url_references(&self) -> Vc<bool> {
Vc::cell(self.should_use_absolute_url_references)
}
#[turbo_tasks::function] #[turbo_tasks::function]
async fn chunk_group( async fn chunk_group(
self: ResolvedVc<Self>, self: ResolvedVc<Self>,
......
...@@ -239,6 +239,11 @@ pub trait ChunkingContext { ...@@ -239,6 +239,11 @@ pub trait ChunkingContext {
MinifyType::NoMinify.cell() MinifyType::NoMinify.cell()
} }
#[turbo_tasks::function]
fn should_use_absolute_url_references(self: Vc<Self>) -> Vc<bool> {
Vc::cell(false)
}
#[turbo_tasks::function] #[turbo_tasks::function]
fn async_loader_chunk_item( fn async_loader_chunk_item(
&self, &self,
......
...@@ -101,15 +101,22 @@ pub async fn resolve_url_reference( ...@@ -101,15 +101,22 @@ pub async fn resolve_url_reference(
url: Vc<UrlAssetReference>, url: Vc<UrlAssetReference>,
chunking_context: Vc<Box<dyn ChunkingContext>>, chunking_context: Vc<Box<dyn ChunkingContext>>,
) -> Result<Vc<Option<RcStr>>> { ) -> Result<Vc<Option<RcStr>>> {
let context_path = chunking_context.chunk_root_path().await?;
if let ReferencedAsset::Some(asset) = &*url.get_referenced_asset(chunking_context).await? { if let ReferencedAsset::Some(asset) = &*url.get_referenced_asset(chunking_context).await? {
let path = asset.path().await?; let path = asset.path().await?;
let relative_path = context_path
.get_relative_path_to(&path)
.unwrap_or_else(|| format!("/{}", path.path).into());
return Ok(Vc::cell(Some(relative_path))); let url_path = if *chunking_context
.should_use_absolute_url_references()
.await?
{
format!("/{}", path.path).into()
} else {
let context_path = chunking_context.chunk_root_path().await?;
context_path
.get_relative_path_to(&path)
.unwrap_or_else(|| format!("/{}", path.path).into())
};
return Ok(Vc::cell(Some(url_path)));
} }
Ok(Vc::cell(None)) Ok(Vc::cell(None))
......
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