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> | |
); | |
} | |
} |
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
Diclaimer - not fully tested this its rough but think it'll work.
Another way to get this to work with the custom way (if you want a custom config) would be...
shared/emotion.ts
_document.tsx
- note the new importshared/emotion
and@emotion/server/create-instance
_app.tsx
- note the new importshared/emotion
Doing it this way is a little maintenance, however, more flexible. All that is required is to use the
css, keyframes
etc etc fromshared/emotion
rather than emotion css. When styling your app. The css classname should now have classname='css-whatever-randomstring'. For example,