서버 컴포넌트는 async 함수로 써서 파일 같은 바깥 데이터를 await로 읽을 수 있습니다. 이 레슨은 레시피 넷을 코드 안 배열에서 JSON 파일로 옮겨 목록 쪽과 자세히 쪽이 서버에서 읽게 하고, 그렇게 고친 쪽을 빌드가 어떻게 미리 그리는지 봅니다.
배열에 두면 레시피 하나를 더할 때도 코드를 고쳐야 합니다. 파일에 두면 데이터만 바꿀 수 있지만, 쪽을 그릴 때 파일을 읽어야 하고 읽기는 끝날 때까지 기다리는 일입니다.
JS 다시 보기: await는 Promise가 풀린 값을 기다려 꺼냈고(async와 await), JSON.parse는 JSON 글을 값으로 바꿨습니다(JSON: 객체와 글 사이). TypeScript 다시 보기: 바깥에서 온 값은 unknown으로 받아 확인 함수로 좁혔습니다(바깥 값 확인하기).
이 단원을 이미 안다면 단원 연습 문제의 진단 문항부터 풀고 틀린 레슨만 보세요 — 건너뛴 레슨은 끝의 바꾼 파일 접기를 붙여 넣고 넘어갑니다. 그 전에 단원 1~3 연습 문제로 레시피 보관함에 더한 쪽을 지웁니다. 두면 빌드가 멈춥니다(목록은 그 연습 문제의 진단 끝 접기 '레슨을 건너뛸 때').
1레시피를 파일에서 읽기
개발 서버는 켜 둔 채 따라 합니다. 프로젝트 뿌리(app/ 폴더 곁)에 data 폴더를 만들고, 배열 recipes의 레시피 넷을 JSON으로 옮긴 recipes.json을 둡니다. lib/recipes.ts에는 readFile을 가져오는 줄과 함수 셋 isRecipe · getRecipes · getRecipe를 더합니다. 두 파일 전체는 조각 아래 접기에 있습니다. 배열은 자세히 쪽이 아직 읽으니 예제까지 둡니다.
…
export const getRecipes =
async () => {
const text = await readFile(
'data/recipes.json',
'utf8',
);
const data: unknown =
JSON.parse(text);
return Array.isArray(data)
? data.filter(isRecipe)
: [];
};
…node:fs/promises는 Node.js에 든 파일 모듈이고, readFile은 파일을 다 읽으면 그 글로 풀리는 Promise를 줍니다. 경로는 서버를 띄운 프로젝트 뿌리에서 셉니다. 읽은 값은 unknown으로 받아, 배열이면 isRecipe(isOrder와 같은 꼴)를 지난 레시피만 남깁니다. getRecipe(id)는 그 목록에서 id가 같은 레시피를 찾습니다.
data/recipes.json · lib/recipes.ts 전체
[
{
"id": "r1",
"title": "김치볶음밥",
"category": "한식",
"minutes": 15,
"ingredients": [
"밥",
"김치",
"달걀"
],
"favorite": true
},
{
"id": "r2",
"title": "토마토 파스타",
"category": "양식",
"minutes": 25,
"ingredients": [
"파스타",
"토마토"
],
"favorite": false
},
{
"id": "r3",
"title": "계란말이",
"category": "한식",
"minutes": 10,
"ingredients": [
"달걀",
"파"
],
"favorite": false
},
{
"id": "r4",
"title": "바나나 팬케이크",
"category": "디저트",
"minutes": 20,
"ingredients": [
"바나나",
"밀가루",
"우유"
],
"favorite": true
}
]
import {
readFile,
} from 'node:fs/promises';
export interface Recipe {
id: string;
title: string;
category: string;
minutes: number;
ingredients: string[];
favorite: boolean;
}
export const categories = [
'한식',
'양식',
'일식',
'중식',
'디저트',
];
function isRecipe(
v: unknown,
): v is Recipe {
return (
typeof v === 'object' &&
v !== null &&
'id' in v &&
'title' in v &&
'category' in v &&
'minutes' in v &&
'ingredients' in v &&
'favorite' in v &&
typeof v.id === 'string' &&
typeof v.title ===
'string' &&
typeof v.category ===
'string' &&
typeof v.minutes ===
'number' &&
Array.isArray(
v.ingredients,
) &&
typeof v.favorite ===
'boolean'
);
}
export const getRecipes =
async () => {
const text = await readFile(
'data/recipes.json',
'utf8',
);
const data: unknown =
JSON.parse(text);
return Array.isArray(data)
? data.filter(isRecipe)
: [];
};
export const getRecipe =
async (id: string) => {
const list =
await getRecipes();
return list.find(
(r) => r.id === id,
);
};
export const recipes: Recipe[] =
[
{
id: 'r1',
title: '김치볶음밥',
category: '한식',
minutes: 15,
ingredients: [
'밥',
'김치',
'달걀',
],
favorite: true,
},
{
id: 'r2',
title: '토마토 파스타',
category: '양식',
minutes: 25,
ingredients: [
'파스타',
'토마토',
],
favorite: false,
},
{
id: 'r3',
title: '계란말이',
category: '한식',
minutes: 10,
ingredients: [
'달걀',
'파',
],
favorite: false,
},
{
id: 'r4',
title: '바나나 팬케이크',
category: '디저트',
minutes: 20,
ingredients: [
'바나나',
'밀가루',
'우유',
],
favorite: true,
},
];목록 쪽 app/recipes/page.tsx는 import의 recipes를 getRecipes로 바꾸고, Page를 async 함수로 바꿔 맨 위에서 목록을 기다립니다. 머리가 한 줄을 넘어 export default는 맨 아래로 뗍니다.
…
async function Page() {
const recipes =
await getRecipes();
return (
<ul>{recipes.map(item)}</ul>
);
}
export default Page;저장하고 /recipes를 새로 고칩니다. 화면은 뜰까요? 고른 뒤 펼쳐 보세요. 맞혀 보기는 점수에 들지 않습니다.
- ① 뜬다 — 레시피 넷이 그대로 보인다
- ② 뜨지 않는다 — 오류 판이 화면을 덮는다
- ③ 머리 '레시피'만 뜨고 목록 자리는 빈다
결과 보기
①입니다. 아래는 고친 목록 쪽 전체와 받은 HTML(다듬음), 서버 터미널입니다. 시간은 다를 수 있습니다.
import Link from 'next/link';
import FavoriteButton from
'@/components/FavoriteButton';
import {
getRecipes,
type Recipe,
} from '@/lib/recipes';
const item = (r: Recipe) => (
<li key={r.id}>
<Link
href={`/recipes/${r.id}`}
>
{r.title}
</Link>
<FavoriteButton
recipe={r}
/>
</li>
);
async function Page() {
const recipes =
await getRecipes();
return (
<ul>{recipes.map(item)}</ul>
);
}
export default Page;<nav><a href="/recipes">▸ 목록</a>·<a href="/stats">통계</a></nav>
<section>
<h1>레시피</h1>
<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>
</section>
<footer>바닥글</footer>> 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 349ms
✓ Running next.config.ts took 1444ms
- Cache Components enabled
- Partial Prefetching enabled
GET /recipes 200 in 166ms (next.js: 63ms, application-code: 103ms)
Error: Route "/recipes": Next.js encountered uncached data during prerendering.
`fetch(...)` or `connection()` accessed outside of `<Suspense>` prevents the route from being prerendered, blocking the page load and leading to a slower user experience.
Ways to fix this:
- [stream] Provide a placeholder with `<Suspense fallback={...}>` around the data access
- [cache] Cache the data access with `"use cache"` (does not apply to `connection()`)
- [block] Set `export const instant = false` to allow a blocking route
Learn more: https://nextjs.org/docs/messages/blocking-prerender-dynamic
at getRecipes (lib/recipes.ts:51:32)
at Page (app/recipes/page.tsx:24:21)
49 | export const getRecipes =
50 | async () => {
> 51 | const text = await readFile(
| ^
52 | 'data/recipes.json',
53 | 'utf8',
54 | );
서버는 파일을 다 읽은 뒤 목록을 그려 보냈습니다. 그런데 터미널의 요청 줄 아래에 오류 글이 찍혔습니다. 첫 줄은 /recipes를 미리 그리는 동안(during prerendering) 캐시하지 않은 데이터(uncached data)를 만났다는 뜻입니다. 캐시는 읽은 결과를 기억해 두는 일로, 다음 단원에서 봅니다. 아래의 at getRecipes와 > 51 |이 그 데이터를 기다린 readFile 줄입니다. 브라우저 콘솔에도 같은 글이 찍히지만, 개발 서버는 알리기만 하고 화면을 띄웁니다.
2빌드가 미리 그린다 — 규칙 6
개발 서버 터미널에서 Ctrl+C로 서버를 끄고 npm run build를 칩니다. 빌드는 /recipes에서 멈춥니다.
1절 파일 셋 그대로 · 빌드 출력
[
{
"id": "r1",
"title": "김치볶음밥",
"category": "한식",
"minutes": 15,
"ingredients": [
"밥",
"김치",
"달걀"
],
"favorite": true
},
{
"id": "r2",
"title": "토마토 파스타",
"category": "양식",
"minutes": 25,
"ingredients": [
"파스타",
"토마토"
],
"favorite": false
},
{
"id": "r3",
"title": "계란말이",
"category": "한식",
"minutes": 10,
"ingredients": [
"달걀",
"파"
],
"favorite": false
},
{
"id": "r4",
"title": "바나나 팬케이크",
"category": "디저트",
"minutes": 20,
"ingredients": [
"바나나",
"밀가루",
"우유"
],
"favorite": true
}
]
import {
readFile,
} from 'node:fs/promises';
export interface Recipe {
id: string;
title: string;
category: string;
minutes: number;
ingredients: string[];
favorite: boolean;
}
export const categories = [
'한식',
'양식',
'일식',
'중식',
'디저트',
];
function isRecipe(
v: unknown,
): v is Recipe {
return (
typeof v === 'object' &&
v !== null &&
'id' in v &&
'title' in v &&
'category' in v &&
'minutes' in v &&
'ingredients' in v &&
'favorite' in v &&
typeof v.id === 'string' &&
typeof v.title ===
'string' &&
typeof v.category ===
'string' &&
typeof v.minutes ===
'number' &&
Array.isArray(
v.ingredients,
) &&
typeof v.favorite ===
'boolean'
);
}
export const getRecipes =
async () => {
const text = await readFile(
'data/recipes.json',
'utf8',
);
const data: unknown =
JSON.parse(text);
return Array.isArray(data)
? data.filter(isRecipe)
: [];
};
export const getRecipe =
async (id: string) => {
const list =
await getRecipes();
return list.find(
(r) => r.id === id,
);
};
export const recipes: Recipe[] =
[
{
id: 'r1',
title: '김치볶음밥',
category: '한식',
minutes: 15,
ingredients: [
'밥',
'김치',
'달걀',
],
favorite: true,
},
{
id: 'r2',
title: '토마토 파스타',
category: '양식',
minutes: 25,
ingredients: [
'파스타',
'토마토',
],
favorite: false,
},
{
id: 'r3',
title: '계란말이',
category: '한식',
minutes: 10,
ingredients: [
'달걀',
'파',
],
favorite: false,
},
{
id: 'r4',
title: '바나나 팬케이크',
category: '디저트',
minutes: 20,
ingredients: [
'바나나',
'밀가루',
'우유',
],
favorite: true,
},
];import Link from 'next/link';
import FavoriteButton from
'@/components/FavoriteButton';
import {
getRecipes,
type Recipe,
} from '@/lib/recipes';
const item = (r: Recipe) => (
<li key={r.id}>
<Link
href={`/recipes/${r.id}`}
>
{r.title}
</Link>
<FavoriteButton
recipe={r}
/>
</li>
);
async function Page() {
const recipes =
await getRecipes();
return (
<ul>{recipes.map(item)}</ul>
);
}
export default Page; Creating an optimized production build ...
✓ Compiled successfully in 1008ms
Running TypeScript ...
Finished TypeScript in 823ms ...
Collecting page data using 8 workers ...
✓ Collecting page data using 8 workers in 206ms
Generating static pages using 8 workers (0/11) ...
Generating static pages using 8 workers (2/11)
Generating static pages using 8 workers (5/11)
Generating static pages using 8 workers (8/11)
Error: Route "/recipes": Next.js encountered uncached or runtime data during prerendering.
`fetch(...)`, `cookies()`, `headers()`, `params`, `searchParams`, or `connection()` accessed outside of `<Suspense>` prevents the route from being prerendered, blocking the page load and leading to a slower user experience.
Ways to fix this:
- [stream] Provide a placeholder with `<Suspense fallback={...}>` around the data access
- [cache] For uncached data (`fetch`, database calls): cache the access with `"use cache"` (does not apply to `connection()`)
- [block] Set `export const instant = false` to allow a blocking route
Learn more: https://nextjs.org/docs/messages/blocking-prerender-dynamic
at section (<anonymous>)
at body (<anonymous>)
at html (<anonymous>)
To get a more detailed stack trace and pinpoint the issue, try one of the following:
- Start the app in development mode by running `next dev`, then open "/recipes" in your browser to investigate the error.
- Rerun the production build with `next build --debug-prerender` to generate better stack traces.
Error occurred prerendering page "/recipes". Read more: https://nextjs.org/docs/messages/prerender-error
Export encountered an error on /recipes/page: /recipes, exiting the build.
⨯ Next.js build worker exited with code: 1 and signal: null
exit=1
오류 글은 셋을 읽습니다. 첫 줄은 개발 서버의 글과 거의 같고, uncached or runtime data로 요청 때 데이터(runtime data)까지 넓혀 적습니다. 둘째, Ways to fix this: 아래 고칠 길 셋 가운데 이 과목은 <Suspense>로 대신 보일 것(placeholder)을 두는 [stream](다음 절)과 결과를 기억해 두는 [cache](다음 단원)를 씁니다. 셋째, 빌드 글에는 코드 자리가 없어 next dev로 열어 보라고 합니다 — 개발 서버 터미널의 > 51 |이 그 자리였습니다.
Next.js 규칙 6. 빌드가 미리 그립니다 — 다 못 그리는 곳은 표시합니다.
next build는 쪽마다 미리 그려 껍데기 HTML을 만듭니다. 요청 때만 아는 값과 캐시하지 않은 읽기는<Suspense>로 감싸 나중에 채울 구멍으로 둡니다. 표시가 없으면 빌드가 멈춥니다.
껍데기(shell)는 빌드가 미리 그려 둔 HTML로, 어디서 도나에서 미룬 미리 그리기가 이것입니다. readFile은 캐시하지 않은 읽기인데, 목록 쪽에는 표시가 없었습니다.
3기다리는 자식을 Suspense로 감싸기
[stream] 길로 고칩니다. 할 일을 하위 목표 셋으로 나눠 코드에 주석으로 적습니다.
- 기다리는 일을 자식으로 —
await줄을 쪽 파일 안 새 자식RecipeList로 옮깁니다. - 자식에서 await로 읽기 —
RecipeList가async함수가 되어 목록을 기다립니다. - 쪽에서 Suspense로 감싸기 —
Page는 기다리지 않고RecipeList를<Suspense>안에 둡니다.
app/recipes/page.tsx 맨 위에 react에서 Suspense를 가져오는 줄을 더하고, item 아래의 Page를 둘로 나눕니다.
…
// 1. 기다리는 일을 자식으로
async function RecipeList() {
// 2. 자식에서 await로 읽기
const recipes =
await getRecipes();
return (
<ul>{recipes.map(item)}</ul>
);
}
……
// 3. 쪽에서 Suspense로 감싸기
export default function Page() {
return (
<Suspense
fallback={
<p>목록을 읽는 중</p>
}
>
<RecipeList />
</Suspense>
);
}<Suspense>는 React가 주는 컴포넌트로, 안의 자식이 기다리는 동안 그 자리에 fallback을 그리고 자식이 다 그려지면 그것으로 바꿉니다. Page는 이제 기다리지 않아 async를 떼고 export default function Page()로 씁니다. 맨 아래 export default Page; 줄은 지웁니다. 다시 npm run build를 칩니다.
고친 파일 셋 전체 · 빌드 출력
[
{
"id": "r1",
"title": "김치볶음밥",
"category": "한식",
"minutes": 15,
"ingredients": [
"밥",
"김치",
"달걀"
],
"favorite": true
},
{
"id": "r2",
"title": "토마토 파스타",
"category": "양식",
"minutes": 25,
"ingredients": [
"파스타",
"토마토"
],
"favorite": false
},
{
"id": "r3",
"title": "계란말이",
"category": "한식",
"minutes": 10,
"ingredients": [
"달걀",
"파"
],
"favorite": false
},
{
"id": "r4",
"title": "바나나 팬케이크",
"category": "디저트",
"minutes": 20,
"ingredients": [
"바나나",
"밀가루",
"우유"
],
"favorite": true
}
]
import {
readFile,
} from 'node:fs/promises';
export interface Recipe {
id: string;
title: string;
category: string;
minutes: number;
ingredients: string[];
favorite: boolean;
}
export const categories = [
'한식',
'양식',
'일식',
'중식',
'디저트',
];
function isRecipe(
v: unknown,
): v is Recipe {
return (
typeof v === 'object' &&
v !== null &&
'id' in v &&
'title' in v &&
'category' in v &&
'minutes' in v &&
'ingredients' in v &&
'favorite' in v &&
typeof v.id === 'string' &&
typeof v.title ===
'string' &&
typeof v.category ===
'string' &&
typeof v.minutes ===
'number' &&
Array.isArray(
v.ingredients,
) &&
typeof v.favorite ===
'boolean'
);
}
export const getRecipes =
async () => {
const text = await readFile(
'data/recipes.json',
'utf8',
);
const data: unknown =
JSON.parse(text);
return Array.isArray(data)
? data.filter(isRecipe)
: [];
};
export const getRecipe =
async (id: string) => {
const list =
await getRecipes();
return list.find(
(r) => r.id === id,
);
};
export const recipes: Recipe[] =
[
{
id: 'r1',
title: '김치볶음밥',
category: '한식',
minutes: 15,
ingredients: [
'밥',
'김치',
'달걀',
],
favorite: true,
},
{
id: 'r2',
title: '토마토 파스타',
category: '양식',
minutes: 25,
ingredients: [
'파스타',
'토마토',
],
favorite: false,
},
{
id: 'r3',
title: '계란말이',
category: '한식',
minutes: 10,
ingredients: [
'달걀',
'파',
],
favorite: false,
},
{
id: 'r4',
title: '바나나 팬케이크',
category: '디저트',
minutes: 20,
ingredients: [
'바나나',
'밀가루',
'우유',
],
favorite: true,
},
];import {
Suspense,
} from 'react';
import Link from 'next/link';
import FavoriteButton from
'@/components/FavoriteButton';
import {
getRecipes,
type Recipe,
} from '@/lib/recipes';
const item = (r: Recipe) => (
<li key={r.id}>
<Link
href={`/recipes/${r.id}`}
>
{r.title}
</Link>
<FavoriteButton
recipe={r}
/>
</li>
);
// 1. 기다리는 일을 자식으로
async function RecipeList() {
// 2. 자식에서 await로 읽기
const recipes =
await getRecipes();
return (
<ul>{recipes.map(item)}</ul>
);
}
// 3. 쪽에서 Suspense로 감싸기
export default function Page() {
return (
<Suspense
fallback={
<p>목록을 읽는 중</p>
}
>
<RecipeList />
</Suspense>
);
} Creating an optimized production build ...
✓ Compiled successfully in 1143ms
Running TypeScript ...
Finished TypeScript in 882ms ...
Collecting page data using 8 workers ...
✓ Collecting page data using 8 workers in 219ms
Generating static pages using 8 workers (0/11) ...
Generating static pages using 8 workers (2/11)
Generating static pages using 8 workers (5/11)
Generating static pages using 8 workers (8/11)
✓ Generating static pages using 8 workers (11/11) in 368ms
Finalizing page optimization ...
✓ Finalizing page optimization in 7ms
Route (app)
┌ ○ /
├ ○ /_not-found
├ ◐ /recipes
├ /recipes/[id]
│ ├ ◐ /recipes/[id]
│ ├ ○ /recipes/r1
│ ├ ○ /recipes/r2
│ └ ◐ [+2 more paths]
└ ○ /stats
○ (Static) prerendered as static content
◐ (Partial Prerender) prerendered as static HTML with dynamic server-streamed content
이번에는 빌드가 지나가고, 경로 표의 /recipes 줄에 ◐가 섭니다. 범례(◐ (Partial Prerender) 줄)는 정적 HTML로 미리 그렸고, 나머지는 요청 때 서버가 흘려보낸다(server-streamed)는 뜻입니다. 빌드는 <Suspense> 바깥(탭 줄 · 머리 '레시피' · 바닥글)과 fallback까지 그려 껍데기를 만들고, 레시피 넷은 요청이 오면 RecipeList가 파일을 읽어 채웁니다. 빌드를 봤으면 npm run dev로 개발 서버를 다시 띄웁니다.
예제
연습 문제에서 레시피 보관함에 더한 쪽은 다 본 쪽이니 먼저 지웁니다. 더한 쪽 가운데 여럿이 배열 recipes를 써서, 남기면 배열을 지운 뒤 빌드가 멈춥니다. 오류 글이 getRecipes를 권해도 폴더째 지웁니다.
그다음 배열을 지웁니다(lib/recipes.ts 끝의 export const recipes부터 파일 끝까지). 자세히 쪽 app/recipes/[id]/page.tsx도 같은 하위 목표 셋으로 고칩니다. import에는 react의 Suspense를 더하고, recipes 대신 getRecipe · getRecipes를 가져옵니다. 빌드가 불러 미리 그릴 id 목록을 받는 generateStaticParams도 이제 목록을 기다려 읽으니 async로 바꿉니다. 빌드가 쪽을 그리기 전에 부르는 함수라 <Suspense> 없이 기다려도 됩니다(Next.js 문서).
…
export const
generateStaticParams =
async () => {
const list =
await getRecipes();
return list.map((r) => ({
id: r.id,
}));
};
…단원 3의 Page가 하던 일은 새 자식 RecipeDetail로 옮깁니다. 목록에 없는 id(r9처럼)의 params는 요청이 와야 아는 값이라, 함께 옮겨 <Suspense> 안에서 기다립니다.
…
// 1. 기다리는 일을 자식으로
async function RecipeDetail({
params,
}: {
params: Promise<{
id: string;
}>;
}) {
// 2. 자식에서 await로 읽기
const { id } = await params;
const found =
await getRecipe(id);
…params의 타입은 단원 3의 Page가 받던 것과 같습니다. 그 아래 if (!found)부터 return까지는 단원 3의 Page 몸 그대로이고, 맨 아래 Page는 params를 기다리지 않고 넘깁니다.
// 3. 쪽에서 Suspense로 감싸기
function Page({
params,
}: PageProps<'/recipes/[id]'>) {
return (
<Suspense
fallback={
<p>레시피를 읽는 중</p>
}
>
<RecipeDetail
params={params}
/>
</Suspense>
…저장하고 개발 서버를 끈 뒤 다시 빌드하면, 경로 표의 /recipes/r1 줄은 어느 표시일까요? 고른 뒤 펼쳐 보세요. 맞혀 보기는 점수에 들지 않습니다.
- ①
○—generateStaticParams가id를 알려 주니 다 그린다 - ②
◐— 껍데기만 그리고 레시피는 요청 때 채운다 - ③ 줄이 없다 —
/recipes/[id]한 줄만 선다
결과 보기
②입니다. 아래는 고친 파일 넷 전체와, 개발 서버로 두 쪽을 연 서버 터미널 · 빌드 출력입니다. 시간과 workers 수는 다를 수 있습니다.
[
{
"id": "r1",
"title": "김치볶음밥",
"category": "한식",
"minutes": 15,
"ingredients": [
"밥",
"김치",
"달걀"
],
"favorite": true
},
{
"id": "r2",
"title": "토마토 파스타",
"category": "양식",
"minutes": 25,
"ingredients": [
"파스타",
"토마토"
],
"favorite": false
},
{
"id": "r3",
"title": "계란말이",
"category": "한식",
"minutes": 10,
"ingredients": [
"달걀",
"파"
],
"favorite": false
},
{
"id": "r4",
"title": "바나나 팬케이크",
"category": "디저트",
"minutes": 20,
"ingredients": [
"바나나",
"밀가루",
"우유"
],
"favorite": true
}
]
import {
readFile,
} from 'node:fs/promises';
export interface Recipe {
id: string;
title: string;
category: string;
minutes: number;
ingredients: string[];
favorite: boolean;
}
export const categories = [
'한식',
'양식',
'일식',
'중식',
'디저트',
];
function isRecipe(
v: unknown,
): v is Recipe {
return (
typeof v === 'object' &&
v !== null &&
'id' in v &&
'title' in v &&
'category' in v &&
'minutes' in v &&
'ingredients' in v &&
'favorite' in v &&
typeof v.id === 'string' &&
typeof v.title ===
'string' &&
typeof v.category ===
'string' &&
typeof v.minutes ===
'number' &&
Array.isArray(
v.ingredients,
) &&
typeof v.favorite ===
'boolean'
);
}
export const getRecipes =
async () => {
const text = await readFile(
'data/recipes.json',
'utf8',
);
const data: unknown =
JSON.parse(text);
return Array.isArray(data)
? data.filter(isRecipe)
: [];
};
export const getRecipe =
async (id: string) => {
const list =
await getRecipes();
return list.find(
(r) => r.id === id,
);
};import {
Suspense,
} from 'react';
import Link from 'next/link';
import FavoriteButton from
'@/components/FavoriteButton';
import {
getRecipes,
type Recipe,
} from '@/lib/recipes';
const item = (r: Recipe) => (
<li key={r.id}>
<Link
href={`/recipes/${r.id}`}
>
{r.title}
</Link>
<FavoriteButton
recipe={r}
/>
</li>
);
// 1. 기다리는 일을 자식으로
async function RecipeList() {
// 2. 자식에서 await로 읽기
const recipes =
await getRecipes();
return (
<ul>{recipes.map(item)}</ul>
);
}
// 3. 쪽에서 Suspense로 감싸기
export default function Page() {
return (
<Suspense
fallback={
<p>목록을 읽는 중</p>
}
>
<RecipeList />
</Suspense>
);
}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,
}));
};
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;> 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 209ms
✓ Running next.config.ts took 1006ms
- Cache Components enabled
- Partial Prefetching enabled
GET /recipes 200 in 123ms (next.js: 50ms, application-code: 73ms)
GET /recipes/r1 200 in 171ms (next.js: 4ms, generate-params: 145ms, application-code: 22ms)
Creating an optimized production build ...
✓ Compiled successfully in 1191ms
Running TypeScript ...
Finished TypeScript in 902ms ...
Collecting page data using 8 workers ...
✓ Collecting page data using 8 workers in 205ms
Generating static pages using 8 workers (0/11) ...
Generating static pages using 8 workers (2/11)
Generating static pages using 8 workers (5/11)
Generating static pages using 8 workers (8/11)
✓ Generating static pages using 8 workers (11/11) in 354ms
Finalizing page optimization ...
✓ Finalizing page optimization in 8ms
Route (app)
┌ ○ /
├ ○ /_not-found
├ ◐ /recipes
├ /recipes/[id]
│ ├ ◐ /recipes/[id]
│ ├ ◐ /recipes/r1
│ ├ ◐ /recipes/r2
│ └ ◐ [+2 more paths]
└ ○ /stats
○ (Static) prerendered as static content
◐ (Partial Prerender) prerendered as static HTML with dynamic server-streamed content
단원 2의 경로 표에서 ○였던 /recipes/r1 · /recipes/r2가 ◐가 됐습니다. 레시피를 <Suspense> 안에서 요청 때 읽으니, 빌드는 머리와 fallback '레시피를 읽는 중'까지만 그려 둡니다. 터미널에는 단원 2부터 자세히 쪽을 열 때마다 찍히던 encountered URL data 덩어리가 없습니다. params를 <Suspense> 안에서 기다리게 되었기 때문입니다.
동적 경로 [id]에서 미룬 ◐ /recipes/[id] 줄도 같은 뜻입니다. 목록에 없는 id가 와도 쓸 껍데기를 빌드 때 그려 두고, <Suspense> 안은 요청이 올 때 채웁니다.
다 봤으면 npm run dev로 다시 띄워 목록에 없는 /recipes/r9를 엽니다. 화면은 '없는 쪽'인데 응답 머리 첫 줄은 200 OK입니다. 없는 쪽 2절의 개발 판은 404였습니다. 까닭은 다음 레슨의 예제에서 읽습니다.
app/not-found.tsx 그대로 · 화면 · 응답 머리
머리 상자는 Network 판 Headers에서 몇 줄만 추린 것입니다.
function NotFound() {
return (
<>
<h1>없는 쪽</h1>
<p>주소를 확인하세요.</p>
</>
);
}
export default NotFound;<nav><a href="/recipes">▸ 목록</a>·<a href="/stats">통계</a></nav>
<h1>없는 쪽</h1>
<p>주소를 확인하세요.</p>
<footer>바닥글</footer>
<meta name="robots" content="noindex">
<meta name="next-error" content="not-found">HTTP/1.1 200 OK
Cache-Control: no-store
x-nextjs-cache: HIT
x-nextjs-prerender: 1
Content-Type: text/html; charset=utf-8
자주 틀리는 곳
틀린 생각: 개발 서버에서 화면이 뜨면 빌드도 지나간다.
맞는 규칙: <Suspense> 밖에서 캐시하지 않은 읽기를 기다리면, 개발 서버는 화면을 띄우고 오류 글만 찍지만 빌드는 멈춥니다(2절). 쪽을 고친 뒤에는 npm run build로 한 번 더 봅니다.
틀린 생각: JSON.parse(text) as Recipe[]면 확인 함수는 필요 없다.
맞는 규칙: as는 타입 검사기에게 믿으라고 하는 말일 뿐 값을 보지 않습니다(바깥 값 확인하기). 파일에 속성이 빠진 레시피가 섞여도 알아채지 못합니다. unknown으로 받아 isRecipe를 지난 것만 씁니다. isRecipe는 재료가 배열인지만 봅니다.
틀린 생각: 자세히 쪽은 단원 3처럼 Page에서 기다려도 된다 — 그때도 빌드는 지나갔다.
맞는 규칙: 단원 3에서 기다린 params는 generateStaticParams가 돌려준 id라 빌드 때 알았습니다. getRecipe(id)까지 Page에서 기다리면 빌드가 /recipes/[id]에서 멈춥니다. 예제처럼 RecipeDetail로 옮겨 <Suspense> 안에 둡니다.
확인 문제
문제 1. 통계 쪽 app/stats/page.tsx의 Page를 이렇게 바꿔, getRecipes()를 Suspense 없이 기다렸습니다. npm run build를 치면 어떻게 될까요?
…
async function Page() {
const list =
await getRecipes();
return (
<p>모두 {list.length}개</p>
);
}
…- ① 빌드 때 파일을 읽어
모두 4개를 미리 그린다 - ② 빌드가
/stats에서 멈춘다 - ③ 빌드는 지나가고,
/stats를 열 때 오류가 난다
정답
②입니다. getRecipes()는 캐시하지 않은 읽기이고, Page가 <Suspense> 밖에서 기다립니다. 표시가 없으니 빌드가 멈춥니다(규칙 6).
- ① 빌드는 캐시하지 않은 읽기의 결과를 껍데기에 넣지 않습니다. 결과를 기억해 두는 길은 다음 단원에서 봅니다.
- ③ 개발 서버라면 화면이 뜨고 오류 글이 찍히지만, 빌드는 그 전에 멈춥니다.
문제 2. 3절처럼 감싼 목록 쪽에서, 빌드가 /recipes의 껍데기에 그려 둔 것은 무엇일까요?
- ① 레시피 넷의 목록
- ② 아무것도 없다 — 쪽 전체를 요청 때 그린다
- ③ 탭 줄 · 머리 '레시피' · '목록을 읽는 중' · 바닥글
정답
③입니다. 빌드는 <Suspense> 바깥과 fallback까지 그려 껍데기를 만듭니다. 경로 표의 ◐가 그 표시입니다.
- ① 목록은
RecipeList가 요청 때 파일을 읽어 채웁니다. - ② 쪽 전체를 요청 때 그린다면 정적 HTML로 미리 그렸다는
◐가 서지 않습니다.
문제 3. 예제의 자세히 쪽 Page는 params를 기다리지 않고 RecipeDetail에 넘깁니다. 까닭으로 맞는 것은 무엇일까요?
- ① 목록에 없는
id의params는 요청 때 오는 값이라, 기다리는 일과 함께<Suspense>안에 둔다 - ②
Page는async함수가 될 수 없다 - ③
notFound()는 자식 컴포넌트에서만 부를 수 있다
정답
①입니다. 목록에 없는 id는 요청이 와야 아는 값이라, Page에서 params를 기다리면 그 기다림이 <Suspense> 밖에 놓입니다. 목록에 든 id는 generateStaticParams가 빌드 때 알려 줍니다. 빌드를 멈추는 것은 getRecipe(id) 같은 캐시하지 않은 읽기입니다(자주 틀리는 곳).
- ②
Page도async함수가 될 수 있습니다. 1절과 단원 3의Page가 그랬습니다. 다만 그러면<Suspense>밖에서 기다립니다. - ③ 단원 3에서는
Page가notFound()를 직접 불렀습니다.
이 레슨에서 바꾼 파일
data/recipes.json — 새로 만듦(레시피 넷)
[
{
"id": "r1",
"title": "김치볶음밥",
"category": "한식",
"minutes": 15,
"ingredients": [
"밥",
"김치",
"달걀"
],
"favorite": true
},
{
"id": "r2",
"title": "토마토 파스타",
"category": "양식",
"minutes": 25,
"ingredients": [
"파스타",
"토마토"
],
"favorite": false
},
{
"id": "r3",
"title": "계란말이",
"category": "한식",
"minutes": 10,
"ingredients": [
"달걀",
"파"
],
"favorite": false
},
{
"id": "r4",
"title": "바나나 팬케이크",
"category": "디저트",
"minutes": 20,
"ingredients": [
"바나나",
"밀가루",
"우유"
],
"favorite": true
}
]
lib/recipes.ts — 배열을 지우고 파일을 읽는 getRecipes · getRecipe와 확인 함수 isRecipe를 둠
import {
readFile,
} from 'node:fs/promises';
export interface Recipe {
id: string;
title: string;
category: string;
minutes: number;
ingredients: string[];
favorite: boolean;
}
export const categories = [
'한식',
'양식',
'일식',
'중식',
'디저트',
];
function isRecipe(
v: unknown,
): v is Recipe {
return (
typeof v === 'object' &&
v !== null &&
'id' in v &&
'title' in v &&
'category' in v &&
'minutes' in v &&
'ingredients' in v &&
'favorite' in v &&
typeof v.id === 'string' &&
typeof v.title ===
'string' &&
typeof v.category ===
'string' &&
typeof v.minutes ===
'number' &&
Array.isArray(
v.ingredients,
) &&
typeof v.favorite ===
'boolean'
);
}
export const getRecipes =
async () => {
const text = await readFile(
'data/recipes.json',
'utf8',
);
const data: unknown =
JSON.parse(text);
return Array.isArray(data)
? data.filter(isRecipe)
: [];
};
export const getRecipe =
async (id: string) => {
const list =
await getRecipes();
return list.find(
(r) => r.id === id,
);
};app/recipes/page.tsx — 목록을 기다리는 자식 RecipeList를 <Suspense>로 감쌈
import {
Suspense,
} from 'react';
import Link from 'next/link';
import FavoriteButton from
'@/components/FavoriteButton';
import {
getRecipes,
type Recipe,
} from '@/lib/recipes';
const item = (r: Recipe) => (
<li key={r.id}>
<Link
href={`/recipes/${r.id}`}
>
{r.title}
</Link>
<FavoriteButton
recipe={r}
/>
</li>
);
// 1. 기다리는 일을 자식으로
async function RecipeList() {
// 2. 자식에서 await로 읽기
const recipes =
await getRecipes();
return (
<ul>{recipes.map(item)}</ul>
);
}
// 3. 쪽에서 Suspense로 감싸기
export default function Page() {
return (
<Suspense
fallback={
<p>목록을 읽는 중</p>
}
>
<RecipeList />
</Suspense>
);
}app/recipes/[id]/page.tsx — 기다리는 일을 자식 RecipeDetail로 옮겨 <Suspense>로 감쌈 · generateStaticParams도 파일에서 읽음
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,
}));
};
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;