Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

NX
Next.js
0/10 completed
Beginner
Why Next.js?Pages, layouts and routingLinks, images and fonts
Intermediate
Server and Client ComponentsFetching data and streamingRoute Handlers (API routes)Forms and Server Actions
Advanced
Caching and revalidationMetadata, SEO, errors and Proxy
Pro
Auth, deployment and production
Tracks / Next.js / Intermediate

Route Handlers (API routes)

Route Handlers let you build HTTP endpoints (a REST API, webhooks, file downloads) inside your Next.js app, using the standard Web Request and Response APIs.

Creating an endpoint

Create a route.ts file and export functions named after HTTP methods:

ts
// app/api/hello/route.ts  →  GET /api/hello
export async function GET() {
  return Response.json({ message: 'Hello from Next.js!', time: new Date().toISOString() });
}

Supported methods: GET, POST, PUT, PATCH, DELETE, HEAD and OPTIONS. Calling any other method returns 405 Method Not Allowed.

A route.ts can't live in the same folder as a page.tsx. Put APIs under app/api/… by convention.

A small REST API

ts
// app/api/todos/route.ts
type Todo = { id: number; text: string; done: boolean };
const todos: Todo[] = [{ id: 1, text: 'Learn Route Handlers', done: false }];   // use a database in real apps!

export async function GET(request: Request) {
  const { searchParams } = new URL(request.url);
  const onlyOpen = searchParams.get('open') === 'true';     // /api/todos?open=true
  return Response.json(onlyOpen ? todos.filter((t) => !t.done) : todos);
}

export async function POST(request: Request) {
  const body = await request.json();
  if (typeof body.text !== 'string' || body.text.trim() === '') {
    return Response.json({ error: 'text is required' }, { status: 400 });
  }
  const todo: Todo = { id: Date.now(), text: body.text.trim(), done: false };
  todos.push(todo);
  return Response.json(todo, { status: 201 });
}
bash
curl http://localhost:3000/api/todos
curl -X POST http://localhost:3000/api/todos -H "Content-Type: application/json" -d '{"text":"Ship it"}'

Dynamic segments

ts
// app/api/todos/[id]/route.ts  →  /api/todos/123
export async function DELETE(_request: Request, { params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const deleted = await db.todo.delete({ where: { id: Number(id) } }).catch(() => null);
  if (!deleted) return Response.json({ error: 'Not found' }, { status: 404 });
  return new Response(null, { status: 204 });
}

There's also a typed helper, RouteContext<'/api/todos/[id]'>, for the second argument.

Reading request data

ts
import { cookies, headers } from 'next/headers';
import type { NextRequest } from 'next/server';

export async function POST(request: NextRequest) {
  const contentType = request.headers.get('content-type');
  const token = (await cookies()).get('session')?.value;
  const userAgent = (await headers()).get('user-agent');
  const ip = request.headers.get('x-forwarded-for');

  const form = await request.formData();          // for form submissions
  const file = form.get('avatar') as File | null; // file uploads

  return Response.json({ contentType, hasToken: !!token, userAgent, ip, fileName: file?.name });
}

Validating input

Never trust request bodies. Validate them with a schema (Zod is the common choice):

ts
import { z } from 'zod';

const CreateUser = z.object({
  email: z.string().email(),
  name: z.string().min(1).max(100),
});

export async function POST(request: Request) {
  const parsed = CreateUser.safeParse(await request.json());
  if (!parsed.success) {
    return Response.json({ errors: parsed.error.flatten().fieldErrors }, { status: 422 });
  }
  const user = await db.user.create({ data: parsed.data });
  return Response.json(user, { status: 201 });
}

Webhooks

Third-party services (Stripe, GitHub, Clerk…) notify your app by POSTing to a URL. Route Handlers are perfect for this. Always verify the signature:

ts
// app/api/webhooks/stripe/route.ts
import Stripe from 'stripe';

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);

export async function POST(request: Request) {
  const payload = await request.text();                    // the raw body is needed for signature checks
  const signature = request.headers.get('stripe-signature')!;
  let event: Stripe.Event;
  try {
    event = stripe.webhooks.constructEvent(payload, signature, process.env.STRIPE_WEBHOOK_SECRET!);
  } catch {
    return new Response('Invalid signature', { status: 400 });
  }
  if (event.type === 'checkout.session.completed') {
    // mark the order as paid…
  }
  return new Response('ok');
}

Non-JSON responses

ts
// app/api/report/route.ts — download a CSV
export async function GET() {
  const csv = 'id,name\n1,Asha\n2,Rahul\n';
  return new Response(csv, {
    headers: {
      'Content-Type': 'text/csv',
      'Content-Disposition': 'attachment; filename="users.csv"',
    },
  });
}

Caching

Route Handlers run on every request by default. With Cache Components enabled, a GET handler that doesn't read request data or anything non-deterministic can be pre-rendered at build time. Use 'use cache' inside it to cache expensive work (more in the Caching lesson).

Route Handlers vs Server Actions

Use a Route Handler for… Use a Server Action (next lesson) for…
Public APIs consumed by mobile apps or other services Mutations triggered by your own UI (forms, buttons)
Webhooks from third parties Create, update, delete from React components
Non-HTML responses (CSV, images, RSS) Progressive forms that work without JS

Practice (in your project)

Build /api/notes with:

  1. GET, which returns all notes (keep them in an in-memory array for now)
  2. POST, which validates { title: string, body: string }, returns 422 on bad input and 201 with the created note on success
  3. DELETE /api/notes/[id], which returns 404 if the note doesn't exist

Test it with curl, or with a REST client like Bruno, Insomnia or the VS Code "REST Client" extension.

✎ Check your understanding

1.Which file creates the endpoint GET /api/users?

2.What status code should a successful "create" return?

← Fetching data and streaming