Next.js API Route with Validation and Error Handling

A type-safe API route implementation with Zod validation and proper error handling


A modern implementation of Next.js API routes with Zod validation, proper error handling, and type safety.

Types and Schemas

types.ts
// Input validation schema
const createUserSchema = z.object({
  name: z.string().min(2).max(50),
  email: z.string().email(),
  role: z.enum(['USER', 'ADMIN']).default('USER'),
});
 
// Type for the request body
type CreateUserInput = z.infer<typeof createUserSchema>;
 
// Error response type
type ErrorResponse = {
  error: string;
  details?: unknown;
};

POST Handler

POST handler
export async function POST(request: Request) {
  try {
    const body = await request.json();
    
    // Validate input
    const validatedData = createUserSchema.parse(body);
    
    // Create user in database
    const user = await prisma.user.create({
      data: validatedData,
      select: {
        id: true,
        name: true,
        email: true,
        role: true,
        createdAt: true,
      },
    });
 
    return NextResponse.json(user, { status: 201 });
  } catch (error) {
    if (error instanceof z.ZodError) {
      return NextResponse.json(
        {
          error: 'Validation failed',
          details: error.errors,
        } as ErrorResponse,
        { status: 400 }
      );
    }
 
    if (error instanceof Error) {
      return NextResponse.json(
        {
          error: error.message,
        } as ErrorResponse,
        { status: 500 }
      );
    }
 
    return NextResponse.json(
      {
        error: 'An unexpected error occurred',
      } as ErrorResponse,
      { status: 500 }
    );
  }
}

GET Handler

GET handler
export async function GET(request: Request) {
  try {
    const { searchParams } = new URL(request.url);
    const page = parseInt(searchParams.get('page') || '1');
    const limit = parseInt(searchParams.get('limit') || '10');
    
    const [users, total] = await Promise.all([
      prisma.user.findMany({
        skip: (page - 1) * limit,
        take: limit,
        orderBy: { createdAt: 'desc' },
        select: {
          id: true,
          name: true,
          email: true,
          role: true,
        },
      }),
      prisma.user.count(),
    ]);
 
    return NextResponse.json({
      data: users,
      pagination: {
        total,
        page,
        limit,
        totalPages: Math.ceil(total / limit),
      },
    });
  } catch (error) {
    return NextResponse.json(
      {
        error: 'Failed to fetch users',
      } as ErrorResponse,
      { status: 500 }
    );
  }
}

Imports

imports.ts
import { NextResponse } from 'next/server';
import { z } from 'zod';
import { prisma } from '@/lib/prisma';

Features:

  • Type-safe API routes with TypeScript
  • Input validation using Zod
  • Proper error handling and status codes
  • Pagination support
  • Database integration with Prisma
  • Clean response structure
  • Selective field returns