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/serverpages/_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.
pages/_document.tsx
If you use <TssCacheProvider/> or <CacheProvider/> anywhere in your app you must provide a getCache function to withEmotionCache.
What's important to remember however is that new instances of the caches should be created for each render!
You can get inspiration on how to do it under the With MUI tab.
If you are using nested selectors, you may need to provide uniq identifiers to your stylesheet.
Last updated
Was this helpful?