🌐 Web Development

Server Actions

Server Actions

Next.js's server function call feature. Simplifies form submission and data mutation.

πŸ“– Detailed Explanation

Server Actions is a feature introduced in Next.js 13.4 that lets you call server functions directly from client components. It uses the 'use server' directive to mark a function so that it runs only on the server, and it allows data mutations without creating an API route.

The biggest advantage of Server Actions is the simplification of form handling. When you pass a server function directly to the action attribute of a form, it automatically supports Progressive Enhancement, which works even in environments where JavaScript is disabled.

Server Actions naturally integrate the RPC (Remote Procedure Call) pattern into React. Because server code is not included in the client bundle, security is strengthened, and database queries or external API calls can be defined in the same file as the component.

When used together with revalidatePath or revalidateTag, the cache can be automatically refreshed after a mutation. Combined with the useFormStatus and useFormState hooks, loading state display and optimistic updates can also be implemented.

πŸ’» Code Example

// app/actions.ts - Server Actions μ •μ˜
'use server';

import { revalidatePath } from 'next/cache';
import { redirect } from 'next/navigation';
import { z } from 'zod';
import { db } from '@/lib/db';

// μŠ€ν‚€λ§ˆ 검증
const PostSchema = z.object({
  title: z.string().min(1, '제λͺ©μ„ μž…λ ₯ν•˜μ„Έμš”'),
  content: z.string().min(10, 'λ‚΄μš©μ€ 10자 이상이어야 ν•©λ‹ˆλ‹€'),
});

// 폼 μƒνƒœ νƒ€μž…
type FormState = {
  errors?: { title?: string[]; content?: string[] };
  message?: string;
};

// κ²Œμ‹œκΈ€ 생성 Action
export async function createPost(
  prevState: FormState,
  formData: FormData
): Promise<FormState> {
  // μœ νš¨μ„± 검사
  const validatedFields = PostSchema.safeParse({
    title: formData.get('title'),
    content: formData.get('content'),
  });

  if (!validatedFields.success) {
    return {
      errors: validatedFields.error.flatten().fieldErrors,
      message: 'μž…λ ₯값을 ν™•μΈν•΄μ£Όμ„Έμš”.',
    };
  }

  try {
    await db.post.create({
      data: validatedFields.data,
    });
  } catch (error) {
    return { message: 'κ²Œμ‹œκΈ€ μž‘μ„±μ— μ‹€νŒ¨ν–ˆμŠ΅λ‹ˆλ‹€.' };
  }

  revalidatePath('/posts');
  redirect('/posts');
}

// μ‚­μ œ Action
export async function deletePost(id: string) {
  await db.post.delete({ where: { id } });
  revalidatePath('/posts');
}

// app/posts/new/page.tsx - 폼 μ»΄ν¬λ„ŒνŠΈ
'use client';

import { useFormState, useFormStatus } from 'react-dom';
import { createPost } from '../actions';

function SubmitButton() {
  const { pending } = useFormStatus();
  return (
    <button type="submit" disabled={pending}>
      {pending ? 'μ €μž₯ 쀑...' : 'κ²Œμ‹œν•˜κΈ°'}
    </button>
  );
}

export default function NewPostForm() {
  const [state, formAction] = useFormState(createPost, {});

  return (
    <form action={formAction}>
      <input name="title" placeholder="제λͺ©" />
      {state.errors?.title && <p>{state.errors.title[0]}</p>}

      <textarea name="content" placeholder="λ‚΄μš©" />
      {state.errors?.content && <p>{state.errors.content[0]}</p>}

      <SubmitButton />
      {state.message && <p>{state.message}</p>}
    </form>
  );
}

πŸ—£οΈ Examples of Practical Conversations

In a technical meeting:

"You don't need to create a separate API route for form submission. With Server Actions, you can define a server function right in the component file. Types are shared automatically too."

In a technical interview:

"What are the security advantages of Server Actions?" - "'use server' functions are not included in the client bundle. They run only on the server, so DB connection information and API keys are not exposed."

In a code review:

"If you throw an error in a Server Action, the error message is exposed to the client as is. Switch to a pattern that returns an error object, and only log sensitive information."

Take a mock interview on this topic β†’ WIA SOOM AI Interview Β· Start for free

⚠️ Cautions

πŸ”— Related Terms

React Server Components Next.js Form Validation REST API Progressive Enhancement

πŸ“š Learn More

πŸ“„ Next.js Official Documentation - Server Actions and Mutations πŸ“„ React Official Documentation - 'use server' πŸ“„ Next.js - Forms and Mutations