Skip to content

Instantly share code, notes, and snippets.

@ludder
Created February 17, 2021 20:25
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ludder/c29efcbd0aee813a914ddaf8a3d16496 to your computer and use it in GitHub Desktop.
Save ludder/c29efcbd0aee813a914ddaf8a3d16496 to your computer and use it in GitHub Desktop.
Typed example of _document.js in Next.js with styled components as in: https://github.com/vercel/next.js/blob/master/examples/with-styled-components/pages/_document.js
import Document, { DocumentContext, DocumentInitialProps } from "next/document";
import { ReactElement } from "react";
import { ServerStyleSheet } from "styled-components";
interface InitialProps extends DocumentInitialProps {
styles: ReactElement;
}
export default class MyDocument extends Document {
static async getInitialProps(ctx: DocumentContext): Promise<InitialProps> {
const sheet = new ServerStyleSheet();
const originalRenderPage = ctx.renderPage;
try {
ctx.renderPage = () =>
originalRenderPage({
enhanceApp: (App) => (props) =>
sheet.collectStyles(<App {...props} />),
});
const initialProps = await Document.getInitialProps(ctx);
return {
...initialProps,
styles: (
<>
{initialProps.styles}
{sheet.getStyleElement()}
</>
),
};
} finally {
sheet.seal();
}
}
}
@lucksp
Copy link

lucksp commented Mar 8, 2021

THANK YOU!! This worked like a charm as of today 💯

@thomas4t
Copy link

Thanks, worked for me! 🥇 👍

@strunkandwhite
Copy link

Thanks a million!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment