Next.js Route Handlers Explained 🀯 GET POST PUT DELETE #18 || Next.js Anatomy || DeathCode - DeathCode

🚦 Route Handlers Deep Dive

The Actual Backend Entry Point in Next.js 16


Route Handlers Kya Hote Hain?

App Router ke andar backend functionality ka primary entry point Route Handlers hote hain.

Jab browser, mobile app, third-party service ya koi frontend component HTTP request bhejta hai, to Next.js us request ko receive karne aur process karne ke liye Route Handlers ka use karta hai.

Simple words mein:

Route Handler ek special file hoti hai jo incoming HTTP requests ko receive karke response return karti hai.

Agar Server Components ko Next.js backend ka rendering layer maana jaaye, to Route Handlers us backend ka API layer hain.


Route Handlers Ka Place App Router Mein

Route Handlers sirf App Router ke andar kaam karte hain.

Structure:

app
 └── api
      └── users
           └── route.js

Automatically endpoint create ho jaata hai:

/api/users

Koi manual router configuration karne ki zarurat nahi hoti.


Why Does This Work?

Kyuki App Router ka routing system file-system based hai.

Yani:

Folder Structure
=
URL Structure

Next.js folder hierarchy ko read karta hai aur uske basis par routes generate karta hai.


Folder β†’ URL Mapping

Example:

app
 └── api
      └── users
           └── route.js

URL:

/api/users

Example:

app
 └── api
      └── posts
           └── route.js

URL:

/api/posts

Example:

app
 └── api
      └── products
           └── featured
                └── route.js

URL:

/api/products/featured

Mental Model

Think:

Folder
  ↓
URL Segment
  ↓
route.js
  ↓
API Endpoint

Exactly wahi rule jo pages ke liye use hota hai, APIs ke liye bhi apply hota hai.


Your First Route Handler

Create:

app
 └── api
      └── users
           └── route.js

Code:

export async function GET() {
  return NextResponse.json({
    success: true,
    message: "Users API Working"
  });
}

Open:

http://localhost:3000/api/users

Response:

{
  "success": true,
  "message": "Users API Working"
}

Yahi aapki pehli Next.js backend API hai.


Route Handlers & HTTP Methods

HTTP request sirf URL se define nahi hoti.

Har request ke saath ek method bhi hoti hai.

Example:

GET    /api/users
POST   /api/users
DELETE /api/users

URL same hai.

Behavior different hai.

Isi wajah se Route Handler file multiple HTTP methods support karti hai.


GET Method

Purpose:

Data Read Karna

Example:

export async function GET() {
  return NextResponse.json({
    users: [
      {
        id: 1,
        name: "DeathCode"
      }
    ]
  });
}

REST Mindset

GET requests ideally:

βœ… Safe hoti hain

βœ… Data read karti hain

❌ Database modify nahi karti


POST Method

Purpose:

Naya Resource Create Karna

Example:

export async function POST() {
  return NextResponse.json({
    success: true,
    message: "User Created"
  });
}

Use cases:

  • Registration
  • Create User
  • Create Post
  • Upload Data

PUT Method

Purpose:

Existing Resource Ko Completely Replace Karna

Example:

export async function PUT() {
  return NextResponse.json({
    success: true,
    message: "User Updated"
  });
}

Thinking

PUT ka meaning:

Purani Resource Hatao
Aur Nayi Resource Se Replace Karo

PATCH Method

Purpose:

Partial Update

Example:

export async function PATCH() {
  return NextResponse.json({
    success: true,
    message: "User Partially Updated"
  });
}

Difference:

PUT

Full Replacement

PATCH

Partial Modification

Example:

Current User:

{
  "name": "DeathCode",
  "age": 25,
  "city": "Delhi"
}

PATCH:

{
  "city": "Mumbai"
}

Sirf city update hogi.

Baaki fields same rahengi.


DELETE Method

Purpose:

Resource Remove Karna

Example:

export async function DELETE() {
  return NextResponse.json({
    success: true,
    message: "User Deleted"
  });
}

Use Cases:

  • Delete User
  • Delete Product
  • Delete Blog Post

HEAD Method

HEAD GET jaisa hi hota hai.

Difference:

Response Body Nahi Hoti

Sirf headers return kiye jaate hain.

Example:

export async function HEAD() {
  return new NextResponse(null, {
    status: 200
  });
}

Common Use Cases:

  • Monitoring Systems
  • Health Checks
  • Crawlers
  • Availability Checks

OPTIONS Method

Purpose:

Client ko batana:

Kaunse HTTP Methods Supported Hain

Example:

export async function OPTIONS() {
  return new NextResponse(null, {
    headers: {
      Allow: "GET, POST, PUT, PATCH, DELETE"
    }
  });
}

Mostly useful in:

  • CORS
  • API Discovery
  • Browser Preflight Requests

One File, Multiple Methods

Ek hi route file multiple methods handle kar sakti hai.

Example:

export async function GET() {}
 
export async function POST() {}
 
export async function PUT() {}
 
export async function PATCH() {}
 
export async function DELETE() {}

Question:

Kaunsa function execute hoga?

Answer:

Request method decide karegi.


Example:

GET /api/users

↓

GET()

Execute hoga.


Example:

POST /api/users

↓

POST()

Execute hoga.


Restaurant Analogy

Same counter.

Different requests.

Customer bolta hai:

Order Place Karna Hai

↓

POST


Customer bolta hai:

Menu Dekhna Hai

↓

GET


Counter same hai.

Action different hai.


Dynamic API Routes

Real-world APIs mein static routes kaafi nahi hote.

Example:

/api/users/1
/api/users/25
/api/users/999

Har user ke liye alag folder banana impossible hai.

Solution:

Dynamic Segments.


Structure:

app
 └── api
      └── users
           └── [id]
                └── route.js

URLs:

/api/users/1
/api/users/25
/api/users/99

Sab same route handler use karenge.


Route Params in Next.js 16

URL:

/api/users/99

Code:

export async function GET(request, { params }) {
  const { id } = await params;
 
  return NextResponse.json({
    userId: id
  });
}

Response:

{
  "userId": "99"
}

Important Next.js 16 Change

Route params asynchronous hain.

Isliye:

await params

use karna required hai.


Search Params

Route params aur query params alag concepts hain.

Example:

/api/users?page=2&limit=10

Code:

export async function GET(request) {
  const searchParams = request.nextUrl.searchParams;
 
  const page = searchParams.get("page");
  const limit = searchParams.get("limit");
 
  return NextResponse.json({
    page,
    limit
  });
}

Response:

{
  "page": "2",
  "limit": "10"
}

Route Params vs Search Params

Feature Route Params Search Params
URL /users/99 /users?page=2
Purpose Resource Identify Karna Filtering / Pagination
Source Folder Structure Query String
SEO Impact High Low

Mental Model

Route Params:

Ye Kis User Ki Baat Ho Rahi Hai?

Search Params:

Us User Data Ko Kaise Dikhana Hai?

Nested Route Handlers

Structure:

app
 └── api
      └── users
           └── profile
                └── route.js

URL:

/api/users/profile

Structure:

app
 └── api
      └── products
           └── featured
                └── route.js

URL:

/api/products/featured

Folder hierarchy naturally API hierarchy create karti hai.


REST API Design Mindset

Professional APIs generally predictable structure follow karti hain.

Example:

GET    /users
GET    /users/1
 
POST   /users
 
PUT    /users/1
PATCH  /users/1
 
DELETE /users/1

Benefits:

βœ… Predictable

βœ… Easy to maintain

βœ… Easy to document

βœ… Easy for frontend developers


Express vs Next.js Routing

Express

app.get("/users", handler);
app.post("/users", handler);

Manual route registration.


Next.js

app/api/users/route.js

File-system routing.


Key Difference

Express:

Code Defines Route

Next.js:

Folder Defines Route

Common Beginner Mistakes

Mistake 1

Creating APIs inside:

page.js

Wrong.

API logic belongs in:

route.js

Mistake 2

Incorrect folder placement.

app/users/route.js

instead of

app/api/users/route.js

Mistake 3

Forgetting:

await params

in Next.js 16.


Mistake 4

Confusing:

/users/99

with

/users?id=99

These are different concepts.


Request Lifecycle Mental Model

Whenever a request arrives:

Request Arrives
        ↓
URL Matched
        ↓
Route Handler Found
        ↓
Method Selected
        ↓
Function Executed
        ↓
Response Returned

Ye hi poore Next.js backend ka foundation hai.

Aage:

  • Authentication
  • MongoDB
  • File Uploads
  • Cookies
  • Sessions
  • Server Actions
  • External APIs

Sab isi Route Handler system ke upar build hote hain.


Final Mental Model

Route Handler ko Express ke route callback ki tarah mat socho.

Isse Next.js backend ke entry gate ki tarah socho.

Incoming Request
        ↓
Route Handler
        ↓
Business Logic
        ↓
Response

Agar App Router frontend ka heart hai,

to Route Handlers App Router backend ki backbone hain.

Β© 2024 DeathCode. All Rights Reserved.