Skip to content

Instantly share code, notes, and snippets.

@chendo
Last active June 2, 2022 02:54
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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>
}
@githubdoramon
Copy link

Many thanks for this!

@szy0syz
Copy link

szy0syz commented Jun 9, 2021

thank you very much ✌️

@kmvan
Copy link

kmvan commented Mar 31, 2022

not work in React 18+Next 12

@hamudeshahin
Copy link

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

@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