Skip to content

Instantly share code, notes, and snippets.

@vmarcosp
Created July 16, 2022 14:41
Show Gist options
  • Save vmarcosp/16e409ceecebc2932b82032ffbb7c922 to your computer and use it in GitHub Desktop.
Save vmarcosp/16e409ceecebc2932b82032ffbb7c922 to your computer and use it in GitHub Desktop.

Revisions

  1. vmarcosp created this gist Jul 16, 2022.
    49 changes: 49 additions & 0 deletions _document.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,49 @@
    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;