1import React from 'react';
2import Document, { Html, Head, Main, NextScript } from 'next/document';
3import { ServerStyleSheets } from '@material-ui/styles'; // works with @material-ui/core/styles, if you prefer to use it.
4import theme from '../src/theme'; // Adjust here as well
5
6export default class MyDocument extends Document {
7 render() {
8 return (
9 <Html lang="en">
10 <Head>
11 {/* Not exactly required, but this is the PWA primary color */}
12 <meta name="theme-color" content={theme.palette.primary.main} />
13 </Head>
14 <body>
15 <Main />
16 <NextScript />
17 </body>
18 </Html>
19 );
20 }
21}
22
23// `getInitialProps` belongs to `_document` (instead of `_app`),
24// it's compatible with server-side generation (SSG).
25MyDocument.getInitialProps = async (ctx) => {
26 // Resolution order
27 //
28 // On the server:
29 // 1. app.getInitialProps
30 // 2. page.getInitialProps
31 // 3. document.getInitialProps
32 // 4. app.render
33 // 5. page.render
34 // 6. document.render
35 //
36 // On the server with error:
37 // 1. document.getInitialProps
38 // 2. app.render
39 // 3. page.render
40 // 4. document.render
41 //
42 // On the client
43 // 1. app.getInitialProps
44 // 2. page.getInitialProps
45 // 3. app.render
46 // 4. page.render
47
48 // Render app and page and get the context of the page with collected side effects.
49 const sheets = new ServerStyleSheets();
50 const originalRenderPage = ctx.renderPage;
51
52 ctx.renderPage = () =>
53 originalRenderPage({
54 enhanceApp: (App) => (props) => sheets.collect(<App {...props} />),
55 });
56
57 const initialProps = await Document.getInitialProps(ctx);
58
59 return {
60 ...initialProps,
61 // Styles fragment is rendered after the app and page rendering finish.
62 styles: [...React.Children.toArray(initialProps.styles), sheets.getStyleElement()],
63 };
64};