typescriptintermediate
Type-Safe API Route Handler
Next.js App Router route handler with input validation, typed responses, and proper error handling.
typescriptPress ⌘/Ctrl + Shift + C to copy
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.
typescriptintermediate
Route Handler with CORS Support
Add CORS headers to Next.js route handlers for cross-origin API access.
Best for: external API consumers
#nextjs#cors
typescriptintermediate
Server Action with Form Validation
Next.js Server Action handling form submissions with validation, error messages, and redirect on success.
Best for: Blog post creation
#server-actions#forms
typescriptintermediate
Next.js Server Actions with Forms
Use Server Actions for form handling with validation, optimistic updates, and error handling.
Best for: Form submissions without API routes
#nextjs#server-actions
typescriptintermediate
Next.js Route Handlers (API Routes)
Build RESTful API endpoints using Next.js App Router route handlers with typed responses.
Best for: Building REST APIs within a Next.js application
#nextjs#api