본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

Next.js 통합

원문 보기 위키 갱신

Next.js 통합 (Next.js integration)

Next.js와 함께 Material UI를 사용하는 방법을 알아볼게요. App Router와 Pages Router 두 방식 모두를 다루며, 의존성 설치부터 폰트 최적화, 커스텀 테마, CSS 테마 변수까지 차근차근 설명드려요.

출처: 문서

본문

✅ Material UI + Next.js 에이전트 스킬을 사용해 AI 코딩 어시스턴트에게 이 통합에 대한 전체 컨텍스트(App Router, SSR cache 프로바이더, next/font, CSS 레이어 포함)를 제공해 보세요.

App Router

이 섹션에서는 Next.js App Router와의 Material UI 통합을 살펴볼게요. App Router는 Pages Router의 진화이며, 현재 버전 13부터 새 Next.js 애플리케이션을 만들 때 권장되는 방식이에요.

의존성 설치하기

먼저 @mui/material과 next가 이미 설치되어 있는지 확인하세요. 그런 다음 아래 명령어 중 하나를 실행해 의존성을 설치합니다.

npm install @mui/material-nextjs @emotion/cache
pnpm add @mui/material-nextjs @emotion/cache
yarn add @mui/material-nextjs @emotion/cache

구성 (Configuration)

app/layout.tsx 안에서 AppRouterCacheProvider를 import 하고 <body> 아래의 모든 엘리먼트를 그것으로 감싸세요:

+import { AppRouterCacheProvider } from '@mui/material-nextjs/v15-appRouter';
 // or `v1X-appRouter` if you are using Next.js v1X

 export default function RootLayout(props) {
   return (
     <html lang="en">
       <body>
+        <AppRouterCacheProvider>
           {props.children}
+        </AppRouterCacheProvider>
       </body>
     </html>
   );
 }

💡 AppRouterCacheProvider 컴포넌트는 Next.js가 .html 페이지 청크를 클라이언트로 스트리밍할 때 서버에서 MUI System이 생성한 CSS를 수집하는 역할을 해요.

AppRouterCacheProvider 컴포넌트를 사용하는 것이 필수는 아니지만, 스타일이 <head>에 추가되고 <body>에서 렌더링되지 않도록 보장하려면 사용하는 것이 권장돼요. 왜 더 나은지 https://github.com/mui/material-ui/issues/26561#issuecomment-855286153 를 참고하세요.

커스텀 cache (선택 사항)

options prop을 사용해 기본 cache 옵션을 오버라이드할 수 있어요—예를 들어 아래 코드 스니펫은 CSS 키를 css로 변경하는 방법을 보여줘요 (기본은 mui):

  <AppRouterCacheProvider
+   options={{ key: 'css' }}
  >
    {children}
  </AppRouterCacheProvider>

폰트 최적화 (Font optimization)

Next.js 폰트 최적화를 Material UI와 통합하려면 src/app/layout.tsx의 <html> 엘리먼트에 폰트의 className을 추가하세요:

 import { AppRouterCacheProvider } from '@mui/material-nextjs/v15-appRouter';
+import { Roboto } from 'next/font/google';

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

 export default function RootLayout(props) {
   const { children } = props;
   return (
+    <html lang="en" className={roboto.className}>
       <body>
          <AppRouterCacheProvider>
              {children}
          </AppRouterCacheProvider>
       </body>
     </html>
   );
 }

이 접근 방식은 테마의 기본 fontFamily를 그대로 유지하므로 Material UI의 Roboto에 맞춰진 typography 자간(letter-spacing) 값이 보존돼요. Next.js는 빌드 시 폰트를 프리로드하고 자체 호스팅하므로, 브라우저는 "Roboto"를 참조하는 모든 엘리먼트( Material UI 컴포넌트 포함)에 이 폰트를 사용해요.

⚠️ 테마에서 typography.fontFamily를 var(--font-roboto)로 설정하는 것은 피하세요. Material UI는 fontFamily가 기본 폰트 스택과 정확히 일치할 때만 Roboto 특화 자간을 적용해요. CSS 변수는 이 검사를 우회해서 모든 typography 변형에서 자간을 제거해요. Roboto 대신 커스텀 폰트를 사용한다면 아래 Custom font를 참고하세요.

커스텀 폰트 (Custom font)

Roboto가 아닌 커스텀 폰트를 사용하려면 CSS 변수로 로드하고 테마에 typography.fontFamily를 설정하세요. 'use client' 지시어가 있는 테마 파일을 만드세요:

'use client';
import { createTheme } from '@mui/material/styles';

const theme = createTheme({
  typography: {
    fontFamily: 'var(--font-inter)',
  },
});

export default theme;

그런 다음 src/app/layout.tsx에서 variable 이름으로 폰트를 로드하고 <html> 엘리먼트에 적용하세요:

 import { AppRouterCacheProvider } from '@mui/material-nextjs/v15-appRouter';
+import { Inter } from 'next/font/google';
+import { ThemeProvider } from '@mui/material/styles';
+import theme from '../theme';

+const inter = Inter({
+  subsets: ['latin'],
+  display: 'swap',
+  variable: '--font-inter',
+});

 export default function RootLayout(props) {
   const { children } = props;
   return (
+    <html lang="en" className={inter.variable}>
       <body>
          <AppRouterCacheProvider>
+           <ThemeProvider theme={theme}>
              {children}
+           </ThemeProvider>
          </AppRouterCacheProvider>
       </body>
     </html>
   );
 }

테마링에 대해 더 알아보려면 테마링 가이드 페이지를 확인하세요.

CSS 테마 변수 (CSS theme variables)

CSS 테마 변수를 사용하려면 cssVariables 플래그를 활성화하세요:

 'use client';
 const theme = createTheme({
+  cssVariables: true,
 });

CSS 테마 변수의 장점과 SSR 플리커 방지 방법에 대해 더 알아보세요.

다른 스타일링 솔루션 사용하기

Emotion이 아닌 다른 스타일링 솔루션으로 Material UI 컴포넌트를 커스터마이즈한다면, options prop에서 enableCssLayer: true를 설정하세요:

<AppRouterCacheProvider options={{ enableCssLayer: true }}>

이 옵션은 Material UI가 생성한 스타일이 CSS @layer mui 규칙으로 감싸지도록 보장해요. 이 규칙은 CSS Modules, Tailwind CSS, 또는 심지어 @layer를 사용하지 않는 순수 CSS와 함께 Material UI를 사용할 때 익명 레이어 스타일에 의해 오버라이드돼요.

더 자세한 내용은 MDN CSS layer 문서를 참고하세요.

Next.js v16 클라이언트 컴포넌트 제약

Next.js Link를 Material UI component prop에 전달할 때 Functions cannot be passed directly to Client Components 오류가 발생한다면, 다음과 같이 use client 지시어가 있는 래퍼 컴포넌트를 만들어야 해요:

'use client';
import Link, { LinkProps } from 'next/link';

export default Link;

그런 다음 Next.js Link를 래퍼 컴포넌트로 교체하세요:

- import Link from 'next/link';
+ import Link from '../components/Link';
  ...
  <Button component={Link} href="/about" variant="contained">
    Go to About Page
  </Button>

URL 기반 UI와 Suspense 경계

클라이언트 컴포넌트가 URL을 읽는 Next.js App Router 훅—예를 들어 필터, 탭, 페이지네이션을 위한 next/navigation의 useSearchParams()—을 사용할 때, Next.js는 React 트리의 해당 부분 주위에 <Suspense> 경계를 기대해요. 그것이 없으면 Suspense 경계 누락에 대한 빌드 실패나 런타임 메시지가 표시될 수 있어요 (동작은 Next.js 버전과 정적/동적 렌더링 여부에 따라 달라요).

이 패턴은 Material UI에서 흔해요: Table, Tabs, TextField 및 기타 컨트롤은 종종 쿼리 문자열에 동기화되는 클라이언트 컴포넌트로 구현되죠.

권장 구조: 가능하면 page.tsx를 서버 컴포넌트로 유지하고, useSearchParams를 호출하는 클라이언트 하위 트리만 <Suspense>로 감싸세요.

레이아웃에서 공간을 예약하는 UI(툴바, 필터, 탭 바 등)에는 fallback={null}(또는 빈 fallback)을 피하세요. 서버와 초기 스트리밍 HTML이 그 하위 트리를 생략하면 실제 콘텐츠는 클라이언트가 하이드레이션한 후에만 나타나는데, 이는 종종 레이아웃 시프트를 일으키고 CLS를 해쳐요. 로드된 컴포넌트와 동일한 minHeight, flex 방향, 브레이크포인트를 가진 Stack 또는 Box 안의 Material UI Skeleton처럼, 크기와 구조가 최종 UI에 근접한 fallback을 선호하세요.

import { Suspense } from 'react';
import Box from '@mui/material/Box';
import Skeleton from '@mui/material/Skeleton';
import Stack from '@mui/material/Stack';
import OrdersToolbar from './OrdersToolbar';

function OrdersToolbarFallback() {
  return (
    <Stack
      direction="row"
      spacing={2}
      useFlexGap
      sx={{ flexWrap: 'wrap', alignItems: 'center', minHeight: 56 }}
    >
      <Skeleton
        variant="rounded"
        height={40}
        sx={{ minWidth: 200, flexGrow: { xs: 1, sm: 0 } }}
      />
      <Skeleton variant="rounded" width={120} height={40} />
      <Box sx={{ flexGrow: 1 }} />
      <Skeleton variant="rounded" width={100} height={40} />
    </Stack>
  );
}

export default function Page() {
  return (
    <Suspense fallback={<OrdersToolbarFallback />}>
      <OrdersToolbar />
    </Suspense>
  );
}

OrdersToolbar는 useSearchParams()를 호출하고 Material UI 컴포넌트를 렌더링하는 'use client'로 표시된 파일이 될 거예요. 실재 툴바(또는 필터 행)에 최대한 가깝게 fallback의 레이아웃과 Skeleton 크기를 조정하세요.

세부 사항과 버전별 참고 사항은 Next.js 문서의 useSearchParams를 참고하세요.

Pages Router

이 섹션에서는 SSR(서버 사이드 렌더링)과 SSG(정적 사이트 생성) 모두에 대해 Next.js Pages Router와 Material UI를 통합하는 방법을 살펴볼게요.

의존성 설치하기

먼저 @mui/material과 next가 이미 설치되어 있는지 확인하세요. 그런 다음 아래 명령어 중 하나를 실행해 의존성을 설치합니다.

npm install @mui/material-nextjs @emotion/cache @emotion/server
pnpm add @mui/material-nextjs @emotion/cache @emotion/server
yarn add @mui/material-nextjs @emotion/cache @emotion/server

구성 (Configuration)

pages/_document.tsx 파일 안에서:

  • documentGetInitialProps를 import 해서 Document의 getInitialProps로 사용한다.
  • DocumentHeadTags를 import 해서 <Head> 안에서 렌더링한다.
+import {
+  DocumentHeadTags,
+  documentGetInitialProps,
+} from '@mui/material-nextjs/v15-pagesRouter';
 // or `v1X-pagesRouter` if you are using Next.js v1X

 export default function MyDocument(props) {
   return (
     <Html lang="en">
       <Head>
+        <DocumentHeadTags {...props} />
         ...
       </Head>
       <body>
         <Main />
         <NextScript />
       </body>
     </Html>
   );
 }

+MyDocument.getInitialProps = async (ctx) => {
+  const finalProps = await documentGetInitialProps(ctx);
+  return finalProps;
+};

그런 다음 pages/_app.tsx 안에서 AppCacheProvider 컴포넌트를 import 해서 루트 엘리먼트로 렌더링하세요:

+import { AppCacheProvider } from '@mui/material-nextjs/v15-pagesRouter';
 // Or `v1X-pages` if you are using Next.js v1X

 export default function MyApp(props) {
   return (
+    <AppCacheProvider {...props}>
       <Head>
         ...
       </Head>
       ...
+    </AppCacheProvider>
   );
 }

💡 AppCacheProvider 컴포넌트는 Next.js가 .html 페이지를 클라이언트로 렌더링할 때 서버에서 MUI System이 생성한 CSS를 수집하는 역할을 해요.

AppCacheProvider 컴포넌트를 사용하는 것이 필수는 아니지만, 스타일이 <head>에 추가되고 <body>에서 렌더링되지 않도록 보장하려면 사용하는 것이 권장돼요. 왜 더 나은지 https://github.com/mui/material-ui/issues/26561#issuecomment-855286153 를 참고하세요.

커스텀 cache (선택 사항)

커스텀 Emotion cache를 사용하려면 _document.tsx의 emotionCache 속성에 전달하세요:

 ...

 MyDocument.getInitialProps = async (ctx) => {
   const finalProps = await documentGetInitialProps(ctx, {
+    emotionCache: createCustomCache(),
   });
   return finalProps;
 };
캐스케이드 레이어 (선택 사항)

캐스케이드 레이어(@layer)를 활성화하려면 enableCssLayer: true로 새 cache를 만들고 _document.tsx와 _app.tsx 양쪽의 emotionCache 속성에 전달하세요:

+import { createEmotionCache } from '@mui/material-nextjs/v15-pagesRouter';
 ...

 MyDocument.getInitialProps = async (ctx) => {
   const finalProps = await documentGetInitialProps(ctx, {
+    emotionCache: createEmotionCache({ enableCssLayer: true }),
   });
   return finalProps;
 };
+import { createEmotionCache } from '@mui/material-nextjs/v15-pagesRouter';
  ...

 const clientCache = createEmotionCache({ enableCssLayer: true });

+ export default function MyApp({ emotionCache = clientCache }) {
    return (
+     <AppCacheProvider emotionCache={emotionCache}>
        <Head>
          ...
        </Head>
        ...
      </AppCacheProvider>
    );
  }
앱 향상 (선택 사항)

plugins 속성에 배열을 전달해 앱을 추가 기능으로 향상시킬 수 있어요, 예를 들어 JSS와 styled-components를 사용할 때 서버 사이드 렌더링 스타일 같은 것요.

각 플러그인은 다음 속성을 가져야 해요.

  • enhanceApp: App 컴포넌트를 받아 새 앱 컴포넌트를 반환하는 고차 컴포넌트.
  • resolveProps: 초기 props를 받아 새 props 객체를 반환하는 함수.

실행 시 각 플러그인의 enhanceApp이 위에서 아래로 먼저 호출된 다음, resolveProps에 대해 동일한 프로세스가 반복돼요.

import { ServerStyleSheet } from 'styled-components';

MyDocument.getInitialProps = async (ctx) => {
  const jssSheets = new JSSServerStyleSheets();
  const styledComponentsSheet = new ServerStyleSheet();

  try {
    const finalProps = await documentGetInitialProps(ctx, {
      emotionCache: createEmotionCache(),
      plugins: [
        {
          // styled-components
          enhanceApp: (App) => (props) =>
            styledComponentsSheet.collectStyles(<App {...props} />),
          resolveProps: async (initialProps) => ({
            ...initialProps,
            styles: [
              styledComponentsSheet.getStyleElement(),
              ...initialProps.styles,
            ],
          }),
        },
        {
          // JSS
          enhanceApp: (App) => (props) => jssSheets.collect(<App {...props} />),
          resolveProps: async (initialProps) => {
            const css = jssSheets.toString();
            return {
              ...initialProps,
              styles: [
                ...initialProps.styles,
                <style
                  id="jss-server-side"
                  key="jss-server-side"
                  // eslint-disable-next-line react/no-danger
                  dangerouslySetInnerHTML={{ __html: css }}
                />,
                <style id="insertion-point-jss" key="insertion-point-jss" />,
              ],
            };
          },
        },
      ],
    });
    return finalProps;
  } finally {
    styledComponentsSheet.seal();
  }
};

TypeScript

TypeScript를 사용한다면 Document의 props 인터페이스에 DocumentHeadTagsProps를 추가하세요:

+import type { DocumentHeadTagsProps } from '@mui/material-nextjs/v15-pagesRouter';
 // or `v1X-pagesRouter` if you are using Next.js v1X

+export default function MyDocument(props: DocumentProps & DocumentHeadTagsProps) {
   ...
 }

폰트 최적화 (Font optimization)

Next.js 폰트 최적화를 Material UI와 통합하려면 pages/_app.tsx를 열고 루트 엘리먼트에 폰트의 className을 추가하세요:

 import * as React from 'react';
 import Head from 'next/head';
 import { AppProps } from 'next/app';
 import { AppCacheProvider } from '@mui/material-nextjs/v15-pagesRouter';
+import { Roboto } from 'next/font/google';

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

 export default function MyApp(props: AppProps) {
  const { Component, pageProps } = props;
  return (
    <AppCacheProvider {...props}>
      <Head>...</Head>
+     <main className={roboto.className}>
          <Component {...pageProps} />
+     </main>
    </AppCacheProvider>
  );
 }

이 접근 방식은 테마의 기본 fontFamily를 그대로 유지하므로 Material UI의 Roboto에 맞춰진 typography 자간 값이 보존돼요. Next.js는 빌드 시 폰트를 프리로드하고 자체 호스팅하므로, 브라우저는 "Roboto"를 참조하는 모든 엘리먼트( Material UI 컴포넌트 포함)에 이 폰트를 사용해요.

⚠️ 테마에서 typography.fontFamily를 var(--font-roboto)로 설정하는 것은 피하세요. Material UI는 fontFamily가 기본 폰트 스택과 정확히 일치할 때만 Roboto 특화 자간을 적용해요. CSS 변수는 이 검사를 우회해서 모든 typography 변형에서 자간을 제거해요. Roboto 대신 커스텀 폰트를 사용한다면 아래 Custom font를 참고하세요.

커스텀 폰트 (Custom font)

Roboto가 아닌 커스텀 폰트를 사용하려면 CSS 변수로 로드하고 테마에 typography.fontFamily를 설정하세요. pages/_app.tsx에서:

 import * as React from 'react';
 import Head from 'next/head';
 import { AppProps } from 'next/app';
 import { AppCacheProvider } from '@mui/material-nextjs/v15-pagesRouter';
+import { ThemeProvider, createTheme } from '@mui/material/styles';
+import { Inter } from 'next/font/google';

+const inter = Inter({
+  subsets: ['latin'],
+  display: 'swap',
+  variable: '--font-inter',
+});

+const theme = createTheme({
+  typography: {
+    fontFamily: 'var(--font-inter)',
+  },
+});

 export default function MyApp(props: AppProps) {
  const { Component, pageProps } = props;
  return (
    <AppCacheProvider {...props}>
      <Head>...</Head>
+     <ThemeProvider theme={theme}>
+       <main className={inter.variable}>
          <Component {...pageProps} />
+       </main>
+     </ThemeProvider>
    </AppCacheProvider>
  );
 }

테마링에 대해 더 알아보려면 테마링 가이드를 확인하세요.

CSS 테마 변수 (CSS theme variables)

CSS 테마 변수를 사용하려면 cssVariables 플래그를 활성화하세요:

 'use client';
 const theme = createTheme({
+  cssVariables: true,
 });

CSS 테마 변수의 장점과 SSR 플리커 방지 방법에 대해 더 알아보세요.

더 알아보기 (Learn more)