Skip to content
Data & CachingChapter 17 / 34Intermediate5 min read

Server Actions

Next.js server actions kya hain, use server directive se forms aur mutations server par kaise chalate hain, auth check aur revalidation ke saath.

On this page

1. Server Actions kya hain?

Pehle data save karne ke liye aap API route banate, phir client se fetch("/api/...") karte. Server Actions mein aap function likhte hain, aur Next.js khud uske liye ek secure POST endpoint bana deta hai.

React ki zubaan mein inhein Server Functions kehte hain. Jab yeh form action ya mutation ke liye use hon to Next.js inhein Server Actions kehta hai.

2. Kyun zaroori hai?

API route + client fetchServer Action
Alag API file aur alag client codeEk function, seedha form se call
JSON body banana aur parse karnaFormData khud milta hai
Loading state manuallyuseActionState se pending milta hai
JavaScript load hone se pehle form kaam nahi kartaProgressive enhancement, bina JS bhi submit
Cache refresh alag seupdateTag ya revalidatePath usi function mein

3. Kahan use hota hai?

Use caseAction kya karta hai
Create postDatabase mein row insert, phir redirect
Like buttonCount update, phir updateTag
Profile settingsForm data validate aur save
Delete itemAuth check, delete, list refresh
LogoutSession cookie delete

4. Kaise kaam karta hai?

Server Action ka flow
User form submit karta hai
Browser POST request bhejta hai
Next.js sahi Server Action dhoondta hai
Action server par chalta hai
Database update + cache invalidate
Updated UI ek hi round trip mein wapas

"use server" do jagah likh sakte hain:

JagahAsar
File ki pehli lineFile ke saare exports Server Actions ban jate hain, Client Components inhein import kar sakte hain
Async function body ki pehli lineSirf woh function Server Action, Server Component ke andar inline

5. Code example

Example 1: Actions file

ts
"use server";

import { updateTag } from "next/cache";
import { redirect } from "next/navigation";
import { db } from "@/lib/db";
import { verifySession } from "@/lib/dal";

export async function createTodo(formData: FormData) {
  const session = await verifySession();
  const title = String(formData.get("title") ?? "").trim();

  if (!title) {
    return;
  }

  await db.todo.create({ data: { title, userId: session.userId } });
  updateTag("todos");
  redirect("/todos");
}

export async function deleteTodo(id: string) {
  const session = await verifySession();
  await db.todo.delete({ where: { id, userId: session.userId } });
  updateTag("todos");
}

Example 2: Form aur button se call karna

tsx
import { createTodo, deleteTodo } from "./actions";

export default function TodoPage() {
  return (
    <main>
      <form action={createTodo}>
        <input name="title" placeholder="Naya kaam" required />
        <button type="submit">Add</button>
      </form>

      <form action={deleteTodo.bind(null, "todo_123")}>
        <button type="submit">Delete</button>
      </form>
    </main>
  );
}

Code kaise kaam kar raha hai?

CheezMatlab
"use server" file top parSaare exported functions Server Actions
verifySession()Har action mein pehle user ki pehchan
formData.get("title")Input ka name attribute se value
updateTag("todos")User ko fauran nayi list dikhe
redirect("/todos")Kaam ke baad doosre page par bhejo
deleteTodo.bind(null, id)Extra argument pass karne ka tareeqa

Pending state aur validation errors dikhane ke liye useActionState use hota hai. Yeh detail Forms & Validation chapter mein hai.

Interview tip

"Server Actions secure kyun hain?" ka sahi jawab: woh khud se secure nahi hain. Har action ek POST endpoint hai, is liye andar authentication, authorization aur input validation zaroori hai.

6. Common mistakes

Galati: Action ke andar auth check na karna

Why? Agar button UI mein chhupa bhi ho, koi bhi request bana kar action call kar sakta hai.

Behtar: Har action ke shuru mein session verify karo aur ownership check karo.

Galati: FormData ko bina validation database mein dalna

Why? User kuch bhi bhej sakta hai, galat ya khatarnak data save ho jata hai.

Behtar: Zod jaisi library se schema bana kar safeParse karo.

Galati: Data padhne ke liye Server Action use karna

Why? Actions mutations ke liye hain, yeh sequentially chalte hain aur cache nahi hote.

Behtar: Data reading Server Components mein karo, actions sirf likhne ke liye.

Galati: redirect ko try catch ke andar rakhna

Why? redirect ek special error throw karta hai, catch use pakar leta hai aur redirect nahi hota.

Behtar: redirect ko try catch ke bahar, kaam mukammal hone ke baad call karo.

7. Pehle aur baad mein kya seekhein?

Final quick revision

PointDetail
Directive"use server" file ya function level par
Call kaise<form action={fn}> ya event handler se
InputFormData
SecurityHar action mein auth + validation
Baad ka kaamupdateTag, revalidatePath, redirect