Route Handlers

Create API endpoints by exporting HTTP-method functions from a route.ts file.

Syntaxapp/api/<name>/route.ts exports GET/POST/...

Route Handlers let you build API endpoints inside the App Router. Add a route.ts file in a folder under app/ and export functions named after HTTP methods (GET, POST, etc.). They use the Web standard Request and Response objects.

Where they live

A file at app/api/hello/route.ts responds at /api/hello. A folder cannot contain both a page.tsx and a route.ts at the same level.

Example

Example Β· typescript
// app/api/hello/route.ts  ->  GET /api/hello
import { NextResponse } from 'next/server';

export async function GET() {
  return NextResponse.json({ message: 'Hello, API!' });
}

When to use it

  • A mobile app consumes a JSON feed from a Next.js route handler that reads the database without a separate backend.
  • A Stripe webhook posts events to app/api/webhooks/route.ts where a handler validates and processes them.
  • A developer exposes a health-check endpoint at /api/health that returns server status for uptime monitoring.

More examples

Hello JSON endpoint

Exporting a function named GET from a route.ts file creates a GET endpoint at that file's URL path.

Example Β· ts
// app/api/hello/route.ts
import { NextResponse } from 'next/server';

export function GET() {
  return NextResponse.json({ message: 'Hello, world!' });
}

Health check endpoint

A minimal route handler returning JSON is enough for an uptime monitor to confirm the server is running.

Example Β· ts
// app/api/health/route.ts
import { NextResponse } from 'next/server';

export function GET() {
  return NextResponse.json({ status: 'ok', time: new Date().toISOString() });
}

Custom response headers

NextResponse.json accepts a second options argument to set status codes and HTTP headers.

Example Β· ts
// app/api/data/route.ts
import { NextResponse } from 'next/server';

export function GET() {
  return NextResponse.json(
    { data: 'example' },
    { headers: { 'Cache-Control': 'no-store' } }
  );
}

Discussion

  • Be the first to comment on this lesson.
Route Handlers β€” Next.js | SoundsCode