Type-Safe API Route Handler
Next.js App Router route handler with input validation, typed responses, and proper error handling.
import { NextRequest, NextResponse } from 'next/server';
interface CreateUserBody {
name: string;
email: string;
}
export async function POST(request: NextRequest) {
try {
const body = (await request.json()) as CreateUserBody;
if (!body.name || !body.email) {
return NextResponse.json(
{ error: 'Name and email are required' },
{ status: 400 }
);
}
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(body.email)) {
return NextResponse.json(
{ error: 'Invalid email format' },
{ status: 400 }
);
}
// Replace with your database call
const user = { id: crypto.randomUUID(), ...body, createdAt: new Date() };
return NextResponse.json(user, { status: 201 });
} catch {
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
);
}
}
export async function GET(request: NextRequest) {
const { searchParams } = new URL(request.url);
const page = parseInt(searchParams.get('page') ?? '1', 10);
const limit = Math.min(parseInt(searchParams.get('limit') ?? '20', 10), 100);
// Replace with your database call
const users: unknown[] = [];
return NextResponse.json({ data: users, page, limit });
}Use Cases
- CRUD API endpoints
- Webhook handlers
- Third-party integrations
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
Server Action with Form Validation
Next.js Server Action handling form submissions with validation, error messages, and redirect on success.
Authentication Middleware Guard
Next.js middleware that checks auth tokens on protected routes and redirects unauthenticated users to login.
Dynamic OG Image Generation
Generate Open Graph images on-the-fly using Next.js ImageResponse with custom fonts and dynamic content.
On-Demand ISR Revalidation
Trigger incremental static regeneration via API route with secret token validation for instant cache purge.