본문으로 건너뛰기

서버 함수

Next.js 목차 서버 함수 레슨 27 / 47

목차

서버 함수(Server Function)는 함수 몸 맨 앞이나 파일 맨 위에 'use server'를 단 async 함수로, 브라우저가 보낸 POST 요청 한 번으로 서버에서 불립니다. 이 레슨은 레시피를 더하는 서버 함수 createRecipe를 app/actions.ts에 만들어 새 쪽 /recipes/new의 폼에 달고, 보낸 레시피가 서버의 data/recipes.json에 쌓이는 차례를 받은 HTML과 서버 터미널로 봅니다.

왜 Next.js인가에서 짚은 리액트 판의 세 한계 가운데 '저장이 그 브라우저에만 있음'이 남았습니다. 지금 data/recipes.json은 서버가 읽기만 합니다. 브라우저에서 적은 레시피를 서버의 파일에 쓰려면, 브라우저가 서버의 함수를 부를 길이 있어야 합니다.

이 단원을 이미 안다면 단원 연습 문제의 진단 문항부터 풀고 틀린 레슨만 보세요 — 건너뛴 레슨은 끝의 바꾼 파일 접기를 붙여 넣고 넘어갑니다. 건너뛰든 처음부터 읽든, 시작 전에 단원 1~5 연습 문제로 레시피 보관함에 더한 쪽을 지웁니다. 두면 빌드가 멈춥니다(목록은 단원 5 연습 문제의 진단 끝 접기 '레슨을 건너뛸 때'와 그 연습 문제 끝 줄). 개발 서버를 끈 채 지웠다면 첫 빌드도 멈추니, 빌드가 미리 그린 것 1절처럼 npm run dev를 한 번 띄웠다가 끄고 빌드합니다.

1'use server'는 무엇을 표시하나

use client에서 파일 맨 위 'use client'는 클라이언트 컴포넌트의 경계를 표시했습니다. 그 짝처럼 보이는 'use server'가 있습니다. 개발 서버를 켜 둔 채 app/stats/page.tsx 맨 위에 'use server'; 한 줄을 붙여 저장하고 /stats를 열면, 이 쪽에 '서버 컴포넌트'라는 표시가 붙을까요? 고른 뒤 펼쳐 보세요. 맞혀 보기는 점수에 들지 않습니다.

  • ① 붙는다 — 서버에서만 그리라는 표시가 된다
  • ② 아무 일도 없다 — 서버 컴포넌트는 원래 서버에서 도니까
  • ③ 쪽이 오류로 멈춘다
결과 보기

③입니다. 아래는 지금의 app/stats/page.tsx, 맨 위에 'use server';를 붙여 저장한 판, 그 뒤 /stats를 연 서버 터미널입니다.

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

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

import {
  Suspense,
} from 'react';
import Count from
  '@/components/Count';
import {
  getRecipes,
} from '@/lib/recipes';

export default function Page() {
  const recipes = getRecipes();
  // 3. 쪽에서 Suspense로 감싸기
  return (
    <>
      <h1>통계</h1>
      <Suspense
        fallback={<p>세는 중</p>}
      >
        <Count
          recipes={recipes}
        />
      </Suspense>
    </>
  );
}
> 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 221ms
✓ Running next.config.ts took 1019ms
- Cache Components enabled
- Partial Prefetching enabled

⨯ ./app/stats/page.tsx:12:25
Error: Server Actions must be async functions.
  10 | } from '@/lib/recipes';
  11 |
> 12 | export default function Page() {
     |                         ^^^^
  13 |   const recipes = getRecipes();
  14 |   // 3. 쪽에서 Suspense로 감싸기
  15 |   return (

Ecmascript file had an error


 GET /stats 500 in 405ms (next.js: 371ms, application-code: 35ms)

'use server'는 서버 컴포넌트가 아니라 서버 함수의 표시입니다. 파일 맨 위에 두면 그 파일이 내보내는 것을 모두 서버 함수로 보고, 서버 함수는 async 함수여야 합니다. 쪽 함수 Page는 async가 아니라서 Server Actions must be async⁠로 시작하는 오류로 멈췄습니다(오류 글은 서버 함수를 다른 이름 Server Action으로 부릅니다). 서버 컴포넌트에는 따로 표시가 없습니다. 표시가 없으면 서버 컴포넌트입니다(Next.js 규칙 1). 그래서 'use server'는 서버 함수만 모은 파일의 맨 위에 둡니다.

다 봤으면 /stats 탭을 닫고 'use server'; 줄을 지워 저장합니다. 이제 서버 함수가 쓸 저장 함수부터 만듭니다. lib/recipes.ts 맨 위 import에 writeFile을 더하고, 맨 끝에 addRecipe를 둡니다.

lib/recipes.ts
…
  const recipe: Recipe = {
    id: crypto.randomUUID(),
    ...input,
    ingredients: [],
    favorite: false,
  };
  list.push(recipe);
  await writeFile(
    'data/recipes.json',
    JSON.stringify(
      list, null, 2,
    ),
  );
…
  • 앞부분은 getRecipes처럼 파일을 readFile로 읽습니다. 기억해 둔 getRecipes()는 파일보다 옛것일 수 있어, 그 위에 더해 쓰면 그사이 더한 레시피가 사라집니다.
  • id는 리액트 판 레시피 더하기처럼 crypto.randomUUID()가 주는 36자 무작위 글입니다. 재료는 빈 배열, 즐겨찾기는 false로 둡니다.
  • JSON.stringify(list, null, 2)⁠는 씨앗 파일처럼 두 칸씩 들여 써서 파일 전체를 다시 씁니다.

그다음 새 파일 app/actions.ts를 만듭니다. 맨 위 'use server'가 이 파일이 내보내는 함수를 모두 서버 함수로 만듭니다(Next.js 문서 use server — 'at the top of a file to indicate that all functions in the file are server-side').

app/actions.ts
'use server';
…
async function createRecipe(
  formData: FormData,
) {
  const title =
    formData.get('title');
…
  // 3. 저장하기
  await addRecipe({
…
}

export { createRecipe };
  • formData는 폼이 보낸 칸들입니다. formData.get('title')⁠은 name="title" 칸의 값을 꺼냅니다(name과 value).
  • get이 돌려주는 값의 타입은 글이 아니라 FormDataEntryValue | null⁠입니다(그 이름의 칸이 없으면 null). 그래서 typeof로 글인지 확인한 뒤 addRecipe에 넘깁니다(직접 만드는 확인 함수). 분 칸은 Number로 수로 바꿉니다.
  • 주석 // 3. 저장하기는 이 단원 끝까지 다듬어 갈 서버 함수 차례의 셋째 걸음입니다. 첫째 걸음은 다음 절의 폼에 둡니다.
lib/recipes.ts · app/actions.ts 전체
lib/recipes.ts
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;
};
app/actions.ts
'use server';

import {
  addRecipe,
} from '@/lib/recipes';

async function createRecipe(
  formData: FormData,
) {
  const title =
    formData.get('title');
  const category =
    formData.get('category');
  if (
    typeof title !== 'string' ||
    typeof category !== 'string'
  ) {
    return;
  }
  // 3. 저장하기
  await addRecipe({
    title,
    category,
    minutes: Number(
      formData.get('minutes'),
    ),
  });
}

export { createRecipe };

2폼이 서버 함수를 부르는 길

새 쪽 app/recipes/new/page.tsx⁠를 만듭니다. 폼의 action에 주소 글 대신 서버 함수 createRecipe를 넘깁니다. 폼 액션에서 <form action={add}>에 함수를 넘긴 것과 같은 꼴이고, 다른 것은 그 함수가 서버에 있다는 것입니다.

app/recipes/new/page.tsx
…
// 1. 폼에 서버 함수 달기
function Page() {
…
    <form action={createRecipe}>
      <input
        name="title"
        placeholder="이름"
      />
…
      <button>더하기</button>
    </form>
…

저장할 때 레시피 보관함 탭은 닫아 둡니다. 저장했으면 차례대로 합니다. 코드 파일을 고쳐 저장한 뒤에는 목록을 한 번 열고 시작합니다. 개발 서버는 저장할 때 기억해 둔 목록을 지우기 때문입니다(use cache 해 보기).

  1. 새 탭의 주소 칸에 /recipes를 쳐서 목록을 한 번 엽니다.
  2. 같은 탭 주소 칸에 /recipes/new를 쳐서 폼을 엽니다. 페이지 소스 보기(주소 앞에 view-source:)로 받은 HTML도 봅니다.
  3. 같은 탭에서 이름 크림 파스타, 분류 양식, 분 20을 넣고 '더하기'를 누릅니다.

차례를 건너뛰어 '더하기'에 addRecipe is not a function 오류가 뜨면, 개발 서버를 Ctrl+C로 껐다 다시 띄우고 1부터 다시 합니다.

app/recipes/new/page.tsx 전체 · 받은 HTML · 서버 터미널

아래는 1절 그대로의 두 파일과 새 쪽 파일, 2에서 받은 HTML(다듬음), 3까지 마친 서버 터미널입니다. 시간과 $ACTION_ID_ 뒤의 글자는 다를 수 있습니다.

lib/recipes.ts
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;
};
app/actions.ts
'use server';

import {
  addRecipe,
} from '@/lib/recipes';

async function createRecipe(
  formData: FormData,
) {
  const title =
    formData.get('title');
  const category =
    formData.get('category');
  if (
    typeof title !== 'string' ||
    typeof category !== 'string'
  ) {
    return;
  }
  // 3. 저장하기
  await addRecipe({
    title,
    category,
    minutes: Number(
      formData.get('minutes'),
    ),
  });
}

export { createRecipe };
app/recipes/new/page.tsx
import {
  createRecipe,
} from '@/app/actions';
import {
  categories,
} from '@/lib/recipes';

// 1. 폼에 서버 함수 달기
function Page() {
  const options =
    categories.map((c) => (
      <option key={c}>
        {c}
      </option>
    ));
  return (
    <form action={createRecipe}>
      <input
        name="title"
        placeholder="이름"
      />
      <select
        name="category"
        aria-label="분류"
      >
        {options}
      </select>
      <input
        name="minutes"
        type="number"
        placeholder="분"
      />
      <button>더하기</button>
    </form>
  );
}

export default Page;
HTML
<nav><a href="/recipes">▸ 목록</a>·<a href="/stats">통계</a></nav><section><h1>레시피</h1><form action="" encType="multipart/form-data" method="POST"><input type="hidden" name="$ACTION_ID_40faf3984058df621a96d443eedd314f1b1fbd664d"/><input placeholder="이름" name="title"/><select name="category" aria-label="분류"><option>한식</option><option>양식</option><option>일식</option><option>중식</option><option>디저트</option></select><input type="number" placeholder="분" name="minutes"/><button>더하기</button></form></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 232ms
✓ Running next.config.ts took 1006ms
- Cache Components enabled
- Partial Prefetching enabled

레시피 파일 읽음
 Cache  레시피 파일 읽음
 GET /recipes 200 in 184ms (next.js: 60ms, application-code: 124ms)
 Cache  레시피 파일 읽음
 Cache  레시피 파일 읽음
 GET /recipes/new 200 in 30ms (next.js: 10ms, application-code: 19ms)
 GET /recipes/new 200 in 16ms (next.js: 0.8ms, application-code: 16ms)
 POST /recipes/new 200 in 8ms (next.js: 0.6ms, application-code: 7ms)
  └─ ƒ createRecipe({}) in 1ms app/actions.ts

받은 HTML의 폼에는 method="POST"와 encType="multipart/form-data"⁠가 붙었습니다. 폼 맨 앞에는 화면에 안 보이는 숨은 칸(type="hidden")이 하나 있고, 그 name이 $ACTION_ID_…입니다. $ACTION_ID_ 뒤의 긴 글자는 서버 함수의 ID입니다. 함수 몸은 브라우저로 가지 않고 서버에 남습니다. 브라우저는 이 ID를 실어 POST를 보내고, 서버가 ID로 createRecipe를 찾아 부릅니다(Next.js 문서 Server Actions 'Security' — 'an action ID plus a dispatcher that POSTs back to the server').

서버 터미널의 POST /recipes/new 200⁠이 '더하기'를 누른 때입니다. 바로 아래 └─ ƒ createRecipe({}) 줄은 개발 판이 서버 함수를 부르면 함수 이름 · 인자 · 걸린 시간을 찍는 줄입니다(Next.js 문서 logging 'Server Functions'). FormData 인자는 {}로 보입니다. 편집기에서 data/recipes.json을 열면 맨 끝에 레시피가 하나 더 있습니다.

JSON
  {
    "id": "…",
    "title": "크림 파스타",
    "category": "양식",
    "minutes": 20,
    "ingredients": [],
    "favorite": false
  }
]

id 자리의 글은 더할 때마다 다릅니다. 저장은 브라우저가 아니라 서버의 파일에 됐습니다.

Next.js 규칙 8. 바꾸는 일은 서버 함수로 합니다. 'use server' 함수는 브라우저가 보내는 POST 한 번으로 불립니다(이 과목은 폼으로 부릅니다). 누구나 그 입구로 보낼 수 있으니 함수 안에서 검사합니다.

검사는 이 단원 끝 레슨 서버 함수는 공개 입구에서 합니다.

3저장한 뒤 목록을 다시 열면

2절 차례에 한 걸음을 더합니다. 4. 같은 탭 주소 칸에 /recipes를 쳐서 목록을 새로 엽니다. lib/recipes.ts는 얼마나 기억하나 끝에 되돌린 cacheLife('hours') 그대로입니다. 목록에 크림 파스타가 보일까요? 고른 뒤 펼쳐 보세요. 맞혀 보기는 점수에 들지 않습니다.

  • ① 보인다 — 파일에 저장됐으니까
  • ② 보이지 않는다 — 레시피 넷 그대로다
  • ③ 목록 자리가 오류로 멈춘다
결과 보기

②입니다. 아래는 2절 그대로의 세 파일과, 2절의 1 ~ 3 뒤 4에서 연 목록 화면입니다. 2절과 4 사이에 개발 서버를 껐다 켰다면 목록은 다섯입니다. 그때는 data/recipes.json을 씨앗 넷으로 되돌리고 2절의 1부터 다시 합니다.

lib/recipes.ts
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;
};
app/actions.ts
'use server';

import {
  addRecipe,
} from '@/lib/recipes';

async function createRecipe(
  formData: FormData,
) {
  const title =
    formData.get('title');
  const category =
    formData.get('category');
  if (
    typeof title !== 'string' ||
    typeof category !== 'string'
  ) {
    return;
  }
  // 3. 저장하기
  await addRecipe({
    title,
    category,
    minutes: Number(
      formData.get('minutes'),
    ),
  });
}

export { createRecipe };
app/recipes/new/page.tsx
import {
  createRecipe,
} from '@/app/actions';
import {
  categories,
} from '@/lib/recipes';

// 1. 폼에 서버 함수 달기
function Page() {
  const options =
    categories.map((c) => (
      <option key={c}>
        {c}
      </option>
    ));
  return (
    <form action={createRecipe}>
      <input
        name="title"
        placeholder="이름"
      />
      <select
        name="category"
        aria-label="분류"
      >
        {options}
      </select>
      <input
        name="minutes"
        type="number"
        placeholder="분"
      />
      <button>더하기</button>
    </form>
  );
}

export default Page;
<nav><a href="/recipes">▸ 목록</a>·<a href="/stats">통계</a></nav><section><h1>레시피</h1><form action="/recipes"><input name="q"><button>찾기</button></form><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>
결과 화면

data/recipes.json에는 크림 파스타가 있는데 목록은 넷입니다. 목록을 그리는 getRecipes는 'use cache'로 1에서 읽은 넷을 기억해 두었고, 4의 요청에 그 기억을 그대로 주었습니다(Next.js 규칙 7). createRecipe는 파일에 썼을 뿐, 기억은 건드리지 않았습니다. 기억을 지워 다시 읽게 하는 길은 다음 레슨 바꾼 뒤 다시 읽기에서 봅니다.

앞으로 코드를 고쳐 저장한 뒤 목록을 열지 않고 바로 더하면, 저장이 지운 기억 탓에 새 레시피가 보여 까닭이 흐려집니다. 개발 판에서는 '코드를 고쳐 저장 → 목록을 한 번 연다 → 데이터를 바꾼다 → 다시 연다' 차례를 지킵니다.

해 보기 — JS를 끄고 보내기

폼은 브라우저 JS 없이도 서버 함수를 부를까요? 개발자 도구를 연 채 Ctrl+Shift+P(맥은 Cmd+Shift+P)로 명령 메뉴를 열고 Disable JavaScript를 고릅니다(하이드레이션에서 쓴 길). /recipes/new를 새로 고친 뒤 이름 떡볶이, 분 30을 넣고 '더하기'를 누릅니다. 어떻게 될까요? 고른 뒤 펼쳐 보세요.

  • ① 아무 일도 없다 — 서버 함수를 부르는 것은 브라우저 JS니까
  • ② 브라우저가 폼을 POST로 보내고, 서버가 보낸 쪽을 새로 받는다
  • ③ 오류 쪽이 뜬다
결과 보기

②입니다. 아래는 2절 그대로의 세 파일, JS 없이 '더하기'를 누른 뒤의 서버 터미널과 그 POST에 돌아온 HTML(다듬음)입니다.

lib/recipes.ts
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;
};
app/actions.ts
'use server';

import {
  addRecipe,
} from '@/lib/recipes';

async function createRecipe(
  formData: FormData,
) {
  const title =
    formData.get('title');
  const category =
    formData.get('category');
  if (
    typeof title !== 'string' ||
    typeof category !== 'string'
  ) {
    return;
  }
  // 3. 저장하기
  await addRecipe({
    title,
    category,
    minutes: Number(
      formData.get('minutes'),
    ),
  });
}

export { createRecipe };
app/recipes/new/page.tsx
import {
  createRecipe,
} from '@/app/actions';
import {
  categories,
} from '@/lib/recipes';

// 1. 폼에 서버 함수 달기
function Page() {
  const options =
    categories.map((c) => (
      <option key={c}>
        {c}
      </option>
    ));
  return (
    <form action={createRecipe}>
      <input
        name="title"
        placeholder="이름"
      />
      <select
        name="category"
        aria-label="분류"
      >
        {options}
      </select>
      <input
        name="minutes"
        type="number"
        placeholder="분"
      />
      <button>더하기</button>
    </form>
  );
}

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 206ms
✓ Running next.config.ts took 974ms
- Cache Components enabled
- Partial Prefetching enabled

 GET /recipes/new 200 in 136ms (next.js: 62ms, application-code: 74ms)
 POST /recipes/new 200 in 21ms (next.js: 0.6ms, application-code: 21ms)
HTML
<nav><a href="/recipes">▸ 목록</a>·<a href="/stats">통계</a></nav><section><h1>레시피</h1><form action="" encType="multipart/form-data" method="POST"><input type="hidden" name="$ACTION_ID_40566a30572cbb98a4d8be74fca466c52fd5bddbc1"/><input placeholder="이름" name="title"/><select name="category" aria-label="분류"><option>한식</option><option>양식</option><option>일식</option><option>중식</option><option>디저트</option></select><input type="number" placeholder="분" name="minutes"/><button>더하기</button></form></section><footer>바닥글</footer>
결과 화면

JS가 없으면 브라우저는 보통 HTML 폼처럼 칸들을 POST로 보냅니다(폼과 제출). 숨은 칸 $ACTION_ID_…도 함께 가서, 서버는 JS로 보낸 때와 같이 createRecipe를 부릅니다. 돌아온 것은 같은 쪽 /recipes/new의 HTML이라 화면은 빈 폼으로 다시 그려집니다. 이번 POST /recipes/new 200 줄 아래에는 2절과 달리 └─ ƒ createRecipe 줄이 없습니다. JS 없이 보낸 폼의 부름에는 이 줄이 찍히지 않았습니다. data/recipes.json 맨 끝에는 떡볶이가 더해졌습니다.

다 봤으면 같은 명령 메뉴에서 Enable JavaScript를 고릅니다. 그리고 data/recipes.json에서 2절과 해 보기에서 더한 크림 파스타 · 떡볶이를 지워 씨앗 넷으로 되돌립니다. 바나나 팬케이크의 닫는 } 뒤 쉼표부터 맨 끝 ] 앞까지 지우면 됩니다.

예제

같은 차례를 배포 판으로 합니다. 개발 서버를 Ctrl+C로 끄고 npm run build → npm run start로 띄운 뒤, 탭 하나로 목록을 한 번 열고 김밥을 더하고 /recipes를 다시 엽니다. 목록은 어떨까요? 고른 뒤 펼쳐 보세요. 맞혀 보기는 점수에 들지 않습니다.

  • ① 레시피가 하나 줄어든다 — 파일을 다시 써서
  • ② 김밥이 더해져 보인다 — 배포 판은 요청마다 그리니까
  • ③ 더하기 전 그대로다
결과 보기

③입니다. 아래는 2절 그대로의 세 파일과, 김밥을 더한 뒤 다시 연 배포 판 목록의 받은 HTML(다듬음)입니다.

lib/recipes.ts
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;
};
app/actions.ts
'use server';

import {
  addRecipe,
} from '@/lib/recipes';

async function createRecipe(
  formData: FormData,
) {
  const title =
    formData.get('title');
  const category =
    formData.get('category');
  if (
    typeof title !== 'string' ||
    typeof category !== 'string'
  ) {
    return;
  }
  // 3. 저장하기
  await addRecipe({
    title,
    category,
    minutes: Number(
      formData.get('minutes'),
    ),
  });
}

export { createRecipe };
app/recipes/new/page.tsx
import {
  createRecipe,
} from '@/app/actions';
import {
  categories,
} from '@/lib/recipes';

// 1. 폼에 서버 함수 달기
function Page() {
  const options =
    categories.map((c) => (
      <option key={c}>
        {c}
      </option>
    ));
  return (
    <form action={createRecipe}>
      <input
        name="title"
        placeholder="이름"
      />
      <select
        name="category"
        aria-label="분류"
      >
        {options}
      </select>
      <input
        name="minutes"
        type="number"
        placeholder="분"
      />
      <button>더하기</button>
    </form>
  );
}

export default Page;
HTML
<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>
결과 화면

배포 판도 getRecipes가 기억한 목록을 줍니다. 김밥은 파일에만 있습니다. 개발 판만의 일이 아닙니다.

다 봤으면 배포 판을 Ctrl+C로 끄고, data/recipes.json에서 예제에서 더한 김밥을 지워 씨앗 넷으로 되돌립니다. 다음 레슨이 같은 장면을 씨앗 넷에서 다시 엽니다. 개발 서버도 npm run dev로 다시 띄웁니다.

자주 틀리는 곳

틀린 생각: 'use server'는 서버 컴포넌트를 표시한다.

맞는 규칙: 'use server'는 서버 함수를 표시합니다. 서버 컴포넌트에는 표시가 없습니다(1절). 쪽 파일 맨 위에 붙이면 쪽 함수도 서버 함수로 보여 Server Actions must be async⁠로 시작하는 오류로 멈춥니다.

틀린 생각: 서버 함수는 그 함수를 쓰는 클라이언트 컴포넌트 파일 안에 두면 된다.

맞는 규칙: 'use client' 파일 안에서는 서버 함수를 만들 수 없습니다. 그 안에 'use server'를 단 함수를 두면 It is not allowed to define⁠으로 시작하는 오류로 멈춥니다. 이어지는 글에 inline "use server"와 in Client Components가 있습니다. 서버 함수는 app/actions.ts처럼 맨 위에 'use server'를 단 파일에 두고 가져다 씁니다.

확인 문제

문제 1. app/actions.ts 맨 위의 'use server'; 줄이 하는 일은 무엇일까요?

  • ① 그 파일이 내보내는 함수를 모두 서버 함수로 만든다
  • ② 그 파일을 import 하는 쪽을 서버 컴포넌트로 만든다
  • ③ 그 파일을 빌드 때 한 번만 돌린다
정답

①입니다. 브라우저는 그 함수를 ID로 불러 서버에서 돌립니다.

  • ② 서버 컴포넌트에는 표시가 없습니다. 쪽에 붙이면 오히려 오류로 멈춥니다.
  • ③ 서버 함수는 폼을 보낼 때마다 요청 때 돕니다.

문제 2. /recipes/new의 받은 HTML 폼에 name이 $ACTION_ID_…인 숨은 칸이 있습니다. 이 칸은 무엇일까요?

  • ① 사용자가 이름을 적는 칸
  • ② 서버가 부를 서버 함수를 찾는 ID — 함수 몸은 서버에 남는다
  • ③ createRecipe의 코드를 글로 바꿔 실은 것
정답

②입니다. 폼을 보내면 이 칸도 함께 가고, 서버가 ID로 createRecipe를 찾아 부릅니다.

  • ① 이름 칸은 name="title"인 보이는 칸입니다.
  • ③ 함수 몸은 브라우저로 가지 않습니다. 브라우저에는 ID만 있습니다.

문제 3. (개발 판 · cacheLife('hours') 그대로) app/actions.ts를 고쳐 저장한 뒤 주소 칸에 /recipes를 쳐서 목록을 한 번 열었습니다. 그다음 /recipes/new에서 김밥을 더하고 /recipes를 다시 열었습니다. data/recipes.json과 목록은 어떨까요?

  • ① 둘 다 김밥이 있다
  • ② 둘 다 김밥이 없다
  • ③ 파일에는 김밥이 있고, 목록에는 없다
정답

③입니다. 서버 함수가 파일에 썼고, 목록은 getRecipes가 기억한 넷을 줍니다.

  • ① 목록은 기억한 결과라 파일을 다시 읽지 않았습니다.
  • ② 저장은 됐습니다. 어긋남은 목록뿐입니다.
이 레슨에서 바꾼 파일

lib/recipes.ts — import에 writeFile · 맨 끝에 addRecipe

lib/recipes.ts
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;
};

app/actions.ts — 새 파일 · 서버 함수 createRecipe

app/actions.ts
'use server';

import {
  addRecipe,
} from '@/lib/recipes';

async function createRecipe(
  formData: FormData,
) {
  const title =
    formData.get('title');
  const category =
    formData.get('category');
  if (
    typeof title !== 'string' ||
    typeof category !== 'string'
  ) {
    return;
  }
  // 3. 저장하기
  await addRecipe({
    title,
    category,
    minutes: Number(
      formData.get('minutes'),
    ),
  });
}

export { createRecipe };

app/recipes/new/page.tsx — 새 쪽 · 폼의 action에 createRecipe

app/recipes/new/page.tsx
import {
  createRecipe,
} from '@/app/actions';
import {
  categories,
} from '@/lib/recipes';

// 1. 폼에 서버 함수 달기
function Page() {
  const options =
    categories.map((c) => (
      <option key={c}>
        {c}
      </option>
    ));
  return (
    <form action={createRecipe}>
      <input
        name="title"
        placeholder="이름"
      />
      <select
        name="category"
        aria-label="분류"
      >
        {options}
      </select>
      <input
        name="minutes"
        type="number"
        placeholder="분"
      />
      <button>더하기</button>
    </form>
  );
}

export default Page;

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

Next.js 목차로