Last active
June 2, 2022 02:54
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Have you try this? https://gist.github.com/kmvan/c97f0ae04ab59af23b10d0c5745eeb34