CPCODELAB
Next.js

Route Handlers (API Routes)

9 min read

Building API Endpoints with Route Handlers

A route.ts file inside src/app/api/ defines an HTTP endpoint. Export named functions for each HTTP method: GET, POST, PUT, PATCH, DELETE. Next.js maps incoming requests to the matching function.

ts
// src/app/api/contact/route.ts
import { NextRequest, NextResponse } from "next/server";

export async function POST(req: NextRequest) {
  const body = await req.json();
  const { name, email, message } = body;

  if (!name || !email || !message) {
    return NextResponse.json(
      { error: "All fields are required" },
      { status: 400 }
    );
  }

  // Process the contact form...
  await sendEmail({ name, email, message });

  return NextResponse.json({ success: true }, { status: 200 });
}

export async function GET() {
  return NextResponse.json({ status: "API is running" });
}

async function sendEmail(data: {
  name: string;
  email: string;
  message: string;
}) {
  // Integration with email provider
  console.log("Sending email:", data);
}

Route Handlers have access to the full Request and Response Web APIs via NextRequest and NextResponse. You can read headers, cookies, query parameters, and stream responses.

Do not create a route.ts in the same folder as a page.tsx. They will conflict. Route Handlers belong under src/app/api/ by convention.

Ready to test yourself?
Practice Next.js— quiz & coding exercises