Next.js

Next.js + React 18 -> SSR will only work with Next.js 12.1.7-canary.4 or newer.

Setup to make SSR work with Next.js.

yarn add @emotion/server

The following instructions are assuming you are using @muiv5.

You can find here a Next.js setup with @material-ui v4.

pages/_document.tsx

import BaseDocument from "next/document";
import { withEmotionCache } from "tss-react/nextJs";
import { createMuiCache } from "./index";

export default withEmotionCache({
    //If you have a custom document pass it instead
    "Document": BaseDocument,
    //Every emotion cache used in the app should be provided.
    //Caches for MUI should use "prepend": true.
    "getCaches": ()=> [ createMuiCache() ]
});

page/index.tsx

import type { EmotionCache } from "@emotion/cache";
import { CacheProvider } from "@emotion/react";
import createCache from "@emotion/cache";

let muiCache: EmotionCache | undefined = undefined;

export const createMuiCache = () =>
    muiCache = createCache({
        "key": "mui",
        "prepend": true
    });

export default function Index() {
    return (
        <CacheProvider value={muiCache ?? createMuiCache()}>
            {/* Your app  */}
        </CacheProvider>
    );
}

You can find a working example here.

This setup is merely a suggestion. Feel free, for example, to move the <CacheProvider/> into pages/_app.tsx.

What's important to remember however is that new instances of the caches should be created for each render!

If you are using nested selectors, you may need to provide uniq identifiers to your stylesheet.

Last updated