하루 지나 풀면 더 오래 남습니다. 1~8단원에서 열 문제를 단원 차례 없이 섞었습니다. 문제마다 어느 레슨인지는 정답을 펼치면 보입니다. 화면은 보이는 글을 위에서부터, 서버 터미널과 브라우저 콘솔(개발자 도구의 Console 판)은 찍히는 줄을 종이나 메모 앱에 쓴 뒤 정답을 펼치세요. 막히면 정답 앞의 힌트를 먼저 펼칩니다. 점수는 매기지 않습니다.
한 번에 다 풀 필요는 없습니다. 문제 1~9는 폰으로도 풀 수 있고(약 75분), 끝의 만들어 보기 하나는 컴퓨터가 있으면 개발 서버로 띄워 봅니다. 나눠 푼다면 문제 3까지(빌드 · 배포 판)와 문제 4부터(개발 판)로 끊기 좋습니다.
문제 1은 새 프로젝트에서, 문제 2~10은 8단원을 마친 레시피 보관함에서 풉니다. 판을 따로 적지 않은 문제는 개발 판(npm run dev)입니다. 결과 상자는 Next.js 16.4.6 · React 19.3.0 · Node.js 26.12.0 · npm 11.20.0으로 돌린 것이고, 시간은 다를 수 있습니다.
문제 1
새 프로젝트(create-next-app 그대로)에 찻집 차림표를 짓습니다. lib/tea.ts의 getPrice는 'use cache'로 결과를 기억해 두고, 몸이 돌 때마다 값 읽음과 받은 크기를 서버 터미널에 찍습니다. 레시피 보관함의 개발 서버가 켜져 있으면 먼저 Ctrl+C로 끕니다.
export async function getPrice(
size: string,
) {
'use cache';
console.log('값 읽음', size);
return size === '큰'
? 5000
: 4000;
}쪽 /tea는 getPrice를 '작은' → '큰' → '작은' 차례로 불러 값 셋을 한 줄에 그립니다. 처리기 /tea/menu는 '작은' → '중간' 차례로 불러 JSON으로 돌려줍니다. 두 파일 모두 맨 위 import 줄(@/lib/tea의 getPrice)을 …로 줄였고, 쪽은 끝의 내보내기 줄도 줄였습니다.
…
async function Page() {
const a =
await getPrice('작은');
const b =
await getPrice('큰');
const c =
await getPrice('작은');
return (
<p>
{`${a} · ${b} · ${c}`}
</p>
);
}
……
export async function GET() {
const small =
await getPrice('작은');
const mid =
await getPrice('중간');
return Response.json({
small,
mid,
});
}개발 서버를 새로 띄우고 /tea를 연 뒤, 이어서 /tea/menu를 엽니다.
(가) /tea의 화면에 그려진 한 줄을 쓰세요.
(나) 두 주소를 연 뒤 서버 터미널에서 머리에 Cache 꼬리표가 없는 값 읽음 줄을 찍힌 차례대로 모두 쓰세요.
힌트
(나)는 기억을 찾을 때 무엇을 열쇠로 쓰는지 떠올립니다. 쪽과 처리기는 같은 서버에서 돕니다.
정답
(가) 4000 · 5000 · 4000 · (나) 값 읽음 작은 · 값 읽음 큰 · 값 읽음 중간 세 줄입니다.
아래는 두 파일 전부와, 개발 서버로 /tea를 연 화면, /tea/menu가 돌려준 받은 글, 두 주소를 연 뒤의 서버 터미널입니다. 시간은 다를 수 있습니다. 터미널 첫 줄의 recipe-box-next 자리에는 내 프로젝트 이름이 찍힙니다.
import {
getPrice,
} from '@/lib/tea';
async function Page() {
const a =
await getPrice('작은');
const b =
await getPrice('큰');
const c =
await getPrice('작은');
return (
<p>
{`${a} · ${b} · ${c}`}
</p>
);
}
export default Page;import {
getPrice,
} from '@/lib/tea';
export async function GET() {
const small =
await getPrice('작은');
const mid =
await getPrice('중간');
return Response.json({
small,
mid,
});
}<p>4000 · 5000 · 4000</p>{"small":4000,"mid":4000}> 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 239ms
✓ Running next.config.ts took 1031ms
- Cache Components enabled
- Partial Prefetching enabled
값 읽음 작은
Cache 값 읽음 작은
값 읽음 큰
Cache 값 읽음 큰
GET /tea 200 in 151ms (next.js: 62ms, application-code: 89ms)
Cache 값 읽음 작은
Cache 값 읽음 큰
Cache 값 읽음 작은
Cache 값 읽음 큰
Cache 값 읽음 작은
값 읽음 중간
Cache 값 읽음 중간
GET /tea/menu 200 in 38ms (next.js: 23ms, application-code: 15ms)
'use cache' 함수는 받은 인자를 열쇠로 결과를 기억합니다. /tea에서 '작은'과 '큰'은 처음이라 몸이 돌아 줄이 찍혔고, 셋째 '작은'은 같은 열쇠의 기억을 꺼내 몸이 돌지 않았습니다. /tea/menu의 '작은'도 쪽이 남긴 기억을 썼고, 처음 보는 '중간'만 몸이 돌았습니다. Cache 꼬리표가 붙은 줄은 기억한 결과를 쓸 때 개발 서버가 그 함수가 처음 돌며 찍은 로그를 다시 보여 준 것이라, 함수가 돈 줄이 아닙니다.
값 읽음 작은을 두 번 이상 쓴 답은 'use cache'를 붙여도 부를 때마다 함수가 돈다고 본 것입니다. 중간을 빼고 두 줄만 쓴 답은 인자가 달라도 한 기억을 나눠 쓴다고 본 것입니다.
다 봤으면 찻집의 개발 서버를 Ctrl+C로 끕니다. 찻집은 따로 만든 새 프로젝트라 레시피 보관함에 옮기지 않습니다.
다시 볼 레슨: 인자가 열쇠다(2절 — 기억을 찾는 열쇠) · 'use cache'(2절 — Cache 꼬리표가 붙은 줄) · 경로 처리기(1절 — 쪽 대신 응답을 만드는 파일)
문제 2
문제 2~10은 8단원을 마친 레시피 보관함입니다. 찻집의 개발 서버는 Ctrl+C로 끄고, recipe-box-next 폴더에서 npm run dev를 띄웁니다. 아래 접기가 그 판의 파일 스물일곱이고, 레슨을 따라왔다면 이미 있습니다. 폰으로 풀 때는 이 접기를 펴지 않아도 됩니다. 백업 처리기 app/api/recipes/route.ts는 data/recipes.json을 await readFile로 읽어 JSON으로 돌려주고 내려받기 머리를 답니다. proxy.ts는 /list를 /recipes로 보내고, .env.local에는 SECRET_KEY=abc123과 NEXT_PUBLIC_APP_NAME=보관함 두 줄이 있습니다. 시작 상태의 data/recipes.json은 씨앗 넷(r1 김치볶음밥 · r2 토마토 파스타 · r3 계란말이 · r4 바나나 팬케이크)입니다. 레시피 보관함 폴더에서 풉니다.
레시피 보관함 — 8단원 끝 판 파일 스물일곱
파일: app/page.tsx · app/layout.tsx · lib/recipes.ts · app/recipes/layout.tsx · app/recipes/page.tsx · app/recipes/[id]/page.tsx · app/stats/page.tsx · app/not-found.tsx · components/TabBar.tsx · components/FavoriteButton.tsx · components/Fold.tsx · data/recipes.json · app/recipes/loading.tsx · components/SearchBar.tsx · components/Count.tsx · app/actions.ts · components/RecipeForm.tsx · app/recipes/new/page.tsx · app/boom/page.tsx · app/boom/error.tsx · app/global-error.tsx · app/recipes/page.module.css · app/stats/page.module.css · app/api/recipes/route.ts · proxy.ts · .env.local · components/Show.tsx
import {
Suspense,
} from 'react';
import {
getRecipes,
} from '@/lib/recipes';
import {
connection,
} from 'next/server';
const wait = (ms: number) =>
new Promise((r) => {
setTimeout(r, ms);
});
// 2초 걸리는 읽기라고 칩니다
const getPick = async () => {
const recipes =
await getRecipes();
await connection();
const at = Math.floor(
Math.random() *
recipes.length,
);
await wait(2000);
return recipes[at];
};
// 1초 걸리는 읽기라고 칩니다
const getFavorites =
async () => {
const recipes =
await getRecipes();
await wait(1000);
return recipes.filter(
(r) => r.favorite,
);
};
// 1. 기다리는 일을 자식으로
async function Pick() {
// 2. 자식에서 await로 읽기
const pick = await getPick();
return (
<p>
오늘의 추천: {pick.title}
</p>
);
}
async function Favorites() {
const list =
await getFavorites();
const text = list
.map((r) => r.title)
.join(', ');
return <p>즐겨찾기: {text}</p>;
}
// 3. 쪽에서 Suspense로 감싸기
export default function Home() {
return (
<>
<h1>레시피 보관함</h1>
<Suspense
fallback={
<p>추천을 고르는 중</p>
}
>
<Pick />
</Suspense>
<Suspense
fallback={
<p>즐겨찾기를 읽는 중</p>
}
>
<Favorites />
</Suspense>
</>
);
}import type {
Metadata,
} from 'next';
import Image from 'next/image';
import {
Noto_Sans_KR,
} from 'next/font/google';
import './globals.css';
import TabBar from
'@/components/TabBar';
import Show from
'@/components/Show';
const noto = Noto_Sans_KR({
subsets: ['latin'],
});
export const
metadata: Metadata = {
title: {
template:
'%s · 레시피 보관함',
default: '레시피 보관함',
},
description:
'내 레시피를 모아 두는 곳',
};
function RootLayout({
children,
}: LayoutProps<'/'>) {
return (
<html lang="ko">
<body
className={
noto.className
}
>
<TabBar />
{children}
<footer>
바닥글
<Show />
<Image
src="/next.svg"
alt="Next.js"
width={100}
height={20}
/>
</footer>
</body>
</html>
);
}
export default RootLayout;import {
readFile,
writeFile,
} from 'node:fs/promises';
import {
cacheLife,
cacheTag,
} from 'next/cache';
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'
);
}
// 1. 함수 머리에 'use cache'
export const getRecipes =
async () => {
'use cache';
// 2. cacheLife로 얼마나
cacheLife('hours');
// 3. cacheTag로 이름 붙이기
cacheTag('recipes');
console.log(
'레시피 파일 읽음',
);
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) => {
'use cache';
cacheLife('hours');
cacheTag('recipes');
console.log(
'레시피 하나 읽음',
id,
);
const list =
await getRecipes();
return list.find(
(r) => r.id === id,
);
};
// 기억한 목록이 아니라 파일을 읽음
export const addRecipe = async (
input: {
title: string;
category: string;
minutes: number;
},
) => {
const text = await readFile(
'data/recipes.json',
'utf8',
);
const data: unknown =
JSON.parse(text);
const list: Recipe[] =
Array.isArray(data)
? data.filter(isRecipe)
: [];
const recipe: Recipe = {
id: crypto.randomUUID(),
...input,
ingredients: [],
favorite: false,
};
list.push(recipe);
await writeFile(
'data/recipes.json',
JSON.stringify(
list, null, 2,
),
);
return recipe;
};function RecipesLayout({
children,
}: LayoutProps<'/recipes'>) {
return (
<section>
<h1>레시피</h1>
{children}
</section>
);
}
export default RecipesLayout;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';
import styles from
'./page.module.css';
export const
metadata: Metadata = {
title: '목록',
};
const item = (r: Recipe) => (
<li
key={r.id}
className={styles.card}
>
<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;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;import {
Suspense,
} from 'react';
import type {
Metadata,
} from 'next';
import Count from
'@/components/Count';
import {
getRecipes,
} from '@/lib/recipes';
import styles from
'./page.module.css';
export const
metadata: Metadata = {
title: '통계',
};
export default function Page() {
const recipes = getRecipes();
// 3. 쪽에서 Suspense로 감싸기
return (
<>
<h1
className={styles.card}
>
통계
</h1>
<Suspense
fallback={<p>세는 중</p>}
>
<Count
recipes={recipes}
/>
</Suspense>
</>
);
}function NotFound() {
return (
<>
<h1>없는 쪽</h1>
<p>주소를 확인하세요.</p>
</>
);
}
export default NotFound;'use client';
import Link from 'next/link';
import {
usePathname,
} from 'next/navigation';
function TabBar() {
const path = usePathname();
const mark = (href: string) =>
path.includes(href)
? '▸ '
: '';
return (
<nav>
<Link href="/recipes">
{mark('/recipes')}목록
</Link>
·<Link href="/stats">
{mark('/stats')}통계
</Link>
</nav>
);
}
export default TabBar;'use client';
import {
useState,
} from 'react';
import type {
Recipe,
} from '@/lib/recipes';
function FavoriteButton({
recipe,
}: {
recipe: Recipe;
}) {
const [starred, setStarred] =
useState(recipe.favorite);
function handleClick() {
setStarred(!starred);
}
return (
<button
onClick={handleClick}
>
{starred ? '★' : '☆'}
</button>
);
}
export default FavoriteButton;'use client';
import {
useState,
type ReactNode,
} from 'react';
function Fold({
children,
}: {
children: ReactNode;
}) {
const [open, setOpen] =
useState(false);
const label = open
? '재료 접기'
: '재료 보기';
function handleClick() {
setOpen(!open);
}
return (
<section>
<button
onClick={handleClick}
>
{label}
</button>
{open && children}
</section>
);
}
export default Fold;[
{
"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
}
]
function Loading() {
return <p>레시피를 여는 중</p>;
}
export default Loading;function SearchBar() {
return (
<form action="/recipes">
<input name="q" />
<button>찾기</button>
</form>
);
}
export default SearchBar;'use client';
import { use } from 'react';
import type {
Recipe,
} from '@/lib/recipes';
// 1. 기다리는 일을 자식으로
function Count({
recipes,
}: {
recipes: Promise<Recipe[]>;
}) {
// 2. Promise를 넘기고 use로 열기
const list = use(recipes);
return (
<p>모두 {list.length}개</p>
);
}
export default Count;'use server';
import {
updateTag,
} from 'next/cache';
import {
redirect,
} from 'next/navigation';
import {
addRecipe,
categories,
} from '@/lib/recipes';
async function createRecipe(
prevState: { error: string },
formData: FormData,
) {
// 2. 값 꺼내 검사하기
const title =
formData.get('title');
const category =
formData.get('category');
if (
typeof title !== 'string' ||
title.trim() === ''
) {
return {
error: '이름을 적어 주세요',
};
}
if (title.length > 30) {
return {
error: '이름은 30자까지',
};
}
if (
typeof category !== 'string'
) {
return {
error: '분류를 골라 주세요',
};
}
if (
!categories.includes(
category,
)
) {
return {
error: '분류를 골라 주세요',
};
}
const minutes = Number(
formData.get('minutes'),
);
if (
minutes < 1 ||
!Number.isInteger(minutes)
) {
return {
error: '분은 1 이상 정수로',
};
}
// 3. 저장하기
const recipe =
await addRecipe({
title: title.trim(),
category,
minutes,
});
// 4. 기억 지우기
updateTag('recipes');
// 5. 새 쪽으로 보내기
redirect(
'/recipes/' + recipe.id,
);
}
export { createRecipe };'use client';
import {
useActionState,
} from 'react';
import {
createRecipe,
} from '@/app/actions';
function RecipeForm({
categories,
}: {
categories: string[];
}) {
// 1. 폼에 서버 함수 달기
const [
state,
formAction,
isPending,
] = useActionState(
createRecipe,
{ error: '' },
);
const options =
categories.map((c) => (
<option key={c}>
{c}
</option>
));
return (
<form action={formAction}>
<input
name="title"
placeholder="이름"
/>
<select
name="category"
aria-label="분류"
>
{options}
</select>
<input
name="minutes"
type="number"
placeholder="분"
/>
<button
disabled={isPending}
>
더하기
</button>
<p>{state.error}</p>
</form>
);
}
export default RecipeForm;import RecipeForm from
'@/components/RecipeForm';
import {
categories,
} from '@/lib/recipes';
function Page() {
console.log(
'더하기 쪽을 그림',
);
return (
<RecipeForm
categories={categories}
/>
);
}
export default Page;import {
Suspense,
} from 'react';
import {
connection,
} from 'next/server';
// 늘 실패하는 읽기라고 칩니다
const getBroken = async () => {
await connection();
throw new Error(
'레시피를 못 읽음',
);
};
async function Fail() {
const text =
await getBroken();
return <p>{text}</p>;
}
function Page() {
return (
<Suspense
fallback={<p>읽는 중</p>}
>
<Fail />
</Suspense>
);
}
export default Page;'use client';
function BoomError({
error,
retry,
}: {
error: unknown;
retry: () => void;
}) {
const message =
error instanceof Error
? error.message
: String(error);
return (
<>
<h2>못 그렸습니다</h2>
<p>{message}</p>
<button onClick={retry}>
다시
</button>
</>
);
}
export default BoomError;'use client';
function GlobalError({
retry,
}: {
error: unknown;
retry: () => void;
}) {
return (
<html lang="ko">
<body>
<h1>앱을 못 그렸습니다</h1>
<button onClick={retry}>
다시
</button>
</body>
</html>
);
}
export default GlobalError;.card {
padding: 8px;
border-top: 1px solid #ccc;
}.card {
color: crimson;
}import {
readFile,
} from 'node:fs/promises';
// 받는 쪽이 파일로 저장하게
const headers = {
'Content-Disposition':
'attachment; filename=' +
'"recipes.json"',
};
export async function GET() {
const text = await readFile(
'data/recipes.json',
'utf8',
);
return Response.json(
JSON.parse(text),
{ headers },
);
}import {
NextResponse,
type NextRequest,
} from 'next/server';
export function proxy(
request: NextRequest,
) {
return NextResponse.redirect(
new URL(
'/recipes',
request.url,
),
);
}
export const config = {
matcher: '/list',
};SECRET_KEY=abc123
NEXT_PUBLIC_APP_NAME=보관함'use client';
function Show() {
const name =
process.env
.NEXT_PUBLIC_APP_NAME;
return <p>{`앱: ${name}`}</p>;
}
export default Show;레시피 수를 세는 처리기 둘을 더합니다. /api/first는 node:fs의 readFileSync로, /api/now는 node:fs/promises의 await readFile로 data/recipes.json을 읽어, 레시피 수를 {"count":4} 꼴 JSON으로 돌려줍니다. 두 파일 모두 맨 위 import 줄은 …로 줄였습니다.
…
export async function GET() {
const text = readFileSync(
'data/recipes.json',
'utf8',
);
const list = JSON.parse(text);
return Response.json({
count: list.length,
});
}…
export async function GET() {
const text = await readFile(
'data/recipes.json',
'utf8',
);
const list = JSON.parse(text);
return Response.json({
count: list.length,
});
}두 파일을 저장했으면 개발 서버를 Ctrl+C로 끄고 npm run build → npm run start로 띄웁니다. 띄운 채 주소 칸에 /api/recipes를 쳐 봅니다. 그다음 data/recipes.json에서 마지막 레시피(r4 바나나 팬케이크)를 지워 셋으로 저장하고, 다시 빌드하지 않은 채 /api/first와 /api/now를 엽니다.
(가) 빌드 출력의 경로 표에서 세 주소 앞의 기호는 무엇일까요? ○나 ƒ로 쓰세요.
- ㉠
/api/first - ㉡
/api/now - ㉢
/api/recipes
(나) r4를 지운 뒤 두 주소가 돌려주는 count는 몇일까요?
- ㉠
/api/first - ㉡
/api/now
(다) 주소 칸에 /api/recipes를 치면 브라우저는 JSON 글을 쪽에 보이지 않고 recipes.json 파일로 내려받습니다. 응답 머리 가운데 그렇게 시키는 머리의 이름을 쓰세요.
힌트
(가) · (나)는 빌드가 처리기를 미리 돌리다가 무엇을 만나면 요청 때로 미루는지 떠올립니다. 기다리지 않는 읽기와 기다리는 읽기를 견줍니다. (다)는 백업 처리기가 단 머리를 봅니다.
정답
(가) ㉠ ○ · ㉡ ƒ · ㉢ ƒ · (나) ㉠ 4 · ㉡ 3 · (다) Content-Disposition입니다.
아래는 두 처리기 전부와, 배포 서버가 돌려준 /api/recipes의 응답 머리, r4를 지운 data/recipes.json, 그 뒤 두 처리기의 받은 글입니다.
import {
readFileSync,
} from 'node:fs';
export async function GET() {
const text = readFileSync(
'data/recipes.json',
'utf8',
);
const list = JSON.parse(text);
return Response.json({
count: list.length,
});
}import {
readFile,
} from 'node:fs/promises';
export async function GET() {
const text = await readFile(
'data/recipes.json',
'utf8',
);
const list = JSON.parse(text);
return Response.json({
count: list.length,
});
}HTTP/1.1 200 OK
content-disposition: attachment; filename="recipes.json"
content-type: application/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
}
]
{"count":4}{"count":3}(가) 빌드 출력의 경로 표에는 ├ ○ /api/first · ├ ƒ /api/now · ├ ƒ /api/recipes 줄이 섭니다. 빌드는 처리기도 미리 돌려 봅니다. readFileSync는 기다리지 않는 읽기라 빌드 때 그대로 돌아, /api/first의 응답({"count":4})이 빌드 때 만들어졌습니다(○). /api/now와 /api/recipes는 기다리는 읽기(await readFile)를 만나 요청 때로 미뤄졌습니다(ƒ).
(나) 그래서 빌드 뒤에 r4를 지워도 /api/first는 빌드 때 만든 4를 그대로 주고, 요청마다 파일을 읽는 /api/now만 3을 줍니다. ㉠에 3을 쓴 답은 서버가 읽은 파일은 요청마다 다시 읽힌다고 본 것입니다.
(다) content-disposition 머리의 값 attachment가 받는 쪽에 파일로 저장하라고 알리고, filename이 저장할 이름입니다. 몸은 JSON 글 그대로입니다.
다 봤으면 Ctrl+C로 배포 서버를 끄고, 지운 r4를 되살려 data/recipes.json을 씨앗 넷으로 되돌립니다. 그다음 npm run dev로 개발 서버를 띄웁니다. 두 처리기는 끝까지 둡니다.
다시 볼 레슨: 경로 처리기(2절 — 경로 표에서 /api/recipes는 · 예제) · 빌드가 미리 그린 것 · 서버에서 읽기(2절 — 빌드가 미리 그린다)
문제 3
비밀 키 SECRET_KEY가 어디까지 가는지 보려고 쪽 /key를 더합니다. 클라이언트 컴포넌트 둘의 전부입니다. Peek은 SECRET_KEY를 바로 읽고, Tag는 받은 value를 그립니다.
'use client';
function Peek() {
const key =
process.env.SECRET_KEY;
return <p>{`열쇠 ${key}`}</p>;
}
export default Peek;'use client';
function Tag({
value,
}: {
value?: string;
}) {
return (
<p>{`열쇠 ${value}`}</p>
);
}
export default Tag;쪽 app/key/page.tsx는 서버 컴포넌트에서 SECRET_KEY를 읽어 Tag의 value로 넘기고, 그 위에 Peek을 그립니다. 맨 위 import 두 줄은 …로 줄였습니다.
…
function Page() {
const key =
process.env.SECRET_KEY;
return (
<>
<Peek />
<Tag value={key} />
</>
);
}
export default Page;개발 서버를 Ctrl+C로 끄고 npm run build → npm run start로 띄워 /key를 엽니다.
(가) 받은 HTML(페이지 소스 보기)에서 Peek과 Tag가 그린 두 줄은 무엇일까요?
(나) 화면에서 두 줄은 무엇일까요?
힌트
(가)는 클라이언트 컴포넌트를 처음 그리는 곳이 어디인지 떠올립니다. (나)는 브라우저로 가는 JS에 NEXT_PUBLIC_이 아닌 값이 있는지, props로 넘긴 값은 어떻게 브라우저에 가는지 떠올립니다.
정답
(가) 열쇠 abc123 · 열쇠 abc123 · (나) 열쇠 undefined · 열쇠 abc123입니다.
아래는 쪽 전부와, 배포 서버가 돌려준 받은 HTML(다듬음)과 화면입니다.
import Peek from
'@/components/Peek';
import Tag from
'@/components/Tag';
function Page() {
const key =
process.env.SECRET_KEY;
return (
<>
<Peek />
<Tag value={key} />
</>
);
}
export default Page;<nav><a href="/recipes">목록</a>·<a href="/stats">통계</a></nav>
<p>열쇠 abc123</p>
<p>열쇠 abc123</p>
<footer>
바닥글
<p>앱: 보관함</p>
<img alt="Next.js" loading="lazy" width="100" height="20" decoding="async" data-nimg="1" src="/next.svg"/>
</footer><nav><a href="/recipes">목록</a>·<a href="/stats">통계</a></nav>
<p>열쇠 undefined</p>
<p>열쇠 abc123</p>
<footer>
바닥글
<p>앱: 보관함</p>
<img alt="Next.js" loading="lazy" width="100" height="20" decoding="async" data-nimg="1" src="/next.svg">
</footer>(가) 클라이언트 컴포넌트도 서버가 먼저 그려 HTML로 보냅니다. Peek이 서버에서 읽은 abc123도, 서버 컴포넌트가 읽어 넘긴 abc123도 받은 HTML에 그대로 실렸습니다. 받은 HTML은 누구나 페이지 소스 보기로 봅니다. Peek 줄에서 abc123을 뺀 답은 비밀 환경 변수는 클라이언트 컴포넌트에서 읽어도 브라우저에서는 비니까 안전하다고 본 것이고, Tag 줄에서 뺀 답은 서버에서 읽어 props로 넘기면 안 보인다고 본 것입니다.
(나) 브라우저로 가는 JS에는 NEXT_PUBLIC_이 아닌 값이 없어, 브라우저에서 다시 그린 Peek은 열쇠 undefined를 그렸습니다. 두 번 그린 글이 달라 화면이 브라우저 판으로 바뀌었습니다. 배포 판 콘솔에는 이 하이드레이션 오류가 긴 글 대신 Minified React error #418 한 줄로 찍힙니다. Tag는 서버가 넘긴 props 값 abc123을 브라우저도 받아 그대로 그렸습니다. 비밀 값은 서버에서만 쓰고, 그린 결과나 props로 내보내지 않습니다.
다 봤으면 Ctrl+C로 배포 서버를 끄고 npm run dev로 개발 서버를 띄웁니다. 문제 4부터는 개발 판입니다.
다시 볼 레슨: 환경 변수(2절 — 클라이언트 컴포넌트가 비밀 값을 읽으면 · 자주 틀리는 곳) · 경계를 넘는 props(1절 — 레시피 객체 넘기기)
문제 4
2초 걸리는 일을 쪽과 처리기에 하나씩 둡니다. 처리기 app/api/slow/route.ts는 2초 기다린 뒤 {"done":true}를 돌려줍니다.
export async function GET() {
await new Promise((r) =>
setTimeout(r, 2000),
);
return Response.json({
done: true,
});
}쪽 app/slow/page.tsx는 <h1>느린 쪽</h1> 아래에, 2초 기다린 뒤 <p>늦은 글</p>을 그리는 Late를 <Suspense>로 감싸 둡니다. 기다리는 동안 대신 보일 글은 기다리는 중입니다. 아래는 쪽 함수의 몸 가운데 그리는 부분만 옮긴 조각입니다.
…
<h1>느린 쪽</h1>
<Suspense
fallback={
<p>기다리는 중</p>
}
>
<Late />
</Suspense>
…개발 서버를 켜 둔 채 두 주소를 한 번씩 열어 컴파일을 마친 뒤, 다시 요청해 받은 것을 봅니다.
(가) /slow에 요청을 보내면 늦은 글은 어떻게 올까요?
- ① 응답은
기다리는 중까지로 끝나고, 2초 뒤 브라우저가늦은 글을 따로 요청해 받는다 - ② 2초 동안 아무것도 오지 않다가
늦은 글까지 한꺼번에 온다 - ③ 같은 응답에서
기다리는 중이 든 덩어리가 먼저 오고, 2초 뒤늦은 글이 든 덩어리가 이어 온다
(나) /api/slow에 요청을 보내면 어떻게 올까요?
- ① 빈 덩어리가 먼저 오고 2초 뒤
{"done":true}가 이어 온다 - ② 2초 뒤
{"done":true}가 한 번에 온다 - ③ 바로
{"done":true}가 온다 — 처리기는 기다리지 않는다
힌트
(가)는 Suspense가 대신 보일 글을 언제 보내고, 채울 것은 어디에 싣는지 떠올립니다. (나)의 처리기에는 Suspense가 없습니다.
정답
(가) ③ · (나) ②입니다.
아래는 쪽 전부와, 두 주소를 한 번씩 연 뒤 다시 요청해 받은 것(다듬음), 서버 터미널입니다. 받은 상자의 덩어리 2 · 2초 뒤 줄은 앞 덩어리와 떨어져 온 자리입니다. 시간은 다를 수 있습니다.
import {
Suspense,
} from 'react';
async function Late() {
await new Promise((r) =>
setTimeout(r, 2000),
);
return <p>늦은 글</p>;
}
function Page() {
return (
<>
<h1>느린 쪽</h1>
<Suspense
fallback={
<p>기다리는 중</p>
}
>
<Late />
</Suspense>
</>
);
}
export default Page;<nav><a href="/recipes">목록</a>·<a href="/stats">통계</a></nav>
<h1>느린 쪽</h1>
<template id="B:0"></template>
<p>기다리는 중</p>
<footer>
바닥글
<p>앱: 보관함</p>
<img alt="Next.js" loading="lazy" width="100" height="20" decoding="async" data-nimg="1" src="/next.svg"/>
</footer>
<!-- 덩어리 2 · 2초 뒤 -->
<div hidden id="S:0">
<p>늦은 글</p>
</div>{"done":true}> 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
- Environments: .env.local
✓ Ready in 221ms
✓ Running next.config.ts took 1018ms
- Cache Components enabled
- Partial Prefetching enabled
GET /slow 200 in 2.1s (next.js: 53ms, application-code: 2.0s)
GET /slow 200 in 2.0s (next.js: 1.2ms, application-code: 2.0s)
GET /api/slow 200 in 2.0s (next.js: 15ms, application-code: 2.0s)
GET /api/slow 200 in 2.0s (next.js: 0.8ms, application-code: 2.0s)
(가) 요청은 한 번이고 응답도 하나입니다. 서버는 기다리는 중을 넣은 껍데기를 먼저 보내고, 같은 응답을 열어 둔 채 2초 뒤 늦은 글을 넣은 덩어리를 이어 보냈습니다. 브라우저는 그 덩어리로 대신 보인 글을 갈아 끼웁니다. ①은 Suspense로 감싼 곳은 브라우저가 나중에 따로 받아 온다고 본 것이고, ②는 Suspense 없이 기다린 쪽과 같다고 본 것입니다.
(나) 처리기는 GET이 돌려준 응답을 그대로 보냅니다. 2초 기다린 뒤 {"done":true} 한 덩어리가 왔고, 서버 터미널의 GET /api/slow 줄에도 2초쯤 걸린 것이 찍혔습니다. Suspense는 쪽을 그릴 때의 일이라 처리기의 응답을 나누지 않습니다.
다 봤으면 개발 서버는 켜 둡니다.
다시 볼 레슨: 흘려보내기(2절 — 받은 HTML의 덩어리 읽기) · 경로 처리기(1절 — 쪽 대신 응답을 만드는 파일)
문제 5
기억한 목록과 파일을 견주는 처리기 app/api/count/route.ts를 더합니다. kept는 'use cache'인 getRecipes()(cacheLife('hours'))가 돌려준 레시피 수, file은 파일을 바로 읽어 센 수입니다. 맨 위 import 줄은 …로 줄였습니다.
…
export async function GET() {
const kept =
await getRecipes();
const text = await readFile(
'data/recipes.json',
'utf8',
);
const list = JSON.parse(text);
return Response.json({
kept: kept.length,
file: list.length,
});
}개발 서버를 켜 둔 채 /api/count를 엽니다. 그다음 편집기로 data/recipes.json에서 마지막 레시피(r4)를 지워 저장하고, /api/count를 다시 엽니다.
(가) 처음 연 /api/count의 kept · file은 몇일까요?
(나) r4를 지운 뒤 다시 연 /api/count의 kept · file은 몇일까요?
힌트
getRecipes()가 기억한 것을 언제 지우는지 떠올립니다. 개발 서버는 데이터 파일을 지켜보지 않습니다.
정답
(가) kept 4 · file 4 · (나) kept 4 · file 3입니다.
아래는 처리기 전부와, 처음 연 받은 글, r4를 지운 data/recipes.json, 다시 연 받은 글입니다.
import {
readFile,
} from 'node:fs/promises';
import {
getRecipes,
} from '@/lib/recipes';
export async function GET() {
const kept =
await getRecipes();
const text = await readFile(
'data/recipes.json',
'utf8',
);
const list = JSON.parse(text);
return Response.json({
kept: kept.length,
file: list.length,
});
}{"kept":4,"file":4}[
{
"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
}
]
{"kept":4,"file":3}getRecipes()는 처음 불릴 때 파일을 읽어 넷을 기억했고, cacheLife('hours') 동안 그 기억을 줍니다. 편집기로 데이터 파일을 고쳐도 기억은 그대로라 kept는 4입니다. 기억을 지우려면 서버 함수에서 updateTag('recipes')를 부릅니다. 파일을 바로 읽은 file만 3이 되었습니다. (나)의 kept를 3으로 쓴 답은 데이터를 바꾸면 다음 요청에 바로 보인다고 본 것입니다.
다 봤으면 지운 r4를 되살려 data/recipes.json을 씨앗 넷으로 되돌립니다. 기억한 목록도 넷이라 서로 맞습니다.
다시 볼 레슨: 얼마나 기억하나(1절 — 'hours'의 세 수) · 'use cache' · 경로 처리기
문제 6
별점을 받는 쪽 /rate를 더합니다. 서버 함수 rate는 받은 star를 서버 터미널에 찍기만 합니다.
'use server';
async function rate(
formData: FormData,
) {
const star =
formData.get('star');
console.log('별점', star);
}
export { rate };쪽 app/rate/page.tsx는 rate를 단 폼 하나를 그립니다. 폼에는 이름이 star이고 처음 값이 5인 칸과 보내기 단추가 있습니다. 아래는 맨 위 import 줄을 …로 줄인 것입니다.
…
function Page() {
return (
<form action={rate}>
<input
name="star"
defaultValue="5"
/>
<button>보내기</button>
</form>
);
}
export default Page;개발 서버를 켜 둔 채, 브라우저는 쓰지 않고 다른 터미널 창에서 curl로 /rate에 POST를 보냅니다. 맥 · 리눅스는 터미널에서, 윈도는 Git Bash에서 칩니다(PowerShell · 명령 프롬프트는 줄 끝 \와 작은따옴표를 이렇게 읽지 않습니다). 이 요청은 내 컴퓨터의 개발 서버(localhost)에만 보냅니다. … 자리에는 /rate 페이지 소스의 폼에 있는 숨은 칸 name에서 $ACTION_ID_ 뒤의 긴 글자를 넣습니다.
curl -i localhost:3000/rate \
-F '$ACTION_ID_…=' \
-F 'star=1'
(가) curl을 보낸 뒤, 개발 서버 터미널에 rate가 찍는 줄은 어떻게 될까요?
- ①
별점 1—rate가 불린다 - ② 아무것도 — 폼 밖에서 보낸 요청이라
rate가 불리지 않는다 - ③
별점 5— 폼의 처음 값이 간다
(나) app/rate/actions.ts 맨 위 'use server'는 무엇을 표시할까요?
- ① 이 파일은 서버 컴포넌트다
- ② 클라이언트 컴포넌트가 이 파일을 import하면 빌드가 멈춘다
- ③ 이 파일이 내보내는 함수는 서버 함수다 — 폼이나 POST 요청으로 서버에서 부른다
힌트
(가)는 서버가 요청에서 무엇을 보고 서버 함수를 고르는지 떠올립니다. (나)는 서버 컴포넌트에 붙이는 표시가 있었는지, 빌드를 멈추게 하는 줄은 무엇이었는지 떠올립니다.
정답
(가) ① · (나) ③입니다.
아래는 쪽 전부와, curl과 같은 값(star=1)을 실어 보낸 POST의 응답 머리, 그 뒤의 개발 서버 터미널입니다. 이 POST는 JS를 끈 폼과 같은 요청으로 보냈습니다.
import {
rate,
} from './actions';
function Page() {
return (
<form action={rate}>
<input
name="star"
defaultValue="5"
/>
<button>보내기</button>
</form>
);
}
export default Page;HTTP/1.1 200 OK
Cache-Control: no-store
Content-Type: text/html; charset=utf-8
> 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
- Environments: .env.local
✓ Ready in 212ms
✓ Running next.config.ts took 1009ms
- Cache Components enabled
- Partial Prefetching enabled
GET /rate 200 in 147ms (next.js: 60ms, application-code: 87ms)
별점 1
POST /rate 200 in 18ms (next.js: 0.7ms, application-code: 18ms)
(가) 서버는 요청에 실린 액션 ID로 부를 서버 함수를 고릅니다. 폼에서 누른 요청인지는 보지 않아, curl로 보낸 star=1로 rate가 돌고 별점 1이 찍혔습니다. ②는 서버 함수는 내 폼에서만 불린다고 본 것이고, ③은 폼에 적힌 값만 간다고 본 것입니다. 받은 값은 서버 함수 안에서 검사합니다. curl은 브라우저와 달리 Origin 머리를 적지 않아, 서버 터미널의 별점 1 위에 ⚠ Missing으로 시작하는 경고 줄이 찍힙니다. 개발 서버는 경고만 찍고 요청을 그대로 처리합니다(손으로 두 번 잼).
(나) 'use server'는 서버 함수를 표시합니다. 서버 컴포넌트에는 표시가 없습니다 — 표시가 없으면 서버 컴포넌트입니다. ①은 'use server'가 서버 컴포넌트를 표시한다고 본 것입니다. ②는 import 'server-only';가 하는 일입니다. 클라이언트 컴포넌트 components/RecipeForm.tsx도 'use server' 파일 app/actions.ts의 createRecipe를 import하고, 빌드는 지나갑니다.
다시 볼 레슨: 서버 함수는 공개 입구(1절 — 폼이 막지 않는 값) · 서버 함수(1절 — 'use server'는 무엇을 표시하나) · 환경 변수(해 보기 — server-only로 막기)
문제 7
둘러보기 쪽 둘을 짓습니다. app/tour/layout.tsx는 쪽 위에 클라이언트 컴포넌트 Clicker를 그립니다. Clicker는 누를 때마다 1씩 느는 단추이고, 처음 글은 누름 0입니다. /tour/a는 <h1>A</h1>과 /tour/b로 가는 <Link>(B로)를, /tour/b는 <h1>B</h1>을 그립니다. 두 쪽의 metadata 제목은 'A' · 'B'입니다. Clicker는 맨 위 'use client'와 import 줄, 끝의 내보내기 줄을 …로 줄였습니다.
…
function Clicker() {
const [n, setN] = useState(0);
function handleClick() {
setN(n + 1);
}
return (
<button
onClick={handleClick}
>
{`누름 ${n}`}
</button>
);
}
…import Clicker from
'@/components/Clicker';
function TourLayout({
children,
}: LayoutProps<'/tour'>) {
return (
<section>
<Clicker />
{children}
</section>
);
}
export default TourLayout;/tour/a를 열어 단추를 두 번 누른 뒤 B로를 누릅니다.
(가) B로를 누른 뒤 단추의 글은 무엇일까요?
- ①
누름 2 - ②
누름 0 - ③ 단추가 사라진다
(나) 그 쪽에서 브라우저의 새로 고침을 누르면 단추의 글은 무엇일까요?
- ①
누름 2 - ②
누름 0
(다) B로를 누른 뒤 브라우저 탭의 제목은 무엇일까요?
힌트
(가)는 <Link>로 옮길 때 브라우저가 무엇을 받아 무엇을 갈아 끼우는지 떠올립니다. (다)는 루트 레이아웃의 제목 틀을 떠올립니다.
정답
(가) ① · (나) ② · (다) B · 레시피 보관함입니다.
아래는 Clicker와 두 쪽 전부, B로를 누른 뒤의 화면, 새로 고친 뒤의 화면입니다.
'use client';
import {
useState,
} from 'react';
function Clicker() {
const [n, setN] = useState(0);
function handleClick() {
setN(n + 1);
}
return (
<button
onClick={handleClick}
>
{`누름 ${n}`}
</button>
);
}
export default Clicker;import Link from 'next/link';
export const metadata = {
title: 'A',
};
function Page() {
return (
<>
<h1>A</h1>
<Link href="/tour/b">
B로
</Link>
</>
);
}
export default Page;export const metadata = {
title: 'B',
};
function Page() {
return <h1>B</h1>;
}
export default Page;<nav><a href="/recipes">목록</a>·<a href="/stats">통계</a></nav>
<section>
<button>누름 2</button>
<h1>B</h1>
</section>
<footer>
바닥글
<p>앱: 보관함</p>
<img alt="Next.js" loading="lazy" width="100" height="20" decoding="async" data-nimg="1" src="/next.svg">
</footer><nav><a href="/recipes">목록</a>·<a href="/stats">통계</a></nav>
<section>
<button>누름 0</button>
<h1>B</h1>
</section>
<footer>
바닥글
<p>앱: 보관함</p>
<img alt="Next.js" loading="lazy" width="100" height="20" decoding="async" data-nimg="1" src="/next.svg">
</footer>(가) <Link>로 옮기면 브라우저는 바뀐 쪽 조각만 받아 /tour/a의 자리에 /tour/b를 끼웁니다. 두 쪽이 같이 쓰는 app/tour/layout.tsx와 그 안의 Clicker는 그대로 남아 누름 2가 이어집니다. ②는 <Link>로 옮겨도 쪽을 통째로 새로 받는다고 본 것입니다.
(나) 새로 고침은 문서를 통째로 새로 받습니다. Clicker도 처음부터 다시 그려져 누름 0입니다.
(다) 루트 레이아웃의 제목 틀 '%s · 레시피 보관함'의 %s 자리에 /tour/b의 'B'가 들어갑니다. 옮긴 뒤 탭 제목도 바뀝니다(손으로 두 번 잼). 컴퓨터로 풀면 /tour/a를 열 때와 새로 고칠 때 서버 터미널에 [browser] Image with src로 시작하는 영어 경고 줄이 찍힙니다. 이 쪽에서 가장 크게 그려진 것이 바닥글 그림이라 loading="eager"를 권하는 안내이고, 쪽은 그대로 돕니다.
다시 볼 레슨: Link로 옮기기(2절 — 응답 머리 — 문서와 조각) · 레이아웃 겹치기(3절 — 주소마다 감싸는 레이아웃) · 제목과 설명(1절 — 루트 레이아웃에 앱 이름 달기 · 2절 — 쪽마다 제목 달기)
문제 8
/list에도 쪽이 있으면 어떻게 될까요? app/list/page.tsx를 만들어 <h1>옛 목록</h1>을 그립니다. proxy.ts는 8단원 판 그대로(matcher: '/list')입니다.
(가) /list에 요청을 보내면 무엇이 돌아올까요?
- ①
200과옛 목록쪽 - ②
307과location: /recipes - ③
500— 쪽과 proxy가 부딪친다
(나) /list/old에 요청을 보내면 무엇이 돌아올까요?
- ①
404와 없는 쪽(없는 쪽·주소를 확인하세요.) - ②
307과location: /recipes - ③
200과옛 목록쪽
힌트
(가)는 proxy가 쪽을 찾기 전에 도는지 뒤에 도는지 떠올립니다. (나)는 matcher에 적은 주소가 무엇인지 봅니다.
정답
(가) ② · (나) ①입니다.
아래는 쪽 전부와, 두 주소의 응답 머리, /list/old의 받은 HTML(다듬음)입니다.
function Page() {
return <h1>옛 목록</h1>;
}
export default Page;HTTP/1.1 307 Temporary Redirect
location: /recipes
HTTP/1.1 404 Not Found
Cache-Control: no-store
Content-Type: text/html; charset=utf-8
<nav><a href="/recipes">목록</a>·<a href="/stats">통계</a></nav>
<h1>없는 쪽</h1>
<p>주소를 확인하세요.</p>
<footer>
바닥글
<p>앱: 보관함</p>
<img alt="Next.js" loading="lazy" width="100" height="20" decoding="async" data-nimg="1" src="/next.svg"/>
</footer>(가) proxy는 쪽을 찾기 전에 돕니다. /list는 matcher에 맞아 proxy()가 307로 /recipes에 보냈고, app/list/page.tsx까지 가지 않았습니다. ①은 쪽 파일이 있으면 proxy보다 먼저라고 본 것입니다.
(나) matcher: '/list'는 /list 한 주소입니다. /list/old는 맞지 않아 proxy가 돌지 않았고, 그 주소의 쪽도 없어 app/not-found.tsx가 그린 없는 쪽이 404로 왔습니다. ②는 matcher가 아래 주소까지 덮는다고 본 것입니다.
다 봤으면 app/list 폴더를 지웁니다.
다시 볼 레슨: proxy.ts(1절 — 쪽보다 먼저 도는 파일) · 쪽과 주소 · 없는 쪽(1절 — app/not-found.tsx — 없는 쪽 짓기)
문제 9
레시피 보관함에 할 일 여섯을 둡니다. 할 일마다 맡는 파일을 보기에서 고르세요. 한 보기는 한 번만 씁니다.
- ㉠ 쪽이 정한 탭 제목 끝에
· 레시피 보관함을 붙인다 - ㉡
/recipes아래 쪽이 기다리는 동안레시피를 여는 중을 보인다 - ㉢
/recipes아래 쪽이 그리다 오류를 내면 대신 보일 화면을 둔다 - ㉣ 레시피 목록을 JSON 파일로 내려받는 주소를 연다
- ㉤ 8단원 판에서 옛 주소
/list로 온 요청을/recipes로 보낸다 - ㉥ 비밀 키의 값을 코드 밖에 둔다
보기:
- ①
.env.local - ②
app/api/recipes/route.ts - ③
app/layout.tsx의metadata - ④
app/recipes/error.tsx - ⑤
app/recipes/loading.tsx - ⑥
proxy.ts
힌트
파일 이름이 하는 일을 말해 주는 것부터 짝을 짓습니다. 쪽보다 먼저 도는 파일, 쪽 대신 응답을 만드는 파일, 쪽을 감싸는 파일을 가릅니다.
정답
㉠ ③ · ㉡ ⑤ · ㉢ ④ · ㉣ ② · ㉤ ⑥ · ㉥ ①입니다.
- ㉠ 루트 레이아웃의
metadata.title.template('%s · 레시피 보관함')이 아래 폴더의 쪽이 정한 제목(목록·통계· 문제 7의B)을%s자리에 넣습니다. - ㉡
loading.tsx는 같은 폴더의 쪽과 그 아래 폴더를 감싸, 기다리는 동안 대신 보입니다. 같은 폴더의 레이아웃은 감싸지 않습니다. - ㉢
error.tsx는 그 폴더 아래 쪽이 그리다 던진 오류를 받아 대신 그립니다. 8단원 판에는 아직 없는 파일이라, 이 일을 맡기려면 새로 만들어야 합니다(이 문제에서는 만들지 않습니다). - ㉣ JSON을 보내는 주소는 쪽 대신
route.ts의GET이 만듭니다(문제 2). - ㉤ 8단원 판의
/list보내기는 쪽을 찾기 전에 도는proxy.ts가 합니다(문제 8). - ㉥ 비밀 값은 프로젝트 뿌리의
.env.local에 둡니다. 템플릿의.gitignore가.env*를 막아 git에 올라가지 않습니다.
다시 볼 레슨: 제목과 설명 · loading.tsx · 오류 화면 · 경로 처리기 · proxy.ts · 환경 변수
문제 10 (만들어 보기)
만들어 보기는 골라서 풀어도 됩니다. 컴퓨터로 풀 때는 레시피 보관함에 파일을 만들어 저장하고 개발 서버로 열어 정답의 받은 글과 맞춰 봅니다. 폰으로 풀 때는 만들 파일의 경로와 코드를 종이에 쓰고 정답과 맞춰 봅니다.
레시피 이름만 차례대로 담은 JSON 배열을 돌려주는 주소 /api/titles를 만듭니다. 할 일은 셋입니다.
- 어느 폴더에 어느 이름의 파일을 만들지 정합니다.
- GET 요청이 오면
lib/recipes.ts의getRecipes()로 목록을 받습니다. - 레시피마다
title만 뽑아["김치볶음밥", …]처럼 JSON으로 돌려줍니다.
힌트
1은 백업 처리기가 놓인 자리를 봅니다. 3은 배열의 map으로 이름만 뽑습니다.
정답
만들 파일은 app/api/titles/route.ts 하나입니다. 아래는 모범 답과, 개발 서버로 /api/titles를 연 받은 글입니다.
import {
getRecipes,
} from '@/lib/recipes';
export async function GET() {
const list =
await getRecipes();
return Response.json(
list.map((r) => r.title),
);
}["김치볶음밥","토마토 파스타","계란말이","바나나 팬케이크"]폴더 app/api/titles/가 주소 /api/titles이고, 쪽 대신 응답을 만드니 route.ts입니다. getRecipes()는 'use cache' 함수라, 처리기에서 불러도 기억한 목록을 씁니다.
다시 볼 레슨: 경로 처리기(1절) · 'use cache'
다 봤으면 이 섞어 풀기로 레시피 보관함에 더한 폴더(app/api/first · app/api/now · app/api/slow · app/api/count · app/api/titles · app/key · app/slow · app/rate · app/tour)와 components/의 Peek.tsx · Tag.tsx · Clicker.tsx를 지웁니다. app/list는 문제 8에서 지웠습니다. data/recipes.json은 씨앗 넷이고, .env.local과 proxy.ts는 8단원 판 그대로입니다. 개발 서버를 끈 채 지웠다면, 다음 빌드 전에 npm run dev를 한 번 띄웠다가 Ctrl+C로 끕니다(빌드가 미리 그린 것 1절). 9단원은 이 판에서 시작합니다.