Created
July 16, 2022 14:41
-
-
Save vmarcosp/16e409ceecebc2932b82032ffbb7c922 to your computer and use it in GitHub Desktop.
Basic config for Emotion + SSR with 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
import React from "react"; | |
import createEmotionServer from "@emotion/server/create-instance"; | |
import NextDocument, { Html, Main, Head, NextScript } from "next/document"; | |
import { cache } from "@emotion/css"; | |
class Document extends NextDocument { | |
static async getInitialProps(ctx) { | |
const page = await ctx.renderPage(); | |
const initialProps = await NextDocument.getInitialProps(ctx); | |
const { css, ids } = renderStatic(page.html); | |
return { | |
...initialProps, | |
styles: ( | |
<> | |
{initialProps.styles} | |
<style | |
data-emotion={`css ${ids.join(" ")}`} | |
dangerouslySetInnerHTML={{ __html: css }} | |
/> | |
</> | |
), | |
}; | |
} | |
render() { | |
return ( | |
<Html lang="pt-br"> | |
<Head /> | |
<body> | |
<Main /> | |
<NextScript /> | |
</body> | |
</Html> | |
); | |
} | |
} | |
export const renderStatic = (html) => { | |
if (html === undefined) { | |
throw new Error("did you forget to return html from renderToString?"); | |
} | |
const { extractCritical } = createEmotionServer(cache); | |
const { ids, css } = extractCritical(html); | |
return { html, ids, css }; | |
}; | |
export default Document; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment