Route handlers in Next.js

From the Next.js cheat sheet · API Routes · verified Jul 2026

Route handlers

typescript
// app/api/hello/route.ts
import { NextRequest, NextResponse } from 'next/server'

// GET request
export async function GET(request: NextRequest) {
  return NextResponse.json({ message: 'Hello World' })
}

// POST request
export async function POST(request: NextRequest) {
  const body = await request.json()
  
  // Process the data
  const result = await processData(body)
  
  return NextResponse.json(result, { status: 201 })
}

// Other HTTP methods
export async function PUT(request: NextRequest) {
  const body = await request.json()
  return NextResponse.json({ updated: true })
}

export async function DELETE(request: NextRequest) {
  return NextResponse.json({ deleted: true })
}

export async function PATCH(request: NextRequest) {
  return NextResponse.json({ patched: true })
}

// With headers and cookies
export async function GET(request: NextRequest) {
  // Read headers
  const token = request.headers.get('authorization')
  
  // Read cookies
  const theme = request.cookies.get('theme')
  
  // Set response headers
  return NextResponse.json(
    { data: 'example' },
    {
      status: 200,
      headers: {
        'Set-Cookie': 'token=abc123; Path=/; HttpOnly',
        'Cache-Control': 'no-cache',
      },
    }
  )
}
💡 Create API endpoints with route.ts files
⚡ Support all HTTP methods
📌 GET is dynamic (uncached) by default since v15; opt in via export const dynamic = force-static
🔥 Full access to Request/Response APIs

More Next.js tasks

Back to the full Next.js cheat sheet