Skip to content

Instantly share code, notes, and snippets.

@MobliMic
Created March 3, 2020 14:18
Show Gist options
  • Save MobliMic/247802610ae4146846cc0c2e9fcaa696 to your computer and use it in GitHub Desktop.
Save MobliMic/247802610ae4146846cc0c2e9fcaa696 to your computer and use it in GitHub Desktop.
/* eslint react/no-danger: 0 */
import React from "react";
import Document, { Html, Head, Main, NextScript } from "next/document";
import { ServerStyleSheet as StyledComponentSheets } from "styled-components";
class CustomDocument extends Document {
render() {
// Store initial props from request data that we need to use again on
// the client. See:
// https://github.com/zeit/next.js/issues/3043#issuecomment-334521241
// https://github.com/zeit/next.js/issues/2252#issuecomment-353992669
// Alternatively, you could use a store, like Redux.
const { AuthUserInfo } = this.props;
return (
<Html>
<Head>
<meta
name="viewport"
content="minimum-scale=1, initial-scale=1, width=device-width"/>
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}
CustomDocument.getInitialProps = async ctx => {
const styledComponentSheet = new StyledComponentSheets();
const originalRenderPage = ctx.renderPage;
try {
ctx.renderPage = () =>
originalRenderPage({
enhanceApp: App => props =>
styledComponentSheet.collectStyles(<App {...props} />)
});
const initialProps = await Document.getInitialProps(ctx);
return {
...initialProps,
AuthUserInfo,
styles: [
<React.Fragment key="styles">
{initialProps.styles}
{styledComponentSheet.getStyleElement()}
</React.Fragment>
]
};
} finally {
styledComponentSheet.seal();
}
};
export default CustomDocument;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment