Menu

Route Handlers (API Endpoints)

Lesson 5: Route Handlers (API Endpoints)

What is a Route Handler?

A Route Handler is a file named route.ts that responds to HTTP requests using the Web Request and Response APIs. It is the App Router's way of building API endpoints.

Use Route Handlers for Prefer something else for
Public APIs used by mobile apps or third parties Fetching data for your own pages (fetch in Server Components)
Webhooks from payment or email providers Form submissions from your own UI (Server Actions, Module 6)
Endpoints for client-side fetching (SWR) –
Files, RSS feeds, or custom responses –

Example

// app/api/courses/route.ts
import { NextResponse, type NextRequest } from 'next/server';
import { getPublishedCourses, createCourse } from '@/lib/data/courses';

export async function GET(request: NextRequest) {
  const level = request.nextUrl.searchParams.get('level');
  const courses = await getPublishedCourses();
  const filtered = level ? courses.filter((c) => c.level === level) : courses;
  return NextResponse.json(filtered);
}

export async function POST(request: NextRequest) {
  const body = await request.json();
  if (!body.title) {
    return NextResponse.json({ error: 'Title is required' }, { status: 400 });
  }
  const course = await createCourse(body);
  return NextResponse.json(course, { status: 201 });
}

Dynamic segments work the same way as pages:

// app/api/courses/[id]/route.ts
export async function GET(_req: Request, { params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const course = await getCourseById(id);
  if (!course) return Response.json({ error: 'Not found' }, { status: 404 });
  return Response.json(course);
}

How it works

  • Export a function per HTTP method: GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS.
  • GET /api/courses?level=Beginner calls the GET function.
  • Route Handlers are not cached by default.
  • A folder cannot contain both route.ts and page.tsx.
Status code Meaning Use when
200 OK Successful read
201 Created A resource was created
400 Bad request Invalid input
401 / 403 Unauthenticated / forbidden Missing login / no permission
404 Not found Resource does not exist
500 Server error Unexpected failure

Common mistakes

Mistake Effect Fix
Trusting request.json() without validation Bad data in the database Validate with a schema library such as Zod
No authentication on write endpoints Anyone can change data Check the session in every mutating handler
Always returning 200 Clients cannot detect errors Return accurate status codes
Building internal APIs just to feed your own pages Extra layer to maintain Query data directly in Server Components

Key takeaways

  • route.ts files export functions named after HTTP methods.
  • Use them for external consumers, webhooks, and client-side fetching, not for your own server-rendered pages.
  • Validate input, check authentication, and return correct status codes.

Try it: Build GET /api/courses with an optional level filter and GET /api/courses/[id] that returns 404 for unknown IDs. Test both in the browser.


Nextjs Tutorial

J

Jebasta





Get in Touch For Details