Next.js Server Actions: Interview Deep Dive
N نکست.جی‌اس

Next.js Server Actions: Interview Deep Dive

Mutate data from forms and components without manual API routes — security and patterns included.

BugCast Admin··۵ دقیقه مطالعه

Server Actions are async functions marked with 'use server' that run on the server and can be called from Client or Server Components — Next.js's answer to form mutations.

Common Interview Questions

Q: Define a Server Action

Answer: Place 'use server' at file or function level. Actions receive FormData or serializable arguments.


"use server";

export async function createPost(formData: FormData) {
  const title = formData.get("title");
  await db.post.create({ data: { title: String(title) } });
  revalidatePath("/posts");
}

Q: Call from a form?

Answer: Pass action to form action prop for progressive enhancement — works without JavaScript.


<form action={createPost}>
  <input name="title" />
  <button type="submit">Create</button>
</form>

Q: Security considerations?

Answer: Always authenticate and authorize inside the action. Never trust client input. Actions are POST endpoints — validate CSRF protection (Next.js handles for same-origin).

Q: useFormState / useActionState?

Answer: Hook for action return values and pending state in Client Components — show validation errors without manual fetch boilerplate.

Key Points for Interviews

  • Colocate mutations with UI

  • Works with forms and programmatic calls

  • Revalidate cache after mutations

  • Validate on server always

  • Alternative to REST for internal app mutations

#server-actions#mutations#interview

مطالب مرتبط