Skip to content

Instantly share code, notes, and snippets.

@kmvan
Created June 2, 2022 02:52
Show Gist options
  • Save kmvan/c97f0ae04ab59af23b10d0c5745eeb34 to your computer and use it in GitHub Desktop.
Save kmvan/c97f0ae04ab59af23b10d0c5745eeb34 to your computer and use it in GitHub Desktop.
Next 12 + React 18 _document.tsx
import Document, {
DocumentContext,
Head,
Html,
Main,
NextScript,
} from 'next/document'
import { CSSProperties, ServerStyleSheet } from 'styled-components'
import { AppContextProps } from 'YOUR APP CONTEXT'
interface PageDocumentProps {
__NEXT_DATA__: {
props: {
appProps: AppContextProps
}
}
}
export default function PageDocument({
__NEXT_DATA__: {
props: { appProps },
},
}: PageDocumentProps) {
return (
<Html lang={appProps.lang}>
<Head />
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
PageDocument.getInitialProps = async (ctx: DocumentContext) => {
const styledComponentsSheet = new ServerStyleSheet()
const originalRenderPage = ctx.renderPage
try {
ctx.renderPage = () =>
originalRenderPage({
enhanceApp: (App) => (props) => {
return styledComponentsSheet.collectStyles(<App {...props} />)
},
})
const initialProps = await Document.getInitialProps(ctx)
initialProps.styles = [
initialProps.styles,
styledComponentsSheet.getStyleElement(),
]
return initialProps
} finally {
styledComponentsSheet.seal()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment