import Document, { DocumentContext, Html, Head, Main, NextScript, } from "next/document"; import { ServerStyleSheet } from "styled-components"; class MyDocument extends Document { static async getInitialProps(ctx: DocumentContext) { const sheet = new ServerStyleSheet(); const originalRenderPage = ctx.renderPage; try { // Run the React rendering logic synchronously ctx.renderPage = () => originalRenderPage({ // Useful for wrapping the whole react tree enhanceApp: (App) => (props) => sheet.collectStyles(), // Useful for wrapping in a per-page basis enhanceComponent: (Component) => Component, }); // Run the parent `getInitialProps`, it now includes the custom `renderPage` const initialProps = await Document.getInitialProps(ctx); return { ...initialProps, styles: (
{initialProps.styles} {sheet.getStyleElement()}
), }; } finally { sheet.seal(); } } render() { return ( {/* generated favicons */}
); } } export default MyDocument;