Skip to content
BackendChapter 19 / 34Intermediate5 min read

Route Handlers (API)

Next.js route handlers se app/api mein REST API banana seekhein, Web Request aur Response, dynamic params, auth check aur caching ke saath.

On this page

1. Route Handlers kya hain?

Pages Router mein isay API Routes kehte the. App Router mein app folder ke andar kahin bhi route.ts bana kar API endpoint ban jata hai, jaise app/api/products/route.ts se /api/products.

Route Handler koi UI render nahi karta. Yeh JSON, text, file ya redirect wapas karta hai.

2. Kyun zaroori hai?

Server Actions sirf aapki apni app ke forms ke liye hain. Lekin kabhi bahar ki duniya ko bhi aapke server se baat karni hoti hai: mobile app, webhook, doosri website.

Server ActionRoute Handler
Sirf apni Next.js app se callKoi bhi client call kar sakta hai
POST only, URL hiddenGET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS
Form aur mutation ke liyePublic API, webhooks, file downloads
Response UI update hota haiResponse JSON ya koi bhi format

3. Kahan use hota hai?

Use caseExample route
Mobile app ke liye APIapp/api/products/route.ts
Stripe ya CMS webhookapp/api/webhooks/stripe/route.ts
File download ya CSV exportapp/api/reports/route.ts
OAuth callbackapp/api/auth/callback/route.ts
RSS feedapp/feed.xml/route.ts

4. Kaise kaam karta hai?

Route Handler ka flow
Client HTTP request bhejta hai
Next.js URL se route.ts dhoondta hai
Method ke naam wala function chalta hai
Auth check + validation + kaam
Response.json wapas

Kuch zaroori rules:

RuleDetail
File naamHamesha route.ts ya route.js
ConflictEk hi segment mein page.tsx aur route.ts dono nahi ho sakte
Unknown methodNext.js khud 405 Method Not Allowed deta hai
CachingBy default koi caching nahi, har request par chalta hai
Paramsctx.params ek Promise hai, await karna zaroori

5. Code example

Example 1: List aur create

ts
import { db } from "@/lib/db";
import { getSession } from "@/lib/dal";

export async function GET(request: Request) {
  const { searchParams } = new URL(request.url);
  const category = searchParams.get("category") ?? undefined;

  const products = await db.product.findMany({ where: { category } });
  return Response.json(products);
}

export async function POST(request: Request) {
  const session = await getSession();
  if (!session) {
    return Response.json({ error: "Login karein" }, { status: 401 });
  }

  const body = await request.json();
  const product = await db.product.create({ data: { name: String(body.name) } });
  return Response.json(product, { status: 201 });
}

Example 2: Dynamic segment app/api/products/[id]/route.ts

ts
import type { NextRequest } from "next/server";
import { db } from "@/lib/db";

export async function GET(_request: NextRequest, ctx: RouteContext<"/api/products/[id]">) {
  const { id } = await ctx.params;
  const product = await db.product.findUnique({ where: { id } });

  if (!product) {
    return Response.json({ error: "Product nahi mila" }, { status: 404 });
  }

  return Response.json(product);
}

Code kaise kaam kar raha hai?

CheezMatlab
export async function GETGET /api/products is function ko chalata hai
new URL(request.url)Query string parhne ka standard tareeqa
request.json()POST body ko JSON mein parse
Response.json(data, { status })JSON response, status code ke saath
RouteContext<"/api/products/[id]">Next.js ka global type helper, params typed
await ctx.paramsNext.js 16 mein params async hain

Cache Components on hon to static GET handler prerender ho sakta hai. Data cache karna ho to "use cache" handler ke andar nahi, ek alag helper function mein lagayein.

Interview tip

"Server Action ya Route Handler?" Jawab: apni app ke forms aur mutations ke liye Server Action, bahar ke clients, webhooks aur non-HTML responses ke liye Route Handler.

6. Common mistakes

Galati: Same folder mein page.tsx aur route.ts dono rakhna

Why? Dono ek hi URL claim karte hain, Next.js conflict error deta hai.

Behtar: API ko alag segment mein rakho, jaise app/api/... ke andar.

Galati: Apne hi Server Component se apni API ko fetch karna

Why? Extra network hop lagta hai aur production build mein URL issues aate hain.

Behtar: Server Component mein seedha database ya service function call karo.

Galati: Route Handler ko protected samajhna kyun ke UI mein link nahi

Why? Har route.ts ek public URL hai, koi bhi curl se hit kar sakta hai.

Behtar: Har handler mein session aur role check karo, 401 ya 403 return karo.

Galati: Request body validate kiye baghair use karna

Why? Galat type ya missing fields database error ya security bug bana dete hain.

Behtar: Zod schema se body ko safeParse karo aur 400 return karo agar fail ho.

7. Pehle aur baad mein kya seekhein?

Final quick revision

PointDetail
Fileapp/api/.../route.ts
FunctionsGET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS
InputWeb Request ya NextRequest
OutputResponse.json(data, { status })
Paramsawait ctx.params
SecurityHar handler mein auth check