Skip to content

Instantly share code, notes, and snippets.

@chendo
Last active June 2, 2022 02:54
Show Gist options
  • Save chendo/3dbfebe8c0412aac813e46dc75f42cd7 to your computer and use it in GitHub Desktop.
Save chendo/3dbfebe8c0412aac813e46dc75f42cd7 to your computer and use it in GitHub Desktop.
Server side rendering (SSR) in Next.js with styled-components, styled-jsx, and emotion.
import Document, { Head, Main, NextScript } from 'next/document'
import { renderToString } from 'react-dom/server'
import { extractCritical } from 'emotion-server'
import { ServerStyleSheet } from 'styled-components'
import flush from 'styled-jsx/server'
export default class MyDocument extends Document {
static async getInitialProps(ctx) {
const styledComponentsSheet = new ServerStyleSheet()
const originalRenderPage = ctx.renderPage
try {
let emotionStyles
ctx.renderPage = () => (
originalRenderPage({
enhanceApp: App => (
props => {
const html = styledComponentsSheet.collectStyles(<App {...props} />)
emotionStyles = extractCritical(renderToString(html)).css
return html
}
)
})
)
const initialProps = await Document.getInitialProps(ctx)
const styledJSXStyles = flush()
return {
...initialProps,
styles: (
<React.Fragment>
{initialProps.styles}
<style>{emotionStyles}</style>
{styledComponentsSheet.getStyleElement()}
{styledJSXStyles}
</React.Fragment>
)
}
} finally {
styledComponentsSheet.seal()
}
}
// <snip>
}
@kmvan
Copy link

kmvan commented Jun 2, 2022

not work in React 18+Next 12
Yep.. Same problem

Have you try this? https://gist.github.com/kmvan/c97f0ae04ab59af23b10d0c5745eeb34

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment