Last active
January 12, 2023 16:44
-
-
Save colinhacks/c40519a6a050a99091862319151377ec to your computer and use it in GitHub Desktop.
How to support server-side rendering for plain "emotion" package in Next.js
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
// ⚠️ works with Emotion 10 only! ⚠️ | |
// 1. `yarn add emotion-server` | |
// 2. copy the contents of this file into your `pages` directory | |
// 3. save it as `_document.tsx` | |
// should work out of the box | |
import Document, { Head, Main, NextScript } from 'next/document'; | |
import { extractCritical } from 'emotion-server'; | |
export default class MyDocument extends Document { | |
static async getInitialProps(ctx: any) { | |
const initialProps = await Document.getInitialProps(ctx); | |
const styles = extractCritical(initialProps.html); | |
return { | |
...initialProps, | |
styles: ( | |
<> | |
{initialProps.styles} | |
<style | |
data-emotion-css={styles.ids.join(' ')} | |
dangerouslySetInnerHTML={{ __html: styles.css }} | |
/> | |
</> | |
), | |
}; | |
} | |
render() { | |
return ( | |
<html> | |
<Head /> | |
<body> | |
<Main /> | |
<NextScript /> | |
</body> | |
</html> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice, thanks!
I've opened a Next.js issue to see if they are interested in this: vercel/next.js#20199