Next.js Developer interview question · Most asked

What are Server Actions and how do you use them for mutations?

Summary

Server Actions are async functions marked with 'use server' that run on the server and can be called from forms (<form action={createPost}>) or Client Components. Next.js handles the network request, and the action can revalidate caches and redirect.

Longer Answer

They remove the need for separate API routes for many mutations and work with progressive enhancement (forms submit before JS loads). Use useActionState (React 19) for pending state and returned errors, and useFormStatus for submit button state. Security: every Server Action is a public HTTP endpoint, so always validate input (e.g., with Zod) and check authentication/authorization inside the action.

Code Example

// app/posts/actions.ts
"use server";
import { z } from "zod";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";

const PostSchema = z.object({ title: z.string().min(3), body: z.string().min(10) });

export async function createPost(prevState: unknown, formData: FormData) {
  const session = await auth();
  if (!session) return { error: "Not signed in" };

  const parsed = PostSchema.safeParse(Object.fromEntries(formData));
  if (!parsed.success) return { error: parsed.error.flatten().fieldErrors };

  const post = await db.post.create({ data: { ...parsed.data, authorId: session.user.id } });
  revalidatePath("/posts");
  redirect(`/posts/${post.id}`);
}

Key Points

  • 'use server' functions callable from forms/clients
  • Revalidate with revalidatePath/revalidateTag
  • useActionState / useFormStatus for UX
  • Treat as public endpoints: validate and authorize

Explanation

Common mistakes

  • Skipping auth checks because the button is only shown to admins
  • Trusting hidden form fields like userId

More most-asked Next.js Developer questions

← All Next.js Developer questions