Skip to content

Instantly share code, notes, and snippets.

@chendo
Created April 16, 2019 12:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chendo/0f6ba6df171c08a4c8f435dad2fcffd9 to your computer and use it in GitHub Desktop.
Save chendo/0f6ba6df171c08a4c8f435dad2fcffd9 to your computer and use it in GitHub Desktop.
Critical CSS support for both styled-components and Emotion in Next.js
import Document, { Head, Main, NextScript } from 'next/document'
import { ServerStyleSheet } from 'styled-components'
import { renderToString } from 'react-dom/server'
import { extractCritical } from 'emotion-server'
export default class MyDocument extends Document {
static async getInitialProps(ctx) {
const sheet = new ServerStyleSheet();
const originalRenderPage = ctx.renderPage
try {
let emotionCriticalCSS
ctx.renderPage = () =>
originalRenderPage({
enhanceApp: App => (
props => {
const styledComponentsData = sheet.collectStyles(<App {...props} />)
emotionCriticalCSS = extractCritical(renderToString(styledComponentsData)).css
return styledComponentsData
}
)
})
const initialProps = await Document.getInitialProps(ctx)
return {
...initialProps,
styles: (
<React.Fragment>
{initialProps.styles}
<style>{emotionCriticalCSS}</style>
{sheet.getStyleElement()}
</React.Fragment>
)
}
} finally {
sheet.seal()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment