본문으로 건너뛰기

서버 함수는 공개 입구

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

목차

서버 함수는 누구나 두드릴 수 있는 공개 입구입니다. 폼이 보내는 것은 주소 하나와 칸 몇 개를 실은 보통 POST 요청이라, 숨은 칸 값만 알면 폼 밖에서도 같은 꼴로 보낼 수 있습니다. 이 레슨은 폼 밖에서 보낸 POST도 createRecipe를 부르는 것을 보고, 들어온 값을 서버 함수 안에서 검사하도록 고칩니다.

지금 createRecipe는 이름이 비었는지와 분류 칸이 글인지만 봅니다. 분에 -5를 넣어도, 다섯 분류에 없는 간식을 보내도 그대로 저장합니다. 화면의 폼은 분류를 다섯 가운데서만 고르게 하지만, 서버 함수에 닿는 것은 폼이 아니라 요청입니다.

1폼이 막지 않는 값

저장 뒤 다른 쪽으로 끝의 파일 그대로, 새 탭으로 목록을 한 번 연 뒤 같은 탭에서 /recipes/new를 열어 이름 김밥, 분 -5를 넣고 '더하기'를 누릅니다.

app/actions.ts 전체 · 옮겨 간 화면

아래는 지금의 app/actions.ts와 '더하기' 뒤의 화면입니다. 주소의 긴 글자는 다를 수 있습니다.

app/actions.ts
'use server';

import {
  updateTag,
} from 'next/cache';
import {
  redirect,
} from 'next/navigation';
import {
  addRecipe,
} 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 (
    typeof category !== 'string'
  ) {
    return {
      error: '분류를 골라 주세요',
    };
  }
  // 3. 저장하기
  const recipe =
    await addRecipe({
      title: title.trim(),
      category,
      minutes: Number(
        formData.get('minutes'),
      ),
    });
  // 4. 기억 지우기
  updateTag('recipes');
  // 5. 새 쪽으로 보내기
  redirect(
    '/recipes/' + recipe.id,
  );
}

export { createRecipe };
<nav><a href="/recipes">▸ 목록</a>·<a href="/stats">통계</a></nav><section><h1>레시피</h1><h2>김밥</h2><section><button>재료 보기</button></section></section><footer>바닥글</footer>
결과 화면

김밥 쪽으로 옮겨 갔으니 저장된 것입니다. data/recipes.json 끝에는 "minutes": -5가 그대로 있습니다. 분 칸에 min="1"을 달면 브라우저가 보내기 전에 막아 줄까요? 고른 뒤 펼쳐 보세요. 맞혀 보기는 점수에 들지 않습니다.

  • ① 막는다 — 서버 함수도 min을 보고 거절한다
  • ② 폼에서 보낸 것만 막는다 — 폼 밖에서 보낸 -5는 그대로 저장된다
  • ③ 아무것도 막지 못한다
결과 보기

②입니다. min은 브라우저가 보내기 전에 보는 칸 검사입니다(폼 검사). 요청에는 min이 실리지 않아 서버 함수는 그런 줄이 있는지 모릅니다. 폼을 거치지 않고 보낸 POST에는 브라우저 검사가 돌 자리도 없습니다. 해 보기에서 폼 밖 요청을 직접 보냅니다.

브라우저의 칸 검사는 쓰는 사람을 돕는 것이고, 데이터를 지키는 검사는 서버 함수 안에 둡니다(Next.js 규칙 8). 요청은 화면을 거치지 않고도 보낼 수 있기 때문입니다(Next.js 문서 Server Actions 'Security' — 'requests can be sent without going through the UI').

2서버 함수 안에서 검사하기

createRecipe의 둘째 걸음 // 2. 값 꺼내 검사하기를 넓힙니다. app/actions.ts가 lib/recipes.ts에서 categories도 가져오게 하고, 검사를 셋 더합니다.

app/actions.ts
…
  if (
    !categories.includes(
      category,
    )
  ) {
…
  const minutes = Number(
    formData.get('minutes'),
  );
  if (
    minutes < 1 ||
    !Number.isInteger(minutes)
  ) {
…
  • 이름은 빈 이름 검사 다음에 title.length > 30이면 이름은 30자까지를 돌려줍니다.
  • 분류는 글인지 본 다음, 다섯 분류 categories에 있는지 includes로 봅니다. 없으면 분류를 골라 주세요입니다.
  • 분은 Number로 바꾼 값이 정수이고 1 이상인지 봅니다. Number.isInteger는 2.5나 글자에서 나온 NaN이면 false입니다. 걸리면 분은 1 이상 정수로를 돌려주고, 저장에는 검사한 minutes를 넘깁니다.
  • 로그인한 사람만 더하게 하려면 '누가 보냈나'도 이 자리에서 봅니다. 이 과목은 로그인을 다루지 않습니다.

탭을 닫은 채 저장했으면, 새 탭으로 /recipes/new를 열어 1절처럼 김밥, 분 -5로 '더하기'를 누릅니다.

app/actions.ts 전체 · 화면 · 서버 터미널

아래는 검사를 넣은 app/actions.ts, '더하기' 뒤의 화면과 서버 터미널입니다.

app/actions.ts
'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 };
<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_REF_1"><input type="hidden" name="$ACTION_1:0" value="{&quot;id&quot;:&quot;60c391ae855bacdd63d859c8f4d190982fd80721ad&quot;,&quot;bound&quot;:&quot;$@1&quot;}"><input type="hidden" name="$ACTION_1:1" value="[{&quot;error&quot;:&quot;&quot;}]"><input type="hidden" name="$ACTION_KEY" value="kc129f751bf5a29f039165561ecca967b"><input placeholder="이름" name="title"><select name="category" aria-label="분류"><option selected="">한식</option><option>양식</option><option>일식</option><option>중식</option><option>디저트</option></select><input type="number" placeholder="분" name="minutes"><button>더하기</button><p>분은 1 이상 정수로</p></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 207ms
✓ Running next.config.ts took 1054ms
- Cache Components enabled
- Partial Prefetching enabled

더하기 쪽을 그림
 GET /recipes/new 200 in 138ms (next.js: 60ms, application-code: 78ms)
 POST /recipes/new 200 in 13ms (next.js: 1.3ms, application-code: 12ms)
  └─ ƒ createRecipe({"error":""}, {}) in 0ms app/actions.ts

폼 아래에 분은 1 이상 정수로가 보이고 쪽은 옮겨 가지 않습니다. 검사에 걸려 저장 · 기억 지우기 · 보내기까지 가지 않았습니다.

이로써 왜 Next.js인가에서 짚은 세 한계 가운데 남은 하나, '그 브라우저에만 저장'을 풀었습니다. 레시피는 서버의 파일에 쌓이고, 어느 브라우저로 열어도 같은 목록입니다.

해 보기 — curl로 '분 -5' 보내기

폼 밖에서 보내 봅니다. curl은 컴퓨터 터미널에서 HTTP 요청을 보내는 명령입니다. 이 요청은 내 컴퓨터의 개발 서버(localhost)에만 보냅니다. 남의 사이트에 이런 요청을 보내지 않습니다.

  1. 개발 서버를 켠 채 /recipes/new의 페이지 소스 보기를 엽니다. 폼 맨 앞 숨은 칸 넷의 name과 value를 찾습니다.
  2. 개발 서버와 다른 터미널 창에서 아래 명령을 칩니다. 맥 · 리눅스는 터미널에서, 윈도는 Git Bash에서 칩니다(PowerShell · 명령 프롬프트는 줄 끝 \와 작은따옴표를 이렇게 읽지 않습니다). … 자리에는 1에서 찾은 value를 넣습니다. 소스의 &quot;는 "로 바꿔 넣습니다.
curl -i \
  localhost:3000/recipes/new \
  -F '$ACTION_REF_1=' \
  -F '$ACTION_1:0=…' \
  -F '$ACTION_1:1=…' \
  -F '$ACTION_KEY=…' \
  -F 'title=김밥' \
  -F 'category=한식' \
  -F 'minutes=-5'

curl이 받은 응답과 서버 터미널은 어떨까요? 고른 뒤 펼쳐 보세요.

  • ① createRecipe가 불리지 않는다 — 내 폼에서 보낸 요청이 아니니까
  • ② createRecipe가 불려 -5가 저장된다
  • ③ createRecipe가 불리고, 검사에 걸려 메시지가 든 HTML이 온다
결과 보기

③입니다. 응답 첫 줄은 HTTP/1.1 200 OK이고, 받은 HTML의 폼 아래에 <p>분은 1 이상 정수로</p>가 있습니다. data/recipes.json은 그대로입니다. 서버 터미널에는 POST /recipes/new 200 위에 ⚠ Missing으로 시작하는 경고 줄이 찍힙니다. origin 머리가 없는 요청이라는 뜻입니다. 브라우저는 폼을 보낼 때 어느 사이트에서 왔는지를 Origin 머리에 적는데, curl은 적지 않았습니다. 개발 서버는 경고만 찍고 요청을 그대로 처리했습니다. 2절의 검사를 넣기 전이었다면 303 See Other와 새 레시피 주소가 와서 -5가 저장됐을 것입니다. 입구는 주소와 숨은 칸만 알면 열립니다. 그래서 검사는 서버 함수 안에 둡니다.

예제

이름 칸에 김치를 열다섯 번 잇고 전을 붙인 31자를 넣고, 분 10으로 '더하기'를 누르면 어떻게 될까요? 고른 뒤 펼쳐 보세요. 맞혀 보기는 점수에 들지 않습니다.

  • ① 30자까지만 잘려 저장된다
  • ② 저장되지 않고 이름은 30자까지가 보인다
  • ③ 오류 쪽이 뜬다
결과 보기

②입니다. 아래는 2절 그대로의 app/actions.ts와 '더하기' 뒤의 화면입니다.

app/actions.ts
'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 };
<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_REF_1"><input type="hidden" name="$ACTION_1:0" value="{&quot;id&quot;:&quot;600c9f7ed82918c72fb1b1997e2599164384d61376&quot;,&quot;bound&quot;:&quot;$@1&quot;}"><input type="hidden" name="$ACTION_1:1" value="[{&quot;error&quot;:&quot;&quot;}]"><input type="hidden" name="$ACTION_KEY" value="kc129f751bf5a29f039165561ecca967b"><input placeholder="이름" name="title"><select name="category" aria-label="분류"><option selected="">한식</option><option>양식</option><option>일식</option><option>중식</option><option>디저트</option></select><input type="number" placeholder="분" name="minutes"><button>더하기</button><p>이름은 30자까지</p></form></section><footer>바닥글</footer>
결과 화면

서버 함수는 값을 고쳐 저장하지 않습니다. 검사에 걸리면 메시지만 돌려주고, 고치는 일은 쓰는 사람에게 맡깁니다.

다 봤으면 data/recipes.json에서 1절에 더한 -5분 김밥을 지워 씨앗 넷으로 되돌립니다. 되돌린 뒤 개발 서버를 Ctrl+C로 끄고 npm run dev로 다시 띄웁니다.

자주 틀리는 곳

틀린 생각: 서버 함수는 내 폼에서만 불린다.

맞는 규칙: 폼이 보내는 것은 보통 POST 요청입니다. 주소와 숨은 칸을 알면 curl로도 같은 함수를 부릅니다(해 보기).

틀린 생각: 칸에 required · min을 달아 두었으니 서버는 따로 검사하지 않아도 된다.

맞는 규칙: 브라우저 칸 검사는 폼에서 보낼 때만 돕니다. 폼 밖 요청에는 닿지 않으니, 지켜야 할 값은 서버 함수 안에서 다시 봅니다.

틀린 생각: 무엇이 틀렸는지 자세히 알려 주려고, 잡은 오류를 그대로 메시지에 담는다.

맞는 규칙: 원래 오류 글에는 파일 경로 같은 서버 속 사정이 들어 있습니다. 돌려준 값은 누구에게나 갑니다. 메시지는 분은 1 이상 정수로처럼 쓰는 사람이 고칠 것만 적습니다.

확인 문제

문제 1. curl로 /recipes/new에 숨은 칸과 이름 칸을 실어 POST를 보냈습니다. createRecipe는 어떻게 될까요?

  • ① 불린다 — 폼에서 보낸 것과 같은 요청이니까
  • ② 불리지 않는다 — 브라우저가 보낸 것이 아니니까
  • ③ 개발 서버에서만 불린다
정답

①입니다. 서버 함수에 닿는 것은 요청이고, 누가 보냈는지는 함수가 스스로 봐야 압니다.

  • ② 브라우저가 보내지 않아도 요청은 처리됩니다. 개발 서버는 Origin 머리가 없다는 경고만 찍었습니다.
  • ③ 배포 서버(npm run start)도 같은 경고만 찍고 createRecipe를 부릅니다.

문제 2. 분 칸에 min="1"만 달고 서버 함수에는 분 검사가 없습니다. 무엇이 막힐까요?

  • ① 폼 밖에서 보낸 -5
  • ② 아무것도 막히지 않는다
  • ③ 폼에서 -5를 넣고 '더하기'를 누른 것
정답

③입니다. min은 브라우저가 폼을 보내기 전에만 봅니다.

  • ① 폼 밖 요청에는 min이 없어 그대로 저장됩니다.
  • ② 폼에서 보낼 때는 브라우저가 막습니다.

문제 3. 2절의 분 검사(minutes < 1 · Number.isInteger)를 지나 저장되는 값은 무엇일까요?

  • ① 2.5
  • ② 3
  • ③ 0
정답

②입니다. 정수이고 1 이상인 값만 지나갑니다.

  • ① 2.5는 정수가 아니라 Number.isInteger가 false입니다.
  • ③ 0은 1보다 작습니다.
이 레슨에서 바꾼 파일

app/actions.ts — categories import · 이름 길이 · 분류 · 분 검사

app/actions.ts
'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 };
이 단원 끝 파일

단원 6에서 바꾼 파일을 모두 끝 판으로 모았습니다. 건너뛴 레슨이 있으면 이 넷을 붙여 넣고 다음 단원으로 갑니다.

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(1 ~ 5)

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

components/RecipeForm.tsx — useActionState 폼

components/RecipeForm.tsx
'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;

app/recipes/new/page.tsx — 새 쪽 · RecipeForm

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

function Page() {
  console.log(
    '더하기 쪽을 그림',
  );
  return (
    <RecipeForm
      categories={categories}
    />
  );
}

export default Page;

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

Next.js 목차로