Free tutorials & notes in Hindi & English · Clean code examples 🧰 मुफ़्त PDF और फ़ोटो टूल्स →
🟣 Data, Server और APIs  ·  Lesson 21

Route Handlers (API बनाएँ)

Route Handler क्या है?

Route Handler एक route.js नाम की file है जो page की जगह data (आमतौर पर JSON) लौटाती है। हर HTTP method के लिए function export करते हैं: GET, POST, PUT, PATCH, DELETE। इसी से आपकी Next.js site Android apps या दूसरी websites के लिए API बनती है।

page.jsx

  • HTML लौटाता है
  • Browser में इंसानों के लिए
  • URL: /courses

route.js

  • JSON / text / file लौटाता है
  • Apps और scripts के लिए
  • URL: /api/courses
Page vs Route Handler

GET /api/courses

JS – app/api/courses/route.js
// app/api/courses/route.js  (from the EduSite project)
import { searchCourses } from '@/lib/courses'

// GET /api/courses?q=python  →  JSON list of matching courses.
export async function GET(request) {
  const q = request.nextUrl.searchParams.get('q') || ''
  const data = searchCourses(q).map(({ slug, title, level, fee, duration }) =>
    ({ slug, title, level, fee, duration }))
  return Response.json({ count: data.length, courses: data })
}

Query strings: ?q=python

request.nextUrl.searchParams.get('q') query string पढ़ता है। Test कीजिए:

Terminal
$ curl "http://localhost:3000/api/courses?q=python" {"count":1,"courses":[{"slug":"python-ai","title":"Python + AI","level":"Beginner","fee":3499,"duration":"8 weeks"}]}

JSON body के साथ POST

JS – app/api/enquiries/route.js
// app/api/enquiries/route.js
import { NextResponse } from 'next/server'

const enquiries = []   // demo only – use a database in real apps

export async function GET() {
  return NextResponse.json(enquiries)
}

export async function POST(request) {
  let body
  try {
    body = await request.json()
  } catch {
    return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 })
  }

  const name = String(body.name || '').trim()
  const phone = String(body.phone || '').trim()
  if (name.length < 2 || !/^[6-9]\d{9}$/.test(phone)) {
    return NextResponse.json({ error: 'Name and a valid 10-digit mobile are required' }, { status: 422 })
  }

  const item = { id: enquiries.length + 1, name, phone, at: new Date().toISOString() }
  enquiries.push(item)
  return NextResponse.json(item, { status: 201 })   // 201 = Created
}
Terminal – POST test
$ curl -X POST http://localhost:3000/api/enquiries \ -H "Content-Type: application/json" \ -d '{"name":"Riya","phone":"9876543210"}' {"id":1,"name":"Riya","phone":"9876543210","at":"2026-10-19T09:12:44.120Z"} $ curl -X POST http://localhost:3000/api/enquiries -d '{"name":"R"}' {"error":"Name and a valid 10-digit mobile are required"} ← status 422

Dynamic API: /api/courses/[slug]

JS – app/api/courses/[slug]/route.js
// app/api/courses/[slug]/route.js
import { getCourse } from '@/lib/courses'

export async function GET(request, { params }) {
  const { slug } = await params              // params is a Promise here too
  const course = getCourse(slug)
  if (!course) {
    return Response.json({ error: 'Course not found' }, { status: 404 })
  }
  return Response.json(course)
}

Request → response flow

Android approute.jsDatabasePOST /api/enquiries {name, phone}input validateINSERT enquiryनई id201 Created {id: 1, ...}
एक typical API call

Status codes और errors

Codeमतलबकब use करें
200OKSuccessful GET
201CreatedPOST से record बना
400Bad RequestInvalid JSON / fields missing
401UnauthorizedLogin नहीं / गलत token
404Not FoundRecord मौजूद नहीं
422UnprocessableValidation fail
500Server ErrorUnexpected crash

Mobile apps के लिए headers और CORS

Native Android apps (Retrofit) को CORS नहीं चाहिए, पर दूसरी websites के JavaScript को चाहिए।

JS – CORS headers
// app/api/courses/route.js — allow any origin to read (public API)
const cors = {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
  'Access-Control-Allow-Headers': 'Content-Type, Authorization',
}

export async function OPTIONS() {               // browser "preflight" request
  return new Response(null, { status: 204, headers: cors })
}

export async function GET(request) {
  const data = { ok: true }
  return Response.json(data, { headers: { ...cors, 'Cache-Control': 'public, max-age=60' } })
}

API test करना

JS – API call करना
// From any JavaScript (browser console, another site, React Native):
const res = await fetch('https://your-site.com/api/courses?q=web')
const json = await res.json()
console.log(json.count, json.courses[0].title)

Browser में http://localhost:3000/api/courses खोल सकते हैं, या POST requests के लिए Postman / Thunder Client (VS Code extension) use करें।

आम गलतियाँ

  • route.js में export default function → named exports होने चाहिए (export async function GET)।
  • page.jsx के बगल में route.js → conflict।
  • { error } के साथ 200 लौटाना → apps failure detect नहीं कर पाते; सही status दें।
  • Validation के बिना input पर भरोसा → हमेशा server पर validate करें।

सारांश

  • route.js GET, POST… export करता है और Response.json() लौटाता है।
  • Query request.nextUrl.searchParams से, body await request.json() से, path await params से।
  • सही status codes use करें; CORS सिर्फ़ cross-site browser clients के लिए।
✅ Practice

/api/courses/[slug] और /api/enquiries (GET + POST) बनाइए। Valid और invalid phone number के साथ curl से POST test करके status codes check कीजिए।

अक्सर पूछे जाने वाले प्रश्न (FAQ)

क्या page.jsx और route.js एक ही folder में हो सकते हैं?
नहीं। Folder या तो page होता है या API endpoint। APIs को app/api/... में रखें ताकि अलग रहें।
क्या अपने forms के लिए Route Handlers चाहिए?
आमतौर पर नहीं। Next.js app के अंदर के forms के लिए Server Actions आसान हैं। Route Handlers external clients जैसे Android apps, webhooks या दूसरी websites के लिए हैं।
क्या GET route handlers cache होते हैं?
Default रूप से नहीं। Request पढ़ने वाला GET handler dynamic होता है। export const dynamic = 'force-static' से static output चुन सकते हैं।
← Next.js Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

अगला topicServer Actions और Forms आपकी प्रगति: 21 / 37 (57%) · Lesson 22 / 37 आगे बढ़ें →

यह lesson कैसा लगा?

आपकी राय से हम content और बेहतर बनाते हैं।

अपना review और सुझाव लिखें (वैकल्पिक)

Review approve होने के बाद आपका नाम और शहर इसके साथ public दिख सकते हैं। Email या phone न लिखें।

▶ CodingEasily on YouTube

Video से सीखें – आसान Hindi में

चुनी हुई video: RDBMS भाग 3 – Class XI Commerce IT

▶ Channel subscribe करें