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.

Revisions

  1. kmvan revised this gist Jun 2, 2022. 1 changed file with 1 addition and 3 deletions.
    4 changes: 1 addition & 3 deletions _document.tsx
    Original file line number Diff line number Diff line change
    @@ -1,4 +1,3 @@
    ```typescript
    import Document, {
    DocumentContext,
    Head,
    @@ -49,5 +48,4 @@ PageDocument.getInitialProps = async (ctx: DocumentContext) => {
    } finally {
    styledComponentsSheet.seal()
    }
    }
    ```
    }
  2. kmvan created this gist Jun 2, 2022.
    53 changes: 53 additions & 0 deletions _document.tsx
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,53 @@
    ```typescript
    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()
    }
    }
    ```