Commit 1f73f796 authored by Tobias Koppers's avatar Tobias Koppers

Fix styled-jsx styles missing when _document.getInitialProps bypasses defaultGetInitialProps

When a custom _document.getInitialProps calls ctx.renderPage() directly
instead of Document.getInitialProps(ctx), it returns { html, head } without
a styles key. Add a fallback to collect styles from the jsxStyleRegistry
(already populated during renderPage) when docProps.styles is absent.
Co-Authored-By: 's avatarClaude <noreply@anthropic.com>
parent 8db9a752
...@@ -1413,8 +1413,15 @@ export async function renderToHTMLImpl( ...@@ -1413,8 +1413,15 @@ export async function renderToHTMLImpl(
let styles let styles
if (hasDocumentGetInitialProps) { if (hasDocumentGetInitialProps) {
styles = docProps.styles styles = docProps?.styles
head = docProps.head head = docProps?.head
if (!styles && documentInitialPropsRes !== null) {
// Custom _document.getInitialProps called ctx.renderPage() directly
// without Document.getInitialProps, so styled-jsx styles were not
// collected. Collect them from the registry populated during renderPage.
styles = jsxStyleRegistry.styles()
jsxStyleRegistry.flush()
}
} else { } else {
styles = jsxStyleRegistry.styles() styles = jsxStyleRegistry.styles()
jsxStyleRegistry.flush() jsxStyleRegistry.flush()
......
import { nextTestSetup } from 'e2e-utils'
describe('styled-jsx with custom _document renderPage', () => {
const { next } = nextTestSetup({
files: __dirname,
skipDeployment: true,
})
// When _document.getInitialProps calls ctx.renderPage() directly instead of
// Document.getInitialProps(ctx), styled-jsx styles are lost because
// defaultGetInitialProps is never called to collect them.
it('should contain styled-jsx styles in <head> during SSR', async () => {
const html = await next.render('/')
// Styles must appear in <head>, not just anywhere in the HTML
const headContent = html.match(/<head[^>]*>([\s\S]*?)<\/head>/i)?.[1] ?? ''
expect(headContent).toMatch(/color:.*?red/)
})
})
import Document, { Html, Head, Main, NextScript } from 'next/document'
class MyDocument extends Document {
static async getInitialProps(ctx) {
// This pattern bypasses defaultGetInitialProps which collects styled-jsx styles.
// It calls ctx.renderPage() directly and returns { html, head } without styles.
const { html, head } = await ctx.renderPage()
return { html, head }
}
render() {
return (
<Html>
<Head />
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
}
export default MyDocument
export default function Page() {
return (
<div>
<style jsx>{'p { color: red; }'}</style>
<p>hello world</p>
</div>
)
}
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