I'm trying to migrate my MUI project to Next.JS, and I'm running into trouble with the theme. I want to be able to specify and apply the theme at server-render-time, so that the site loads in already themed before hydration.
According to /, I've set this up in src/app/layout.tsx
:
<body>
<AppRouterCacheProvider>
<ThemeProvider theme={AppTheme}>
{children}
</ThemeProvider>
</AppRouterCacheProvider>
...
AppTheme
is the return value of createTheme()
from @mui/material/styles
, run in a file with 'use client'
on the first line. This appropriately applies the theme post-hydration, while the layout is rendered using the default MUI theme pre-hydration.
If I remove the 'use client'
directive from the theme file, NextJS throws a fit, producing an endless stream of this type of error:
⨯ Error: Functions cannot be passed directly to Client Components unless you explicitly expose it by marking it with "use server". Or maybe you meant to call this function rather than return it.
{themeKey: "borders", transform: function borderTransform}
^^^^^^^^^^^^^^^^^^^^^^^^
at stringify (<anonymous>)
at stringify (<anonymous>) {
digest: '704751682'
}
which is presumably because of all the functions that exist inside the theme object that createTheme()
returns.
Is applying a custom theme at server-render-time possible with existing versions of MUI? I can't seem to find any resources on it. It's clearly capable of applying themes during server-render, since the default theme is being applied. But I don't know how I would go about applying a custom theme to the server versions of the layout components, other than what I've already tried.