typescriptintermediate

Type-Safe API Route Handler

Next.js App Router route handler with input validation, typed responses, and proper error handling.

typescript
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.