Next.jsでMUIのテーマAPIを使おうとした際のエラー
環境
- MUI 6.1.9
- Next.js 15.0.3
- React 18.2.0
- Vercelへのデプロイ
コード
// 省略
import { createTheme } from '@mui/material/styles';
const theme = createTheme({
colorSchemes: {
light: {},
dark: {},
},
});
// 以下略
エラー
Error occurred prerendering page "/". Read more: https://nextjs.org/docs/messages/prerender-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.
{keys: ..., values: ..., up: function s, down: ..., between: ..., only: ..., not: ..., unit: ...}
^^^^^^^^^^
at eO (/vercel/path0/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:84:23766)
at Object.toJSON (/vercel/path0/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:84:14915)
at stringify (<anonymous>)
at eU (/vercel/path0/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:84:26272)
at eB (/vercel/path0/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:84:26502)
at eq (/vercel/path0/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:84:27056)
at AsyncLocalStorage.run (node:internal/async_local_storage/async_hooks:91:14)
at /vercel/path0/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:84:39749
at node:internal/process/task_queues:151:7
at AsyncResource.runInAsyncScope (node:async_hooks:211:14)
Export encountered an error on /page: /, exiting the build.
⨯ Static worker exited with code: 1 and signal: null
Error: Command "npm run build" exited with 1
原因
MUIのcreateThemeの部分が関数を返すことが原因。
createTheme()の定義で、cssContainerQueries()の結果が返されるようになっている。
cssContainerQueries()の定義ではcontainerQueriesのup, down, between, only, notプロパティに対して関数が割り当てられている。
おそらく、トレースバックの{keys: ..., values: ..., up: function s, down: ..., between: ..., only: ..., not: ..., unit: ...}の部分はこれ。
Next.jsは関数を含むコンポーネントをSSRできないため、エラーが出る。
今回の場合、
Layouts are Server Components by default but can be set to a Client Component.
とあるように、layout.tsxは強制的にサーバーコンポーネントになるので、createThemeもSSRすることになりエラーになる。
解決策
createThemeを別ファイルに移す。