MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
API Route Handlers (route.ts): Building RESTful Microservices0%
Study Materials
Next.js 15Progress 0%
1.1Next.js 15 Overview & App Router vs Pages Router Architecture1.2Core File Conventions: page.tsx, layout.tsx, template.tsx & not-found.tsx1.3Dynamic Routes ([id]), Catch-All Routes ([...slug]) & Route Groups ((group))1.4Streaming UI with loading.tsx and Suspense Boundaries
4.1API Route Handlers (route.ts): Building RESTful Microservices4.2Middleware.ts: Route Protection, Redirects, Cookies & Geolocation4.3Authentication with NextAuth / Auth.js & JWT Session Management4.4Metadata API: Dynamic SEO, OpenGraph Tags & Sitemap Generation4.5Production Optimization, Dockerization & Vercel Cloud Deployment
HomeTutorialsNext.js 15API Route Handlers (route.ts): Building RESTful Microservices
Middleware.ts: Route Protection, Redirects, Cookies & Geolocation

API Route Handlers (route.ts): Building RESTful Microservices

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

While Server Components and Server Actions handle most internal data fetching and mutations, modern full-stack web applications frequently need to expose public RESTful endpoints for third-party integrations, mobile applications, webhooks (e.g., Stripe, Razorpay), or external microservices. Next.js provides Route Handlers via route.ts files.


1. Route Handler Conventions

  • Created inside the app/ directory as route.ts (or route.js).
  • Conflict Rule: A route.ts and a page.tsx CANNOT exist at the same URL segment level!
  • Handlers export named functions corresponding to standard HTTP verbs: GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS.
1app/
2 └── api/
3 ├── courses/
4 │ └── route.ts # GET /api/courses, POST /api/courses
5 └── webhooks/
6 └── stripe/
7 └── route.ts # POST /api/webhooks/stripe

2. Implementing RESTful Handlers: GET & POST

1// app/api/courses/route.ts
2import { NextRequest, NextResponse } from 'next/server';
3import dbConnect from '@/lib/dbConnect';
4import Course from '@/models/Course';
5 
6// GET: /api/courses?category=web
7export async function GET(request: NextRequest) {
8 await dbConnect();
9 
10 const searchParams = request.nextUrl.searchParams;
11 const category = searchParams.get('category');
12 
13 const filter = category ? { category, isPublished: true } : { isPublished: true };
14 const courses = await Course.find(filter).lean();
15 
16 return NextResponse.json({
17 status: 'success',
18 results: courses.length,
19 data: courses
20 });
21}
22 
23// POST: /api/courses
24export async function POST(request: NextRequest) {
25 try {
26 await dbConnect();
27 const body = await request.json();
28 
29 if (!body.title || !body.price) {
30 return NextResponse.json(
31 { error: 'Missing required fields: title, price' },
32 { status: 400 }
33 );
34 }
35 
36 const newCourse = await Course.create(body);
37 
38 return NextResponse.json(
39 { message: 'Course created successfully', data: newCourse },
40 { status: 201 }
41 );
42 } catch (error: any) {
43 return NextResponse.json({ error: error.message }, { status: 500 });
44 }
45}

3. Dynamic Route Handlers with Parameters

1// app/api/courses/[id]/route.ts
2import { NextRequest, NextResponse } from 'next/server';
3import dbConnect from '@/lib/dbConnect';
4import Course from '@/models/Course';
5 
6export async function DELETE(
7 request: NextRequest,
8 { params }: { params: Promise<{ id: string }> }
9) {
10 await dbConnect();
11 const { id } = await params;
12 
13 const deleted = await Course.findByIdAndDelete(id);
14 
15 if (!deleted) {
16 return NextResponse.json({ error: 'Course not found' }, { status: 404 });
17 }
18 
19 return new NextResponse(null, { status: 204 }); // 204 No Content
20}

Interactive Quiz• Knowledge Check

Multiple Choice Questions

Question 1
What special file name is used in the Next.js App Router to create API endpoints?
Question 2
Can a page.tsx and a route.ts exist within the exact same directory (e.g. app/api/users/)?
Question 3
How do you extract query string parameters from an incoming NextRequest in a Route Handler?
Question 4
Which utility is standard in Next.js for sending JSON responses with the correct headers and status codes?
Question 5
Why are Route Handlers ideal for implementing payment provider webhooks (e.g. Stripe, Razorpay)?

Next Lesson

Middleware.ts: Route Protection, Redirects, Cookies & Geolocation

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Optimistic UI Updates with React useOptimistic HookMiddleware.ts: Route Protection, Redirects, Cookies & Geolocation

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master Next.js 15 with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext