본문 바로가기
카테고리 없음

Next.js에서 "use client"과 메타데이터 오류 해결하기

by 3급우사기 2024. 5. 31.

오류가 뜬다

문제상황

Error: × You are attempting to export "metadata" from a component marked with "use client", which is disallowed. Either remove the export, or the "use client" directive.

 

layoyt.tsx파일에서 "use client" 지시문 사용하다가 메타데이터 내보내기를 하면 오류가 난다.

진짜 짜증남. 근데 해결 방법은 간단하다. 메타데이터는 서버 컴포넌트에서 내보내고, 클라이언트 컴포넌트는 따로 파일로 분리하면 됨.

 

 

해결법


1.서버 컴포넌트에서 메타데이터 내보내기

// layout.tsx - 서버 컴포넌트
import { Metadata } from 'next'
import ExampleClientComponent from '@/components/ExampleClientComponent'
 
export const metadata: Metadata = {
  title: '페이지 제목',
  description: '페이지 설명',
}

export default function Layout({ children }) {
  return (
    <>
      <ExampleClientComponent>
        {children}
      </ExampleClientComponent>
    </>
  )
}



2. 클라이언트 컴포넌트 파일 따로 만들기

// ExampleClientComponent.tsx - 클라이언트 컴포넌트
'use client'
 
export default function ExampleClientComponent({ children }) {
  return (
    <>
      {/* 클라이언트 컴포넌트 코드 */}
      {children}
    </>
  )
}


이렇게 하면 끝! 서버 컴포넌트에서 메타데이터 내보내고, 클라이언트 컴포넌트는 따로 파일로 분리해서 "use client" 지시문을 사용할 수 있음. 서버 컴포넌트에서 클라이언트 컴포넌트 렌더링하면서 필요한 props도 넘길 수 있으니까 문제없이 작동함.

 

 

정리


메타데이터는 서버 컴포넌트에서 내보내고, 클라이언트 컴포넌트는 따로 분리!