Skip to content

Instantly share code, notes, and snippets.

@colinhacks
Last active January 12, 2023 16:44
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save colinhacks/c40519a6a050a99091862319151377ec to your computer and use it in GitHub Desktop.
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
// ⚠️ 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>
);
}
}
@karlhorky
Copy link

Nice, thanks!

I've opened a Next.js issue to see if they are interested in this: vercel/next.js#20199

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