Next.js 15 introduces powerful new patterns for building APIs that scale. In this comprehensive guide, we'll explore the best practices for creating type-safe, performant API routes using the App Router.
Getting Started
Before diving in, ensure you have Next.js 15 installed. The new App Router provides a file-system based approach to API routes that makes organization intuitive.
1$npm create next-app@latest my-api --typescript
Route Handlers
Route Handlers are defined in route.ts files and support all HTTP methods. They provide native Request and Response objects for maximum flexibility.
1// app/api/users/route.ts2import { NextResponse } from "next/server";34export async function GET() {5 const users = await prisma.user.findMany();6 return NextResponse.json(users);7}89export async function POST(request: Request) {10 const body = await request.json();11 const user = await prisma.user.create({ data: body });12 return NextResponse.json(user, { status: 201 });13}
Type Safety with Zod
Runtime validation is crucial for API reliability. Zod provides excellent TypeScript integration for validating incoming requests.
1import { z } from "zod";23const createUserSchema = z.object({4 name: z.string().min(2),5 email: z.string().email(),6 role: z.enum(["admin", "user"]).default("user"),7});89export async function POST(request: Request) {10 const body = await request.json();11 const result = createUserSchema.safeParse(body);1213 if (!result.success) {14 return NextResponse.json(15 { error: result.error.issues },16 { status: 400 }17 );18 }1920 const user = await createUser(result.data);21 return NextResponse.json(user, { status: 201 });22}
Conclusion
Next.js 15's API routes provide a powerful foundation for building scalable backends. Combined with TypeScript and Zod, you can create APIs that are both type-safe and maintainable.