Next.js Route Handlers — Building API Endpoints with route.ts

▲ Next.js 15+ (App Router) 🟢 Chapter 22 of 43 📂 Phase 10: Route Handlers & Backend 📅 2026 Edition
📌 Covered in this chapter: route.ts Basics · GET/POST/PUT/DELETE · Request & Response Objects · Query Parameters · Headers & Cookies · Status Codes
Server Actions forms కోసం best, kani external clients (mobile apps, third-party integrations) కి public REST API కావాలంటే Route Handlers అవసరం. Ee chapter lో API endpoints ela build cheయాలో nerchukుందాం.
1Creating Your First Route Handler

app/api/ folder లోపల, route.ts ఫైల్ create చేస్తే, ఆ path ఒక API endpoint అవుతుంది — page.tsx లాగానే, kani UI బదులు JSON return చేస్తుంది:

💻 Example 1: A Simple GET Endpoint
app/api/courses/route.ts ▶ Run in Compiler
import { NextResponse } from "next/server";

export async function GET() {
  return NextResponse.json({
    courses: ["JavaScript", "React", "Next.js"],
  });
}

Ee endpoint /api/courses కి request వస్తే, JSON response return అవుతుంది.

2Handling POST Requests with a Body
💻 Example 2: Creating a Resource via POST
app/api/courses/route.ts ▶ Run in Compiler
import { NextRequest, NextResponse } from "next/server";

export async function POST(request: NextRequest) {
  const body = await request.json();

  if (!body.name) {
    return NextResponse.json({ error: "Name is required" }, { status: 400 });
  }

  // ... save to database here
  return NextResponse.json({ message: "Course created", course: body }, { status: 201 });
}
🔍 Breakdown:
  • await request.json(): Incoming request body ni parse చేస్తుంది.
  • {"{"}status: 400{"}"}: HTTP status code — 400 (Bad Request), 201 (Created) లాంటివి explicitly set చేయవచ్చు.
3Reading Query Parameters
💻 Example 3: Filtering with ?category=
app/api/courses/route.ts ▶ Run in Compiler
import { NextRequest, NextResponse } from "next/server";

export async function GET(request: NextRequest) {
  const category = request.nextUrl.searchParams.get("category");
  return NextResponse.json({ filteredBy: category });
}

URL /api/courses?category=web అయితే, category variable value "web" అవుతుంది.

4Supported HTTP Methods
Function NameHTTP MethodTypical Use
GETGETReading/fetching data
POSTPOSTCreating a new resource
PUTPUTFull update of a resource
PATCHPATCHPartial update of a resource
DELETEDELETEDeleting a resource

Same route.ts file లో, prathi HTTP method కోసం, ఆ method పేరుతో ఒక export function rాస్తే chాలు — Next.js automatic గా correct one call చేస్తుంది.

⚠️ Common Mistake: Forgetting Status Codes

NextResponse.json() ki status code specify చేయకపోతే, default గా 200 (success) వస్తుంది — even for errors. Client-side code కి error ని correctly identify చేయడానికి, ఎప్పుడూ appropriate status code (400, 401, 404, 500) set చేయాలి.

💻 Hands-on Interactive Practice Challenge

Create a DELETE route handler for /api/courses/[id] that returns a success message with the deleted id.

app/api/courses/[id]/route.ts ▶ Run in Compiler
import { NextRequest, NextResponse } from "next/server";

export async function DELETE(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const { id } = await params;
  // ... delete from database here
  return NextResponse.json({ message: `Course ${id} deleted` });
}
Run This Challenge in Online Node.js IDE →
Frequently Asked Questions (FAQ)

Q Route Handlers, Server Actions కంటే ఎప్పుడు better?

External clients (mobile app, third-party webhook, public API) కి access కావాలంటే Route Handlers అవసరం. Internal forms/mutations కోసం matrame అయితే Server Actions simpler.

Q route.ts, page.tsx ఒకే folder లో ఉండొచ్చా?

Ledు — same route segment లో రెండూ ఉండలేవు. ఒక folder ki page.tsx (UI) leda route.ts (API) matrame ఉండాలి, రెండూ కాదు.

Q Route Handler లో database directly access చేయవచ్చా?

Avunు, Server Component లాగానే, Route Handlers ఎప్పుడూ server meedha run అవుతాయి కాబట్టి, database, secret keys safe గా వాడొచ్చు.

OC
Written by Our Compiler Technical Editorial Team
Reviewed for accuracy & tested on Next.js 15+ (App Router) · Last updated August 2026