C.W.K.
Stream
Lesson 01 of 08 · published

Server Action 이란?

~20 min · Server Action, use server, mutations

Level 0Curious
0 XP0/68 lessons0/11 achievements
0/120 XP to next level120 XP to go0% complete

Server Action = mutation endpoint, inline 선언

Server Action 은 server 에서 도는 async function 인데 Client Component 에서 callable. Framework 가 unique POST endpoint 로 뒤에서 wiring — API 처럼 부르는 게 아니라 function 처럼.

선언 두 방법

접근방법
File-levelFile 위에 'use server'. 그 file 의 모든 export 가 action.
InlineServer Component 안에 function 정의 + 그 body 위에 'use server'.

대체하는 것

내부 CRUD 위해서는 더 이상 /api/…/route.ts + fetch() + 양쪽 JSON parse 안 필요. Server Action 이 built-in CSRF protection, encrypted action ID, unused action 자동 dead-code elimination 가진 POST endpoint.

대체 안 하는 것

Public API (third party 가 부름), webhook, integration, stable URL 노출 필요한 거 — Route Handler 가 owning (다음 track).

Code

File-level action module·ts
// app/actions.ts
'use server';
import { revalidatePath } from 'next/cache';
import { db } from '@/lib/db';

export async function createPost(formData: FormData) {
  const title = formData.get('title') as string;
  const content = formData.get('content') as string;
  await db.post.create({ data: { title, content } });
  revalidatePath('/posts');
}
Server Component 안 inline action·tsx
// app/page.tsx
export default function Page() {
  async function handleSubmit(formData: FormData) {
    'use server';
    await db.post.create({ data: { title: formData.get('title') as string } });
  }
  return (
    <form action={handleSubmit}>
      <input name="title" required />
      <button>Create</button>
    </form>
  );
}

External links

Exercise

Project 의 POST /api/…/route.ts CRUD endpoint 하나를 Server Action 으로 교체. Form 여전히 작동하고 (그 endpoint 의 URL surface 가 사라진다는 거) 보여줘.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.