Commit d39f0bc2 authored by Jimmy Lai's avatar Jimmy Lai

refactor: scope inlineCss fix to 'shared' mode only

- Remove double CSS insertion fix for `inlineCss: true` (revert to original behavior)
- Keep optimized CSS handling only for `inlineCss: 'shared'` mode
- Add limitation note in docs about CSS duplication for `inlineCss: true`
- Add tests for nested layout CSS and multiple navigations in shared mode
parent ac385226
......@@ -39,9 +39,19 @@ module.exports = nextConfig
| `true` | All CSS is inlined |
| `'shared'` | Only root layout CSS is inlined |
### The `'shared'` Option
### The `'shared'` Option (Recommended for Tailwind)
When using `inlineCss: 'shared'`, only the CSS from your root layout is inlined. This is particularly useful when using utility-first CSS frameworks like Tailwind CSS, where the root layout CSS is shared across all pages.
When using `inlineCss: 'shared'`, only the CSS from your root layout is inlined. This mode is ideal for utility-first CSS frameworks like Tailwind CSS, where:
- Tailwind CSS is typically imported once in the root layout
- The styles are shared across all pages
- The CSS bundle doesn't grow significantly per page (O(1) complexity)
This mode provides optimized performance by:
- Inlining root layout CSS in the initial HTML for fast First Contentful Paint
- Excluding root layout CSS from RSC payloads during navigation (client already has it)
- Loading page-specific CSS via `<link>` tags to avoid duplication issues
```ts filename="next.config.ts" switcher
import type { NextConfig } from 'next'
......@@ -105,3 +115,4 @@ Evaluate these trade-offs carefully, and consider combining inlining with other
> - CSS inlining is applied globally and cannot be configured on a per-page basis
> - When navigating to statically rendered pages, styles will use `<link>` tags instead of inline CSS to avoid duplication
> - This feature is not available in development mode and only works in production builds
> - When using `inlineCss: true`, styles are duplicated during initial page load - once within `<style>` tags for SSR and once in the RSC payload. Consider using `'shared'` mode if this is a concern.
......@@ -9,14 +9,12 @@ import type { PreloadCallbacks, CollectedInlineCss } from './types'
* For inlined CSS, renders a <style> tag with the CSS content directly embedded.
* For external CSS files, renders a <link> tag pointing to the CSS file.
*
* When collectedInlineCss is provided, inline CSS is collected for injection
* via ServerInsertedHTML instead of being rendered in the component tree.
* This avoids duplicating CSS in both HTML and RSC payload.
*
* The inlineCssMode determines the inlining behavior:
* - `false` or `undefined`: No CSS inlining (render as <link> tags)
* - `true`: Inline ALL CSS
* - `'shared'`: Only inline root layout CSS (safer for client navigations)
* - `true`: Inline ALL CSS (note: CSS will be duplicated in HTML and RSC payload)
* - `'shared'`: Only inline root layout CSS (safer for client navigations).
* In this mode, collectedInlineCss is used to inject CSS via ServerInsertedHTML
* to avoid duplicating CSS in both HTML and RSC payload.
*/
export function renderCssResource(
entryCssFiles: CssResource[],
......@@ -97,18 +95,6 @@ export function renderCssResource(
!ctx.parsedRequestHeaders.isRSCRequest
) {
// inlineCss: true mode - inline ALL CSS for non-RSC requests
// When collectedInlineCss is provided, collect CSS for ServerInsertedHTML
// injection instead of rendering in the component tree. This prevents
// CSS from being duplicated in both HTML and RSC payload.
if (collectedInlineCss) {
collectedInlineCss.styles.push({
href: fullHref,
content: entryCssFile.content!,
precedence: precedence,
nonce: ctx.nonce,
})
return null
}
return createElement(
'style',
{
......
import { connection } from 'next/server'
import './styles.css'
export default async function PageB() {
await connection()
return (
<main id="page-b" className="p-4">
<h1 className="text-2xl font-bold text-blue-500">Page B</h1>
<p className="page-b-custom">This has page B specific CSS</p>
</main>
)
}
/* Page B specific CSS - should NOT be inlined, loaded via <link> */
.page-b-custom {
font-weight: bold;
color: purple;
}
......@@ -8,6 +8,7 @@ export default function RootLayout({ children }) {
<nav className="flex gap-4 p-4">
<Link
href="/"
id="link-home"
prefetch={false}
className="text-blue-500 hover:underline"
>
......@@ -21,6 +22,22 @@ export default function RootLayout({ children }) {
>
Page A
</Link>
<Link
href="/b"
id="link-b"
prefetch={false}
className="text-blue-500 hover:underline"
>
Page B
</Link>
<Link
href="/nested"
id="link-nested"
prefetch={false}
className="text-blue-500 hover:underline"
>
Nested
</Link>
</nav>
{children}
</body>
......
/* Nested layout CSS - should NOT be inlined (only root layout is inlined) */
.nested-layout-wrapper {
border: 2px solid orange;
padding: 16px;
}
.nested-header {
background-color: orange;
color: white;
padding: 8px;
margin-bottom: 16px;
}
import './layout.css'
export default function NestedLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<div className="nested-layout-wrapper">
<header className="nested-header">Nested Layout Header</header>
{children}
</div>
)
}
import { connection } from 'next/server'
export default async function NestedPage() {
await connection()
return (
<main id="page-nested" className="p-4">
<h1 className="text-2xl font-bold text-blue-500">Nested Page</h1>
<p>This page is inside a nested layout</p>
</main>
)
}
......@@ -118,5 +118,72 @@ describe('app dir - css - experimental inline css shared mode', () => {
expect(await customElement.getComputedCss('fontSize')).toBe('32px')
expect(await customElement.getComputedCss('color')).toBe('rgb(0, 128, 0)') // green
})
it('should maintain styles after multiple navigations', async () => {
const browser = await next.browser('/')
// Verify initial page
expect(await browser.elementByCss('h1').getComputedCss('color')).toBe(
'rgb(59, 130, 246)'
)
// Navigate: Home → A
await browser.elementByCss('#link-a').click()
await browser.waitForElementByCss('#page-a')
expect(await browser.elementByCss('h1').getComputedCss('color')).toBe(
'rgb(59, 130, 246)'
)
// Navigate: A → B
await browser.elementByCss('#link-b').click()
await browser.waitForElementByCss('#page-b')
expect(await browser.elementByCss('h1').getComputedCss('color')).toBe(
'rgb(59, 130, 246)'
)
// Page B specific styles
expect(
await browser.elementByCss('.page-b-custom').getComputedCss('color')
).toBe('rgb(128, 0, 128)') // purple
// Navigate: B → Home
await browser.elementByCss('#link-home').click()
await browser.waitForElementByCss('#page-home')
expect(await browser.elementByCss('h1').getComputedCss('color')).toBe(
'rgb(59, 130, 246)'
)
})
it('should only inline root layout CSS, not nested layout CSS', async () => {
const $ = await next.render$('/nested')
// Tailwind (root layout) CSS should be inlined
const styleContent = $('style').text()
expect(styleContent).toMatch(/\.text-blue-500|--tw-|\.bg-white/)
// Nested layout CSS should NOT be in the inline styles
expect(styleContent).not.toContain('.nested-layout-wrapper')
expect(styleContent).not.toContain('.nested-header')
// Nested layout CSS should be loaded via <link> tag
const linkTags = $('link[rel="stylesheet"]')
expect(linkTags.length).toBeGreaterThan(0)
})
it('should include nested layout CSS in RSC payload for navigations', async () => {
// Fetch the RSC payload for /nested (navigation request)
const rscPayload = await (
await next.fetch(`/nested?${NEXT_RSC_UNION_QUERY}`, {
method: 'GET',
headers: {
rsc: '1',
},
})
).text()
// Nested layout CSS should be referenced in the RSC payload
expect(rscPayload).toContain('__PAGE__') // sanity check
// The nested layout CSS should be referenced (as link or stylesheet)
expect(rscPayload).toMatch(/stylesheet|\.css/)
})
})
})
......@@ -93,28 +93,5 @@ describe('app dir - css - experimental inline css', () => {
expect(res.status).toBe(200)
expect(res.headers.get('content-type')).toContain('font')
})
it('should not include CSS content in RSC inline payload on initial HTML', async () => {
const $ = await next.render$('/')
// Get the RSC inline payload from script tags
const rscScripts = $('script')
.filter(function () {
const content = $(this).html()
return content && content.includes('self.__next_f.push')
})
.toArray()
// Combine all RSC payload content
const rscPayload = rscScripts.map((script) => $(script).html()).join('\n')
// CSS content should be in the HTML <style> tags
const styleContent = $('style').text()
expect(styleContent).toContain('color')
// CSS content "color:yellow" should NOT be in the RSC payload
// (The CSS is injected via ServerInsertedHTML, not the RSC tree)
expect(rscPayload).not.toContain('color:yellow')
})
})
})
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