Lesson 23 +10 XP

Route Handlers Basics (route.ts & HTTP Methods)

Route Handlers Basics (route.ts & HTTP Methods)

Route Handlers allow you to create custom request handlers for a given route using the Web Request and Response APIs. They are the App Router replacement for the legacy pages/api API routes.

File Conventions

Route Handlers are defined in a file named route.ts (or .js) inside the app/ directory.

[!CAUTION] A route.ts file cannot exist in the same route segment folder as a page.tsx file! If both exist at app/api/users/route.ts and app/api/users/page.tsx, Next.js will throw a routing collision build error.

Supported HTTP Methods

Route Handlers support the following HTTP method functions: GET, POST, PUT, PATCH, DELETE, HEAD, and OPTIONS.

// app/api/users/route.ts
import { NextResponse } from 'next/server';

export async function GET() {
  const users = [
    { id: 1, name: 'Alice' },
    { id: 2, name: 'Bob' },
  ];

  return NextResponse.json(users);
}

export async function POST(request: Request) {
  const body = await request.json();

  if (!body.name) {
    return NextResponse.json({ error: 'Name is required' }, { status: 400 });
  }

  const newUser = { id: Date.now(), name: body.name };
  return NextResponse.json(newUser, { status: 201 });
}

Caching Behavior of GET Route Handlers

GET Route Handlers are statically cached by default in Next.js if they do not use dynamic functions or request objects.

Opting Out of Route Handler Caching:

  1. Export export const dynamic = 'force-dynamic'; from the route.ts file.
  2. Use dynamic methods like POST, PUT, or DELETE in the file.
  3. Access NextRequest properties like request.headers or query parameters.

Route Handler Method Summary

Export NameHTTP VerbPurposeCaching
GETRead resourceRetrieves dataStatically cached by default
POSTCreate resourceCreates new entryNever cached
PUT / PATCHUpdate resourceUpdates existing dataNever cached
DELETEDelete resourceRemoves recordNever cached

TL;DR

  • Define API endpoints in route.ts files inside the app/ directory.
  • Export functions named after HTTP verbs (GET, POST, DELETE, etc.).
  • Never place route.ts and page.tsx in the exact same directory.
  • Use NextResponse.json(data, { status: N }) to return structured JSON responses.