Commit f158df18 authored by Tobias Koppers's avatar Tobias Koppers Committed by Will Binns-Smith

Fix styled-jsx race condition: styles lost due to concurrent rendering (#92459)

### What?

Fix a race condition in the Pages Router SSR path where styled-jsx
styles were dropped from the rendered HTML.

### Why?

`styledJsxInsertedHTML()` reads and flushes the styled-jsx style
registry. Previously it was called concurrently with the page render via
`Promise.all`:

```js
const [rawStyledJsxInsertedHTML, content] = await Promise.all([
  renderToString(styledJsxInsertedHTML()),
  (async () => { /* render the page */ })(),
])
```

Because both ran at the same time, `styledJsxInsertedHTML()` could (and
in practice did) execute and flush the registry **before** the page
render had finished populating it. The result was that dynamic
styled-jsx styles — those with interpolated expressions that compute
their class names at runtime via DJB2 hashing — were silently dropped
from the SSR output, causing a flash of unstyled content on first load.

This is particularly visible in production deployments where all
components use dynamic styled-jsx (numeric `jsx-*` class names), since
those styles only exist in the registry after rendering completes.

### How?

Serialize the two operations: render the page first, then call
`styledJsxInsertedHTML()`. Since the registry is fully populated by the
time it is read, all styles are captured correctly.

A new e2e test (`test/e2e/styled-jsx-dynamic`) exercises this scenario
with multiple nested components that all use dynamic styled-jsx with
interpolated props, covering the exact FOUC pattern seen in production.

<!-- NEXT_JS_LLM_PR -->
Co-authored-by: 's avatarTobias Koppers <sokra@users.noreply.github.com>
Co-authored-by: 's avatarClaude <noreply@anthropic.com>
parent 356d605b
...@@ -1385,29 +1385,22 @@ export async function renderToHTMLImpl( ...@@ -1385,29 +1385,22 @@ export async function renderToHTMLImpl(
| {} | {}
| Awaited<ReturnType<typeof loadDocumentInitialProps>> | Awaited<ReturnType<typeof loadDocumentInitialProps>>
const [rawStyledJsxInsertedHTML, content] = await Promise.all([ let content: string | null
renderToString(styledJsxInsertedHTML()), if (hasDocumentGetInitialProps) {
(async () => { documentInitialPropsRes = await loadDocumentInitialProps(renderShell)
if (hasDocumentGetInitialProps) { if (documentInitialPropsRes === null) {
documentInitialPropsRes = await loadDocumentInitialProps(renderShell) content = null
if (documentInitialPropsRes === null) return null } else {
const { docProps } = documentInitialPropsRes as any const { docProps } = documentInitialPropsRes as any
return docProps.html content = docProps.html
} else { }
documentInitialPropsRes = {} } else {
const stream = await renderShell(App, Component) documentInitialPropsRes = {}
await stream.allReady const stream = await renderShell(App, Component)
return streamToString(stream) await stream.allReady
} content = await streamToString(stream)
})(),
])
if (content === null) {
return null
} }
const contentHTML = rawStyledJsxInsertedHTML + content
// @ts-ignore: documentInitialPropsRes is set // @ts-ignore: documentInitialPropsRes is set
const { docProps } = (documentInitialPropsRes as any) || {} const { docProps } = (documentInitialPropsRes as any) || {}
const documentElement = (htmlProps: any) => { const documentElement = (htmlProps: any) => {
...@@ -1427,6 +1420,17 @@ export async function renderToHTMLImpl( ...@@ -1427,6 +1420,17 @@ export async function renderToHTMLImpl(
jsxStyleRegistry.flush() jsxStyleRegistry.flush()
} }
// Registry is now flushed; rawStyledJsxInsertedHTML will be empty.
const rawStyledJsxInsertedHTML = await renderToString(
styledJsxInsertedHTML()
)
if (content === null) {
return null
}
const contentHTML = rawStyledJsxInsertedHTML + content
return { return {
contentHTML, contentHTML,
documentElement, documentElement,
......
export default function DynamicStyled({ color }) {
return (
<div>
<style jsx>{`
p {
color: ${color};
}
`}</style>
<p>dynamic styled</p>
</div>
)
}
export default function Footer({ color }) {
return (
<footer>
<style jsx>{`
footer {
color: ${color};
padding: 1rem;
}
`}</style>
<span>Footer</span>
</footer>
)
}
export default function Header({ bg, fg }) {
return (
<header>
<style jsx>{`
header {
background-color: ${bg};
color: ${fg};
padding: 1rem;
}
`}</style>
<span>Header</span>
</header>
)
}
import { nextTestSetup } from 'e2e-utils'
describe('styled-jsx dynamic styles SSR', () => {
const { next } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
// Dynamic styled-jsx (with interpolated expressions) produces numeric class
// names at runtime via the DJB2 hash in styled-jsx's computeId function.
// This pattern matches production deployments where all jsx class names
// are numeric (e.g. jsx-2267428885) rather than hex (jsx-f36313d9f07883b7).
it('should contain dynamic styled-jsx styles during SSR', async () => {
const html = await next.render('/')
// Dynamic styled-jsx produces numeric class names at runtime
const numericClasses = html.match(/\bjsx-\d+\b/g) || []
console.log('Numeric jsx classes:', [...new Set(numericClasses)])
expect(numericClasses.length).toBeGreaterThan(0)
// All dynamic styles should be present as inline <style> tags
expect(html).toMatch(/color:.*?green/) // main page
expect(html).toMatch(/color:.*?blue/) // DynamicStyled
expect(html).toMatch(/background-color:.*?navy/) // header
expect(html).toMatch(/color:.*?purple/) // footer
})
})
import DynamicStyled from '../components/DynamicStyled'
import Header from '../components/Header'
import Footer from '../components/Footer'
export default function Page({ mainColor }) {
return (
<div>
<style jsx>{`
div {
color: ${mainColor};
}
`}</style>
<Header bg="navy" fg="white" />
<main>
<DynamicStyled color="blue" />
</main>
<Footer color="purple" />
</div>
)
}
export function getServerSideProps() {
return {
props: {
mainColor: 'green',
},
}
}
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