Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 36 ยท Next.js and Tooling

Next.js App Router Setup

Set up Material UI in the Next.js App Router: the Emotion cache provider, ThemeProvider in a client component, use client boundaries, fonts and the server-client split.

Next.js is the most common framework for production React apps, and its App Router renders components on the server by default. Material UI relies on Emotion, which creates styles at runtime and needs a place to collect them while rendering. That is why MUI in the App Router needs a little extra setup: a cache provider that gathers the styles during server rendering, a theme provider that lives in a client component, and a clear idea of which files are server code and which are client code.

Neither Next.js nor MUI can run in the live editors on this site. All Next.js and MUI snippets are read-only. The runnable examples are stand-ins that demonstrate the server/client rules and the provider structure with plain React.

Install and structure

In a Next.js project (App Router, app/ folder):

Terminal
npm install @mui/material @emotion/react @emotion/styled @mui/material-nextjs @emotion/cache

@mui/material-nextjs provides AppRouterCacheProvider, which makes sure the CSS that Emotion generates on the server is inlined into the HTML stream exactly once, and is reused by the browser after hydration. Without it you may see unstyled content flashing, styles missing in the first HTML, or hydration warnings.

A typical layout:

TEXT
app/
  layout.tsx         server component: html, body, providers
  page.tsx           server component: the home page
  theme.ts           the theme object (no JSX, no hooks)
  ThemeRegistry.tsx  'use client': ThemeProvider + CssBaseline
  components/
    CounterButton.tsx  'use client': needs state and events

The root layout

TSX
// Real Next.js + Material UI, read-only: app/layout.tsx
import type { Metadata } from 'next';
import { Roboto } from 'next/font/google';
import { AppRouterCacheProvider } from '@mui/material-nextjs/v15-appRouter';
import InitColorSchemeScript from '@mui/material/InitColorSchemeScript';
import ThemeRegistry from './ThemeRegistry';

const roboto = Roboto({
  weight: ['300', '400', '500', '700'],
  subsets: ['latin'],
  display: 'swap',
  variable: '--font-roboto',
});

export const metadata: Metadata = { title: 'My app' };

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en" className={roboto.variable} suppressHydrationWarning>
      <body>
        <InitColorSchemeScript attribute="data-mui-color-scheme" />
        <AppRouterCacheProvider options={{ enableCssLayer: true }}>
          <ThemeRegistry>{children}</ThemeRegistry>
        </AppRouterCacheProvider>
      </body>
    </html>
  );
}

Notes on the details:

  • The import path of AppRouterCacheProvider depends on your Next.js major version (v13-appRouter, v14-appRouter, v15-appRouter, v16-appRouter). Use the one that matches your installed Next.js.
  • next/font self-hosts the font and avoids layout shift; the CSS variable is used in the theme.
  • enableCssLayer: true puts MUI's styles into a CSS layer so that your own CSS or Tailwind rules can override them without specificity battles.
  • suppressHydrationWarning on <html> is needed because the color scheme script changes an attribute before React hydrates.

The theme and its provider

The theme itself is a plain object, so it can be shared. The provider uses context, so it must be a client component:

TSX
// Real Material UI, read-only: app/theme.ts
'use client';
import { createTheme } from '@mui/material/styles';

const theme = createTheme({
  cssVariables: { colorSchemeSelector: 'data' },
  colorSchemes: { light: true, dark: true },
  typography: { fontFamily: 'var(--font-roboto)' },
});

export default theme;
TSX
// Real Material UI, read-only: app/ThemeRegistry.tsx
'use client';
import { ThemeProvider } from '@mui/material/styles';
import CssBaseline from '@mui/material/CssBaseline';
import theme from './theme';

export default function ThemeRegistry({ children }: { children: React.ReactNode }) {
  return (
    <ThemeProvider theme={theme} defaultMode="system">
      <CssBaseline />
      {children}
    </ThemeProvider>
  );
}

'use client' at the top of a file marks it, and everything it imports, as part of the client bundle. The theme file also needs it when it contains functions that you pass to components, because a theme object with functions cannot be sent from the server to the client as props.

Server components and client components

flowchart TD
  L["layout.tsx (server)"] --> C["AppRouterCacheProvider (client)"]
  C --> R["ThemeRegistry (client)"]
  R --> P["page.tsx (server)"]
  P --> B["CounterButton (client)"]
  P --> T["Typography, Paper, Box (client library parts)"]

A server component can render client components as children. A client component can receive server-rendered children, because children are a prop and not an import.

The rules you must remember:

Rule Why
Hooks, state, effects, event handlers (onClick) need a client component They run in the browser
Server components may render MUI components that do not need handlers Typography, Box, Paper, Grid, Container work from server components
Button with an onClick must be in a client component Functions cannot be passed from server to client
Props crossing the boundary must be serializable Strings, numbers, arrays, plain objects; no functions or class instances
sx as a callback (theme) => ... from a server component fails It is a function. Use a client component, or sx object form with theme strings
useTheme, styled components defined in a server file Define them in a client file

Most MUI components work in server components for rendering (the library marks them with 'use client' internally), as long as you do not pass functions as props from the server file.

A page that mixes both

TSX
// Real Next.js + Material UI, read-only: app/page.tsx (a server component)
import Container from '@mui/material/Container';
import Typography from '@mui/material/Typography';
import CounterButton from './components/CounterButton';

export default async function Home() {
  const stats = await fetch('https://api.example.com/stats', { next: { revalidate: 60 } }).then((r) => r.json());
  return (
    <Container maxWidth="md" sx={{ py: 6 }}>
      <Typography variant="h3" component="h1" gutterBottom>Dashboard</Typography>
      <Typography color="text.secondary">Active users: {stats.active}</Typography>
      <CounterButton initial={stats.active} />
    </Container>
  );
}
TSX
// Real Material UI, read-only: app/components/CounterButton.tsx
'use client';
import { useState } from 'react';
import Button from '@mui/material/Button';

export default function CounterButton({ initial }: { initial: number }) {
  const [count, setCount] = useState(initial);
  return (
    <Button variant="contained" onClick={() => setCount((c) => c + 1)} sx={{ mt: 3 }}>
      Count: {count}
    </Button>
  );
}

The page fetches data on the server (no client JavaScript for that), and only CounterButton ships to the browser as interactive code. Keep client components small and low in the tree.

Try it: where can this component run?

This stand-in is a checklist for the boundary rules. Describe a component and the checker tells you whether it needs 'use client'. It encodes the rules from the table above.

Does this component need use client?

Try it: the serialization rule

A server component can only pass data that can be serialized (turned into text and sent) to a client component. This stand-in serializes props with JSON.stringify, which is similar in spirit, and shows what is lost.

What survives the server to client boundary?

Pages Router and other setups

If you use the older pages/ router, MUI has a different setup: a custom _document and _app, and an Emotion cache created with createEmotionCache and @mui/material-nextjs/v15-pagesRouter. The ideas are the same: collect the styles on the server, reuse them on the client, and wrap the app in a theme provider.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What problem does AppRouterCacheProvider solve?

    Emotion creates styles at runtime. In the App Router the cache provider records styles during the server stream and sends them with the HTML.
  2. 2. Why is ThemeProvider placed in a file with 'use client'?

    Context providers need client rendering. The server layout renders the client ThemeRegistry as a wrapper around the children.
  3. 3. What happens if a server component passes onClick={() => ...} to a MUI Button?

    Event handlers are functions and must live in client components.
  4. 4. Where should 'use client' components be placed in the tree for the least JavaScript?

    A client boundary pulls everything it imports into the client bundle, so keep interactive parts small.

Summary

  • In the App Router, wrap the app with AppRouterCacheProvider (matching your Next.js version) so Emotion styles render on the server.
  • Put ThemeProvider and CssBaseline in a 'use client' file; use InitColorSchemeScript and next/font.
  • Server components may render display-only MUI components; anything with state, effects or handlers belongs in a small client component.
  • Props that cross the boundary must be serializable; no functions.

Next: SSR, Emotion and the Theme Flash