For everyone who still has the problem with the code above: I had to also include the StylesProvider in pages/_app.tsx.
_app.tsx:
import { StylesProvider } from '@material-ui/core/styles';
<StylesProvider injectFirst>
{/* Your component tree.
Now, you can override Material-UI's styles. */}
</StylesProvider>
_document.tsx:
import React from 'react';
import Document, { Head, Main, NextScript } from 'next/document';
import { ServerStyleSheets } from '@material-ui/styles';
import { ServerStyleSheet } from 'styled-components';
class MyDocument extends Document {
render() {
return (
<html lang="en">
<Head>
<meta charSet="utf-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no"
/>
<meta name="theme-color" content="#000000" />
{/* Fonts and icons */}
<link
rel="stylesheet"
type="text/css"
href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Roboto+Slab:400,700|Material+Icons"
/>
<link
href="https://use.fontawesome.com/releases/v5.0.10/css/all.css"
rel="stylesheet"
/>
</Head>
<body>
<div id="page-transition" />
<Main />
<NextScript />
</body>
</html>
);
}
}
MyDocument.getInitialProps = async (ctx) => {
// Render app and page and get the context of the page with collected side effects.
const materialSheet = new ServerStyleSheets();
const styledComponentSheet = new ServerStyleSheet();
const originalRenderPage = ctx.renderPage;
try {
ctx.renderPage = () =>
originalRenderPage({
enhanceApp: (App) => (props) =>
styledComponentSheet.collectStyles(
materialSheet.collect(<App {...props} />),
),
});
const initialProps = await Document.getInitialProps(ctx);
return {
...initialProps,
// Styles fragment is rendered after the app and page rendering finish.
styles: [
...React.Children.toArray(initialProps.styles),
materialSheet.getStyleElement(),
styledComponentSheet.getStyleElement(),
],
};
} finally {
styledComponentSheet.seal();
}
};
export default MyDocument;