본문으로 건너뛰기

제목과 설명

Next.js 목차 화면 다듬기 레슨 33 / 47

목차

metadata는 레이아웃 · 쪽 파일에서 내보내는 객체로, Next.js가 이것을 읽어 받은 HTML의 <title> · 설명 태그를 만듭니다. 이 레슨은 루트 레이아웃에 앱 이름을, 쪽마다 제목을 달고, 주소마다 다른 레시피 제목은 generateMetadata로 정해 탭 제목과 받은 HTML에서 확인합니다.

지금 레시피 보관함의 탭에는 제목 대신 주소가 보입니다. 프로젝트 파일 읽기에서 루트 layout.tsx의 metadata를 지웠기 때문입니다. 탭 제목은 문서 머리의 <title>에서 오고, 즐겨찾기 이름과 검색 결과의 제목으로도 쓰입니다(문서 뼈대).

1루트 레이아웃에 앱 이름 달기

루트 app/layout.tsx에서 metadata를 내보냅니다. 타입 Metadata는 next에서 가져옵니다.

app/layout.tsx
import type {
  Metadata,
} from 'next';
…
export const
  metadata: Metadata = {
    title: {
      template:
        '%s · 레시피 보관함',
      default: '레시피 보관함',
    },
    description:
      '내 레시피를 모아 두는 곳',
  };
…
  • title.default는 제목을 따로 정하지 않은 쪽의 제목입니다.
  • title.template은 아래 폴더의 쪽이 정한 제목을 끼울 틀입니다. 쪽의 제목이 %s 자리에 들어갑니다. 루트 레이아웃과 같은 폴더인 첫 쪽 app/page.tsx의 제목에는 끼우지 않습니다(Next.js 문서 generateMetadata — title.template).
  • description은 <meta name="description">⁠이 됩니다. 검색 결과에서 제목 아래 보이는 글입니다.
app/layout.tsx 전체 · 받은 HTML 그대로
app/layout.tsx
import type {
  Metadata,
} from 'next';
import './globals.css';
import TabBar from
  '@/components/TabBar';

export const
  metadata: Metadata = {
    title: {
      template:
        '%s · 레시피 보관함',
      default: '레시피 보관함',
    },
    description:
      '내 레시피를 모아 두는 곳',
  };

function RootLayout({
  children,
}: LayoutProps<'/'>) {
  return (
    <html lang="ko">
      <body>
        <TabBar />
        {children}
        <footer>바닥글</footer>
      </body>
    </html>
  );
}

export default RootLayout;
HTML
<html lang="ko">
<head>
<meta charSet="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<link rel="stylesheet" href="/_next/static/chunks/app_globals_0yg4wg8plh8sv.css" data-precedence="next_static/chunks/app_globals_0yg4wg8plh8sv.css"/>
<link rel="preload" as="script" fetchPriority="low" href="/_next/static/chunks/%5Bturbopack%5D_browser_dev_hmr-client_hmr-client_ts_0oc3hfxhoz2c3._.js"/>
<title>레시피 보관함</title>
<meta name="description" content="내 레시피를 모아 두는 곳"/>
<link rel="icon" href="/favicon.ico?favicon.117ezoe8m31dk.ico" sizes="48x48" type="image/x-icon"/>
</head>
<body>
<nav>
<a href="/recipes">목록</a>·<a href="/stats">▸ 통계</a>
</nav>
<h1>통계</h1>
<template id="B:0">
</template>
<p>세는 중</p>
<footer>바닥글</footer>
<div hidden id="S:0">
<p>모두 4개</p>
</div>
</body>
</html>
결과 화면탭: 레시피 보관함

저장하고 /stats를 새로 고치면 탭에 레시피 보관함이 보입니다. 위 접기의 받은 HTML은 <html>부터 끝까지입니다. script · 주석 · style 속성과 <body> 맨 앞의 빈 <div hidden>을 빼고, 태그마다 줄을 나눴습니다. <head> 안에는 Next.js가 늘 넣는 <meta> · <link> 줄 사이에 <title>레시피 보관함</title>⁠과 설명을 담은 <meta name="description">⁠이 있습니다. 통계 쪽은 제목을 정하지 않아 default가 쓰였습니다. 브라우저에서는 페이지 소스 보기(주소 앞에 view-source:)로 같은 <head>를 봅니다.

2쪽마다 제목 달기

목록 쪽 app/recipes/page.tsx에도 metadata를 내보냅니다. 쪽에서는 제목 글 하나면 됩니다.

app/recipes/page.tsx
…
import type {
  Metadata,
} from 'next';

export const
  metadata: Metadata = {
    title: '목록',
  };
…
app/recipes/page.tsx 전체
app/recipes/page.tsx
import {
  Suspense,
} from 'react';
import Link from 'next/link';
import type {
  Metadata,
} from 'next';
import FavoriteButton from
  '@/components/FavoriteButton';
import SearchBar from
  '@/components/SearchBar';
import {
  getRecipes,
  type Recipe,
} from '@/lib/recipes';

export const
  metadata: Metadata = {
    title: '목록',
  };

const item = (r: Recipe) => (
  <li key={r.id}>
    <Link
      href={`/recipes/${r.id}`}
    >
      {r.title}
    </Link>
    <FavoriteButton
      recipe={r}
    />
  </li>
);

// 1. 기다리는 일을 자식으로
async function RecipeList({
  searchParams,
}: {
  searchParams: Promise<{
    q?: string | string[];
  }>;
}) {
  // 2. 자식에서 await로 읽기
  const { q } =
    await searchParams;
  const word =
    typeof q === 'string'
      ? q
      : '';
  const recipes =
    await getRecipes();
  const found = recipes.filter(
    (r) =>
      r.title.includes(word),
  );
  return (
    <ul>{found.map(item)}</ul>
  );
}

// 3. 쪽에서 Suspense로 감싸기
function Page({
  searchParams,
}: PageProps<'/recipes'>) {
  return (
    <>
      <SearchBar />
      <Suspense
        fallback={
          <p>목록을 읽는 중</p>
        }
      >
        <RecipeList
          searchParams={
            searchParams
          }
        />
      </Suspense>
    </>
  );
}

export default Page;

저장하고 /recipes를 새로 고치면 탭 제목은 목록 · 레시피 보관함입니다. 쪽의 목록이 루트 틀의 %s 자리에 들어갔습니다. 받은 HTML의 <head>에도 <title>목록 · 레시피 보관함</title>⁠이 있습니다.

받은 HTML 그대로

아래는 1절 그대로의 루트 레이아웃과, 저장한 뒤 /recipes를 연 받은 HTML입니다.

app/layout.tsx
import type {
  Metadata,
} from 'next';
import './globals.css';
import TabBar from
  '@/components/TabBar';

export const
  metadata: Metadata = {
    title: {
      template:
        '%s · 레시피 보관함',
      default: '레시피 보관함',
    },
    description:
      '내 레시피를 모아 두는 곳',
  };

function RootLayout({
  children,
}: LayoutProps<'/'>) {
  return (
    <html lang="ko">
      <body>
        <TabBar />
        {children}
        <footer>바닥글</footer>
      </body>
    </html>
  );
}

export default RootLayout;
HTML
<html lang="ko">
<head>
<meta charSet="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<link rel="stylesheet" href="/_next/static/chunks/app_globals_0yg4wg8plh8sv.css" data-precedence="next_static/chunks/app_globals_0yg4wg8plh8sv.css"/>
<link rel="preload" as="script" fetchPriority="low" href="/_next/static/chunks/%5Bturbopack%5D_browser_dev_hmr-client_hmr-client_ts_0oc3hfxhoz2c3._.js"/>
<title>목록 · 레시피 보관함</title>
<meta name="description" content="내 레시피를 모아 두는 곳"/>
<link rel="icon" href="/favicon.ico?favicon.117ezoe8m31dk.ico" sizes="48x48" type="image/x-icon"/>
</head>
<body>
<nav>
<a href="/recipes">▸ 목록</a>·<a href="/stats">통계</a>
</nav>
<section>
<h1>레시피</h1>
<form action="/recipes">
<input name="q"/>
<button>찾기</button>
</form>
<template id="B:0">
</template>
<p>목록을 읽는 중</p>
</section>
<footer>바닥글</footer>
<div hidden id="S:0">
<ul>
<li>
<a href="/recipes/r1">김치볶음밥</a>
<button>★</button>
</li>
<li>
<a href="/recipes/r2">토마토 파스타</a>
<button>☆</button>
</li>
<li>
<a href="/recipes/r3">계란말이</a>
<button>☆</button>
</li>
<li>
<a href="/recipes/r4">바나나 팬케이크</a>
<button>★</button>
</li>
</ul>
</div>
</body>
</html>
결과 화면탭: 목록 · 레시피 보관함

metadata는 서버 컴포넌트 파일에서만 내보냅니다(Next.js 문서 generateMetadata — 'only supported in Server Components'). 맨 위에 'use client'를 단 쪽 파일에서 내보내면, 개발 판은 그 쪽이 500이 되고 빌드도 멈춥니다.

3주소마다 다른 제목 — generateMetadata

자세히 쪽은 주소의 id에 따라 레시피가 다릅니다. 이렇게 값을 읽어야 정해지는 제목은 metadata 대신 generateMetadata 함수로 냅니다. 자세히 쪽 파일의 generateStaticParams 아래에 더하고, RecipeDetail과 같은 꼴로 params를 받습니다.

app/recipes/[id]/page.tsx
…
export const
  generateMetadata = async ({
    params,
  }: {
    params: Promise<{
      id: string;
    }>;
  }) => {
…

몸에서는 같은 getRecipe로 레시피를 찾아, 제목을 담은 객체를 돌려줍니다.

app/recipes/[id]/page.tsx
…
    const { id } = await params;
    const found =
      await getRecipe(id);
    return {
      title: found?.title,
    };
  };
…

이제 /recipes/r3의 탭 제목은 어떻게 될까요? 고른 뒤 펼쳐 보세요. 맞혀 보기는 점수에 들지 않습니다.

  • ① 계란말이
  • ② 계란말이 · 레시피 보관함
  • ③ 레시피 보관함 — 루트의 default
결과 보기

②입니다. 아래는 1절 그대로의 app/layout.tsx, generateMetadata를 더한 쪽 파일, 개발 서버를 새로 띄운 뒤 처음 연 /recipes/r3의 받은 HTML(다듬음)과 서버 터미널입니다. 시간은 다를 수 있습니다.

app/layout.tsx
import type {
  Metadata,
} from 'next';
import './globals.css';
import TabBar from
  '@/components/TabBar';

export const
  metadata: Metadata = {
    title: {
      template:
        '%s · 레시피 보관함',
      default: '레시피 보관함',
    },
    description:
      '내 레시피를 모아 두는 곳',
  };

function RootLayout({
  children,
}: LayoutProps<'/'>) {
  return (
    <html lang="ko">
      <body>
        <TabBar />
        {children}
        <footer>바닥글</footer>
      </body>
    </html>
  );
}

export default RootLayout;
app/recipes/[id]/page.tsx
import {
  Suspense,
} from 'react';
import {
  notFound,
} from 'next/navigation';
import {
  getRecipe,
  getRecipes,
} from '@/lib/recipes';
import Fold from
  '@/components/Fold';

export const
  generateStaticParams =
    async () => {
      const list =
        await getRecipes();
      return list.map((r) => ({
        id: r.id,
      }));
    };

export const
  generateMetadata = async ({
    params,
  }: {
    params: Promise<{
      id: string;
    }>;
  }) => {
    const { id } = await params;
    const found =
      await getRecipe(id);
    return {
      title: found?.title,
    };
  };

function Ingredients({
  items,
}: {
  items: string[];
}) {
  return (
    <ul>
      {items.map((i) => (
        <li key={i}>{i}</li>
      ))}
    </ul>
  );
}

// 1. 기다리는 일을 자식으로
async function RecipeDetail({
  params,
}: {
  params: Promise<{
    id: string;
  }>;
}) {
  // 2. 자식에서 await로 읽기
  const { id } = await params;
  const found =
    await getRecipe(id);
  if (!found) {
    notFound();
  }
  const items =
    found.ingredients;
  return (
    <>
      <h2>{found.title}</h2>
      <Fold>
        <Ingredients
          items={items}
        />
      </Fold>
    </>
  );
}

// 3. 쪽에서 Suspense로 감싸기
function Page({
  params,
}: PageProps<'/recipes/[id]'>) {
  return (
    <Suspense
      fallback={
        <p>레시피를 읽는 중</p>
      }
    >
      <RecipeDetail
        params={params}
      />
    </Suspense>
  );
}

export default Page;
HTML
<div hidden="">
<template id="B:0">
</template>
</div>
<nav>
<a href="/recipes">▸ 목록</a>·<a href="/stats">통계</a>
</nav>
<section>
<h1>레시피</h1>
<template id="B:1">
</template>
<p>레시피를 읽는 중</p>
<template id="B:2">
</template>
</section>
<footer>바닥글</footer>
<title>계란말이 · 레시피 보관함</title>
<meta name="description" content="내 레시피를 모아 두는 곳"/>
<link rel="icon" href="/favicon.ico?favicon.117ezoe8m31dk.ico" sizes="48x48" type="image/x-icon"/>
<div hidden id="S:1">
<h2>계란말이</h2>
<section>
<button>재료 보기</button>
</section>
</div>
<div hidden id="S:2">
</div>
<div hidden id="S:0">
</div>
결과 화면탭: 계란말이 · 레시피 보관함
> recipe-box-next@0.1.0 dev
> next dev

▲ Next.js 16.4.6 (Turbopack)
- Local:         http://localhost:3000
- Network:       http://127.131.113.34:3000
✓ Ready in 222ms
✓ Running next.config.ts took 1021ms
- Cache Components enabled
- Partial Prefetching enabled

레시피 파일 읽음
 Cache  레시피 파일 읽음
레시피 하나 읽음 r3
레시피 파일 읽음
 Cache  레시피 하나 읽음 r3
 Cache  레시피 파일 읽음
 Cache  레시피 파일 읽음
 GET /recipes/r3 200 in 350ms (next.js: 65ms, generate-params: 190ms, application-code: 95ms)
 Cache  레시피 하나 읽음 r3
 Cache  레시피 파일 읽음
 Cache  레시피 하나 읽음 r3
 Cache  레시피 파일 읽음

쪽의 제목 계란말이가 루트 틀에 끼워졌습니다. generateMetadata가 돌려준 제목도 1절의 template을 따릅니다.

받은 HTML에서 <title>이 <head>가 아니라 <footer> 바로 뒤에 있습니다. 제목을 정하려면 레시피를 읽어야 해서, Next.js는 껍데기를 먼저 보내고 제목이 정해지면 <body> 끝에 이어 붙입니다(Next.js 문서 generateMetadata — Streaming metadata). 브라우저는 이 <title>도 탭 제목으로 씁니다. 레시피를 기억해 둔 뒤 다시 열면 제목이 바로 정해져 <head>에 듭니다. 배포 판은 빌드 때 레시피를 읽어 두어, 처음 열어도 <title>이 <head>에 있습니다.

서버 터미널의 꼬리표 없는 레시피 하나 읽음 r3은 한 줄입니다. generateMetadata와 RecipeDetail이 같은 getRecipe('r3')를 불렀지만, 'use cache'로 기억한 함수라 한 번만 돌았습니다. 꼬리표 없는 레시피 파일 읽음은 인자가 열쇠다에서 본, 섞여 찍히는 줄이라 세지 않습니다.

예제

통계 쪽에도 제목을 답니다. 2절의 목록 쪽과 같은 꼴입니다.

app/stats/page.tsx
…
import type {
  Metadata,
} from 'next';
…
export const
  metadata: Metadata = {
    title: '통계',
  };
…
app/stats/page.tsx 전체
app/stats/page.tsx
import {
  Suspense,
} from 'react';
import type {
  Metadata,
} from 'next';
import Count from
  '@/components/Count';
import {
  getRecipes,
} from '@/lib/recipes';

export const
  metadata: Metadata = {
    title: '통계',
  };

export default function Page() {
  const recipes = getRecipes();
  // 3. 쪽에서 Suspense로 감싸기
  return (
    <>
      <h1>통계</h1>
      <Suspense
        fallback={<p>세는 중</p>}
      >
        <Count
          recipes={recipes}
        />
      </Suspense>
    </>
  );
}

저장하고 /stats를 새로 고치면 탭 제목이 레시피 보관함에서 통계 · 레시피 보관함으로 바뀝니다. 탭 막대의 목록 · 통계를 오가며 탭 제목이 바뀌는지 보세요. 제목을 정하지 않은 첫 쪽 /은 그대로 레시피 보관함입니다.

받은 HTML 그대로

아래는 1절 그대로의 루트 레이아웃과, 저장한 뒤 /stats를 연 받은 HTML입니다. <title>이 통계 · 레시피 보관함입니다.

app/layout.tsx
import type {
  Metadata,
} from 'next';
import './globals.css';
import TabBar from
  '@/components/TabBar';

export const
  metadata: Metadata = {
    title: {
      template:
        '%s · 레시피 보관함',
      default: '레시피 보관함',
    },
    description:
      '내 레시피를 모아 두는 곳',
  };

function RootLayout({
  children,
}: LayoutProps<'/'>) {
  return (
    <html lang="ko">
      <body>
        <TabBar />
        {children}
        <footer>바닥글</footer>
      </body>
    </html>
  );
}

export default RootLayout;
HTML
<html lang="ko">
<head>
<meta charSet="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<link rel="stylesheet" href="/_next/static/chunks/app_globals_0yg4wg8plh8sv.css" data-precedence="next_static/chunks/app_globals_0yg4wg8plh8sv.css"/>
<link rel="preload" as="script" fetchPriority="low" href="/_next/static/chunks/%5Bturbopack%5D_browser_dev_hmr-client_hmr-client_ts_0oc3hfxhoz2c3._.js"/>
<title>통계 · 레시피 보관함</title>
<meta name="description" content="내 레시피를 모아 두는 곳"/>
<link rel="icon" href="/favicon.ico?favicon.117ezoe8m31dk.ico" sizes="48x48" type="image/x-icon"/>
</head>
<body>
<nav>
<a href="/recipes">목록</a>·<a href="/stats">▸ 통계</a>
</nav>
<h1>통계</h1>
<template id="B:0">
</template>
<p>세는 중</p>
<footer>바닥글</footer>
<div hidden id="S:0">
<p>모두 4개</p>
</div>
</body>
</html>
결과 화면탭: 통계 · 레시피 보관함

자주 틀리는 곳

틀린 생각: 단원 6까지 탭에 주소가 보인 것은 쪽 파일이 잘못돼서다.

맞는 규칙: 탭 제목은 <title>에서 옵니다. 루트 레이아웃에 metadata가 없어 <title>이 없었습니다. 루트에 title을 달면 모든 쪽에 제목이 섭니다.

틀린 생각: 'use client'를 단 쪽 파일에서도 metadata를 내보낼 수 있다.

맞는 규칙: metadata · generateMetadata는 서버 컴포넌트 파일에서만 내보냅니다. 클라이언트 쪽 파일에서 내보내면 You are attempting to export⁠가 든 오류가 나고, 개발 판 쪽은 500, 빌드는 멈춥니다. 상태를 쓰는 부분만 다른 파일로 떼어 냅니다('use client' 경계).

확인 문제

문제 1. 루트 레이아웃의 title에 template: '%s · 레시피 보관함'⁠과 default: '레시피 보관함'이 있습니다. 첫 쪽 app/page.tsx에는 metadata가 없습니다. /의 탭 제목은 무엇일까요?

  • ① %s · 레시피 보관함
  • ② 레시피 보관함
  • ③ 제목 없이 주소가 보인다
정답

②입니다. 제목을 정하지 않은 쪽에는 default가 쓰입니다(1절).

  • ① template은 아래 폴더의 쪽이 제목을 정했을 때 그 제목을 끼우는 틀입니다. 첫 쪽은 루트 레이아웃과 같은 폴더라, 제목을 정해도 틀에 끼우지 않습니다.
  • ③ 주소가 보인 것은 루트에 metadata가 없던 단원 6까지입니다.

문제 2. 주소의 id에 따라 받은 HTML의 <title>을 바꾸려면 어떻게 할까요?

  • ① 쪽 파일에서 metadata를 내보내고 title에 params.id를 적는다
  • ② 'use client' 파일에서 document.title을 바꾼다
  • ③ 쪽 파일에서 generateMetadata를 내보내 params로 찾은 제목을 돌려준다
정답

③입니다. 값을 읽어야 정해지는 제목은 generateMetadata가 돌려줍니다(3절).

  • ① metadata는 고정된 객체라 요청마다 다른 params를 쓸 수 없습니다.
  • ② 받은 HTML에는 제목이 없어, 검색 결과에 보일 제목이 서지 않습니다.

문제 3. 개발 판에서 /recipes/r3을 처음 열 때, generateMetadata와 RecipeDetail이 둘 다 getRecipe('r3')를 부릅니다. 서버 터미널에 꼬리표 없는 레시피 하나 읽음 r3은 몇 줄 찍힐까요?

  • ① 한 줄
  • ② 두 줄
  • ③ 0줄
정답

①입니다. 'use cache'로 기억한 함수라 같은 인자의 두 번째 부름은 파일을 읽지 않습니다(3절).

  • ② 두 곳이 불러도 기억이 한 번의 결과를 나눠 씁니다.
  • ③ 처음 연 때라 기억이 비어 한 번은 읽습니다.
이 레슨에서 바꾼 파일

app/layout.tsx — Metadata import · 루트 metadata

app/layout.tsx
import type {
  Metadata,
} from 'next';
import './globals.css';
import TabBar from
  '@/components/TabBar';

export const
  metadata: Metadata = {
    title: {
      template:
        '%s · 레시피 보관함',
      default: '레시피 보관함',
    },
    description:
      '내 레시피를 모아 두는 곳',
  };

function RootLayout({
  children,
}: LayoutProps<'/'>) {
  return (
    <html lang="ko">
      <body>
        <TabBar />
        {children}
        <footer>바닥글</footer>
      </body>
    </html>
  );
}

export default RootLayout;

app/recipes/page.tsx — 목록 쪽 제목

app/recipes/page.tsx
import {
  Suspense,
} from 'react';
import Link from 'next/link';
import type {
  Metadata,
} from 'next';
import FavoriteButton from
  '@/components/FavoriteButton';
import SearchBar from
  '@/components/SearchBar';
import {
  getRecipes,
  type Recipe,
} from '@/lib/recipes';

export const
  metadata: Metadata = {
    title: '목록',
  };

const item = (r: Recipe) => (
  <li key={r.id}>
    <Link
      href={`/recipes/${r.id}`}
    >
      {r.title}
    </Link>
    <FavoriteButton
      recipe={r}
    />
  </li>
);

// 1. 기다리는 일을 자식으로
async function RecipeList({
  searchParams,
}: {
  searchParams: Promise<{
    q?: string | string[];
  }>;
}) {
  // 2. 자식에서 await로 읽기
  const { q } =
    await searchParams;
  const word =
    typeof q === 'string'
      ? q
      : '';
  const recipes =
    await getRecipes();
  const found = recipes.filter(
    (r) =>
      r.title.includes(word),
  );
  return (
    <ul>{found.map(item)}</ul>
  );
}

// 3. 쪽에서 Suspense로 감싸기
function Page({
  searchParams,
}: PageProps<'/recipes'>) {
  return (
    <>
      <SearchBar />
      <Suspense
        fallback={
          <p>목록을 읽는 중</p>
        }
      >
        <RecipeList
          searchParams={
            searchParams
          }
        />
      </Suspense>
    </>
  );
}

export default Page;

app/recipes/[id]/page.tsx — generateMetadata

app/recipes/[id]/page.tsx
import {
  Suspense,
} from 'react';
import {
  notFound,
} from 'next/navigation';
import {
  getRecipe,
  getRecipes,
} from '@/lib/recipes';
import Fold from
  '@/components/Fold';

export const
  generateStaticParams =
    async () => {
      const list =
        await getRecipes();
      return list.map((r) => ({
        id: r.id,
      }));
    };

export const
  generateMetadata = async ({
    params,
  }: {
    params: Promise<{
      id: string;
    }>;
  }) => {
    const { id } = await params;
    const found =
      await getRecipe(id);
    return {
      title: found?.title,
    };
  };

function Ingredients({
  items,
}: {
  items: string[];
}) {
  return (
    <ul>
      {items.map((i) => (
        <li key={i}>{i}</li>
      ))}
    </ul>
  );
}

// 1. 기다리는 일을 자식으로
async function RecipeDetail({
  params,
}: {
  params: Promise<{
    id: string;
  }>;
}) {
  // 2. 자식에서 await로 읽기
  const { id } = await params;
  const found =
    await getRecipe(id);
  if (!found) {
    notFound();
  }
  const items =
    found.ingredients;
  return (
    <>
      <h2>{found.title}</h2>
      <Fold>
        <Ingredients
          items={items}
        />
      </Fold>
    </>
  );
}

// 3. 쪽에서 Suspense로 감싸기
function Page({
  params,
}: PageProps<'/recipes/[id]'>) {
  return (
    <Suspense
      fallback={
        <p>레시피를 읽는 중</p>
      }
    >
      <RecipeDetail
        params={params}
      />
    </Suspense>
  );
}

export default Page;

app/stats/page.tsx — 통계 쪽 제목

app/stats/page.tsx
import {
  Suspense,
} from 'react';
import type {
  Metadata,
} from 'next';
import Count from
  '@/components/Count';
import {
  getRecipes,
} from '@/lib/recipes';

export const
  metadata: Metadata = {
    title: '통계',
  };

export default function Page() {
  const recipes = getRecipes();
  // 3. 쪽에서 Suspense로 감싸기
  return (
    <>
      <h1>통계</h1>
      <Suspense
        fallback={<p>세는 중</p>}
      >
        <Count
          recipes={recipes}
        />
      </Suspense>
    </>
  );
}

끝까지 내려오면 저절로 표시됩니다. 이 기기에만 저장합니다.

Next.js 목차로