API Routes and Server ActionsLesson 3.1
How to create API routes in the Next.js App Router
Route Handlers, route.ts, GET POST PUT DELETE handlers, NextRequest, NextResponse, HTTP methods, JSON responses
Route Handlers Replace API Routes
In the App Router, API endpoints are called Route Handlers. Create a route.ts file inside any folder in app/. The file exports named functions matching HTTP methods.
// app/api/users/route.ts
import { NextRequest, NextResponse } from 'next/server'
export async function GET() {
const users = await db.user.findMany()
return NextResponse.json(users)
}
export async function POST(request: NextRequest) {
const body = await request.json()
const user = await db.user.create({ data: body })
return NextResponse.json(user, { status: 201 })
}Reading Request Data
export async function GET(request: NextRequest) {
// Query params
const { searchParams } = new URL(request.url)
const limit = searchParams.get('limit') ?? '10'
// Headers
const authHeader = request.headers.get('authorization')
// Cookies
const token = request.cookies.get('session')?.value
return NextResponse.json({ limit, hasAuth: !!authHeader })
}Returning Different Status Codes
// 404
return NextResponse.json({ error: 'Not found' }, { status: 404 })
// 401
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
// Redirect from a Route Handler
return NextResponse.redirect(new URL('/login', request.url))Route Handlers and page.tsx files cannot coexist in the same folder. If a folder has route.ts, it's an API endpoint. If it has page.tsx, it's a UI route. Put your API under /app/api/ by convention to avoid conflicts.
