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/useFormStatusfor 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
- How does data fetching work in the App Router?
- How did caching defaults change in Next.js 15?
- What happens, step by step, when a request reaches a Next.js App Router application?
- What is Next.js and what problems does it solve on top of React?
- What are the differences between the App Router and the Pages Router?
- What is the difference between Server Components and Client Components?
- Explain the App Router file conventions: page, layout, loading, error, not-found, template and route.
- Explain SSR, SSG, ISR and CSR in Next.js.