Search code examples
reactjsnext.jsmaterial-uiserver-side-renderingemotion

Material styling not loading in production build


I'm currently working on a project with Nextjs and Material UI. Everything works great in development mode. When I build the project, the first page loads just fine but when I navigate to a second page, a lot of the components load without styling, such as a Dialog.

In dev mode:

enter image description here

In the production build:

enter image description here

I'm guessing it's either a problem with the emotion cache not being injected properly with SSR or with the way I'm using the Link component:

    //Link from next/link
    <Link href={href}>
      <ButtonBase sx={{ width: "100%" }}>
        <CardContent item={item} />
      </ButtonBase>
    </Link

The emotion cache is implemented like this example: https://github.com/mui/material-ui/tree/master/examples/nextjs-with-typescript

React version: 18.1.0 (I've tried with versions 17.0.2 and 18.0 as well) Next: 12.1.6 MUI: 5.7

This question suggests using ServerStyleSheets, which is not included in MUI5.

Has anyone else experienced the same issue?


Solution

  • I've managed to solve the issue myself by first bumping these packages to their latest versions:

    • @emotion/cache
    • @emtion/react
    • @emotion/server
    • @emotion/styled
    • @mui
    • Next
    • React & React-dom

    Then I added a property to tsconfig.json after thoroughly comparing my project with the example repo and finding out I was missing this:

        "jsxImportSource": "@emotion/react",
    

    I'm not entirely sure which one of these actions actually solved the issue but I'm guessing the latter.

    If you're running into a similar problem, you could try adding it to your tsconfig and see if it fixes things.