Route Handlers (API Routes)

▲ Next.js Lesson 11 Advanced

Route Handlers allow you to create custom backend API endpoints, handling requests using standard HTTP methods and returning structured JSON payloads.

1 route.js files and dynamic backend endpoints

Writing custom API endpoints in Next.js is configured through specific naming conventions:

  • route.js / route.ts: Files containing request handlers. Like page files, they map directly to folder paths (e.g. app/api/users/route.js exposes /api/users).
  • Http methods handlers: Export functions named after HTTP methods (GET, POST, PUT, DELETE, PATCH).
  • NextResponse: Helper class extending standard Web Response objects, simplifying sending JSON payloads and headers.
2 Writing a Route Handler API

Let's check how to write a GET/POST handler API endpoint:

TypeScript — app/api/users/route.js
import { NextResponse } from 'next/server';

// Handle HTTP GET requests
export async function GET() {
  const users = [
    { id: 1, name: 'Balaji' },
    { id: 2, name: 'Nayak' }
  ];
  
  return NextResponse.json(users);
}

// Handle HTTP POST requests
export async function POST(request) {
  const body = await request.json();
  console.log('Received post payload:', body);

  return NextResponse.json({ 
    status: 'success', 
    received: body 
  }, { status: 201 });
}
3 Code Challenge
Challenge: Write a dynamic route handler representing a delete endpoint (e.g. app/api/tasks/[id]/route.js). Read the dynamic ID parameter and log it in the console on a DELETE request.