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
GET /api/courses
// 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 कीजिए:
JSON body के साथ POST
// 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
}Dynamic API: /api/courses/[slug]
// 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
Status codes और errors
| Code | मतलब | कब use करें |
|---|---|---|
| 200 | OK | Successful GET |
| 201 | Created | POST से record बना |
| 400 | Bad Request | Invalid JSON / fields missing |
| 401 | Unauthorized | Login नहीं / गलत token |
| 404 | Not Found | Record मौजूद नहीं |
| 422 | Unprocessable | Validation fail |
| 500 | Server Error | Unexpected crash |
Mobile apps के लिए headers और CORS
Native Android apps (Retrofit) को CORS नहीं चाहिए, पर दूसरी websites के JavaScript को चाहिए।
// 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 करना
// 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.jsGET,POST… export करता है औरResponse.json()लौटाता है।- Query
request.nextUrl.searchParamsसे, bodyawait request.json()से, pathawait paramsसे। - सही status codes use करें; CORS सिर्फ़ cross-site browser clients के लिए।
/api/courses/[slug] और /api/enquiries (GET + POST) बनाइए। Valid और invalid phone number के साथ curl से POST test करके status codes check कीजिए।
