validated-handler
Type-safe API route handler with automatic Zod validation for Next.js App Router...
What this skill does
# Next.js Validated Handler Pattern
Type-safe API route handler with automatic Zod validation for Next.js App Router.
## When to Use This Skill
Use this skill when:
- Building Next.js API routes (App Router)
- Want automatic input validation with Zod
- Need consistent error handling across API routes
- Want to eliminate boilerplate validation code
- Building type-safe APIs with TypeScript
## The Problem
Without a validated handler, every API route has repetitive validation code:
```typescript
// ❌ REPETITIVE - Every route looks like this
export async function GET(request: NextRequest) {
try {
// 1. Parse query params
const { searchParams } = new URL(request.url);
const rawPage = searchParams.get('page');
const rawLimit = searchParams.get('limit');
// 2. Validate each param manually
if (!rawPage || isNaN(Number(rawPage))) {
return NextResponse.json(
{ error: 'Invalid page parameter' },
{ status: 400 }
);
}
if (!rawLimit || isNaN(Number(rawLimit))) {
return NextResponse.json(
{ error: 'Invalid limit parameter' },
{ status: 400 }
);
}
const page = Number(rawPage);
const limit = Number(rawLimit);
// 3. Validate ranges
if (page < 1) {
return NextResponse.json(
{ error: 'Page must be >= 1' },
{ status: 400 }
);
}
if (limit < 1 || limit > 100) {
return NextResponse.json(
{ error: 'Limit must be between 1 and 100' },
{ status: 400 }
);
}
// 4. Finally, business logic
const data = await fetchData(page, limit);
return NextResponse.json(data);
} catch (error) {
console.error(error);
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
);
}
}
```
**Problems**:
- 30+ lines of boilerplate per route
- Error-prone manual validation
- Inconsistent error messages
- No type safety
- Hard to maintain across 100+ routes
## The Solution: validatedHandler
Create a reusable handler that combines Zod validation with Next.js API routes:
```typescript
// src/lib/api/handler.ts
import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
type ValidationSource = 'query' | 'body';
export function validatedHandler<T extends z.ZodType>(
config: {
input: { schema: T; source: ValidationSource };
},
handler: (ctx: { input: z.infer<T>; request: NextRequest }) => Promise<Response>,
) {
return async (request: NextRequest): Promise<Response> => {
try {
// 1. Parse input based on source
const rawInput = config.input.source === 'query'
? Object.fromEntries(new URL(request.url).searchParams)
: await request.json();
// 2. Validate with Zod schema
const result = config.input.schema.safeParse(rawInput);
if (!result.success) {
return NextResponse.json({
error: "Validation failed",
details: result.error.issues.map(err => ({
path: err.path.join("."),
message: err.message,
})),
}, { status: 400 });
}
// 3. Call handler with typed data
return await handler({ input: result.data, request });
} catch (error) {
console.error('API Error:', error);
return NextResponse.json(
{ error: "Internal server error" },
{ status: 500 }
);
}
};
}
```
### Usage Example
With validatedHandler, routes become clean and type-safe:
```typescript
// src/app/api/schools/route.ts
import { validatedHandler } from '@/lib/api/handler';
import { paginationInputSchema } from '@/lib/api/pagination';
import { z } from 'zod';
import { db } from '@/lib/db';
import { schools } from '@/lib/db/schema';
import { ilike } from 'drizzle-orm';
// Define schema
const getSchoolsSchema = paginationInputSchema.extend({
keyword: z.string().optional(),
districtId: z.string().uuid().optional(),
});
// Use validatedHandler - clean and type-safe!
export const GET = validatedHandler({
input: { source: 'query', schema: getSchoolsSchema }
}, async ({ input }) => {
// input is fully typed: { page: number, limit: number, keyword?: string, districtId?: string }
const schoolList = await db.query.schools.findMany({
where: input.keyword
? ilike(schools.name, `%${input.keyword}%`)
: undefined,
limit: input.limit,
offset: (input.page - 1) * input.limit,
});
return NextResponse.json(schoolList);
});
```
**Benefits**:
- ✅ Only 15 lines vs 50+ lines
- ✅ Automatic validation with Zod
- ✅ Full TypeScript type inference
- ✅ Consistent error responses
- ✅ No manual parsing
- ✅ Single place to maintain validation logic
## Core Implementation
### Complete Handler Implementation
```typescript
// src/lib/api/handler.ts
import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
type ValidationSource = 'query' | 'body';
interface HandlerConfig<T extends z.ZodType> {
input: {
schema: T;
source: ValidationSource;
};
}
interface HandlerContext<T extends z.ZodType> {
input: z.infer<T>;
request: NextRequest;
}
export function validatedHandler<T extends z.ZodType>(
config: HandlerConfig<T>,
handler: (ctx: HandlerContext<T>) => Promise<Response>,
) {
return async (request: NextRequest): Promise<Response> => {
try {
// Parse input based on source
let rawInput: unknown;
if (config.input.source === 'query') {
const { searchParams } = new URL(request.url);
rawInput = Object.fromEntries(searchParams);
} else if (config.input.source === 'body') {
rawInput = await request.json();
}
// Validate with Zod
const result = config.input.schema.safeParse(rawInput);
if (!result.success) {
return NextResponse.json({
error: "Validation failed",
details: result.error.issues.map(err => ({
path: err.path.join("."),
message: err.message,
})),
}, { status: 400 });
}
// Call handler with typed data
return await handler({
input: result.data,
request,
});
} catch (error) {
// Log error for debugging
console.error('API Error:', error);
// Return generic error to client
return NextResponse.json(
{ error: "Internal server error" },
{ status: 500 }
);
}
};
}
```
### Pagination Schema (Reusable)
```typescript
// src/lib/api/pagination.ts
import { z } from 'zod';
export const paginationInputSchema = z.object({
page: z.coerce.number().min(1).default(1),
limit: z.coerce.number().min(1).max(100).default(10),
});
export type PaginationInput = z.infer<typeof paginationInputSchema>;
export type PaginatedResponse<T> = {
data: T[];
page: number;
limit: number;
total: number;
totalPages: number;
nextPage: number | null;
previousPage: number | null;
};
export function createPaginatedResponse<T>(
data: T[],
total: number,
page: number,
limit: number
): PaginatedResponse<T> {
const totalPages = Math.ceil(total / limit);
return {
data,
page,
limit,
total,
totalPages,
nextPage: page < totalPages ? page + 1 : null,
previousPage: page > 1 ? page - 1 : null,
};
}
```
## Common Patterns
### GET Route with Query Params
```typescript
// src/app/api/providers/route.ts
import { validatedHandler } from '@/lib/api/handler';
import { paginationInputSchema } from '@/lib/api/pagination';
import { z } from 'zod';
const getProvidersSchema = paginationInputSchema.extend({
status: z.enum(['active', 'inactive']).optional(),
specialty: z.string().optional(),
});
export const GET = validatedHandler({
input: { source: 'query', schema: getProvidersSchema }
}, async ({ input }) => {
const providers = await db.query.providers.findMany({
where: buildWhereClause(input),
limit: input.limit,
offset: (input.page - 1) * input.limit,
});
return NextReRelated in Web Dev
generating-lwc-components
IncludedLightning Web Components with PICKLES methodology and 165-point scoring. Use this skill when the user creates or edits LWC components, builds wire service patterns, or writes Jest tests for LWC. TRIGGER when: user creates/edits LWC components, touches lwc/**/*.js, .html, .css, .js-meta.xml files, or asks about wire service, SLDS, or Jest LWC tests. DO NOT TRIGGER when: Apex classes (use generating-apex), Aura components, or Visualforce.
tanstack-query
IncludedManage server state in React with TanStack Query v5. Set up queries with useQuery, mutations with useMutation, configure QueryClient caching strategies, implement optimistic updates, and handle infinite scroll with useInfiniteQuery. Use when: setting up data fetching in React projects, migrating from v4 to v5, or fixing object syntax required errors, query callbacks removed issues, cacheTime renamed to gcTime, isPending vs isLoading confusion, keepPreviousData removed problems.
document-processor-api
IncludedProcess documents with Nutrient DWS. Use when the user wants to generate PDFs from HTML or URLs, convert Office/images/PDFs, assemble or split packets, OCR scans, extract text/tables/key-value pairs, redact PII, watermark, sign, fill forms, optimize PDFs, or produce compliance outputs like PDF/A or PDF/UA. Triggers include convert to PDF, merge these PDFs, OCR this scan, extract tables, redact PII, sign this PDF, make this PDF/A, or linearize for web delivery.
nutrient-document-processing
IncludedProcess documents with Nutrient DWS. Use when the user wants to generate PDFs from HTML or URLs, convert Office/images/PDFs, assemble or split packets, OCR scans, extract text/tables/key-value pairs, redact PII, watermark, sign, fill forms, optimize PDFs, or produce compliance outputs like PDF/A or PDF/UA. Triggers include convert to PDF, merge these PDFs, OCR this scan, extract tables, redact PII, sign this PDF, make this PDF/A, or linearize for web delivery.
tanstack-query
IncludedManage server state in React with TanStack Query v5. Covers useMutationState, simplified optimistic updates, throwOnError, network mode (offline/PWA), and infiniteQueryOptions. Use when setting up data fetching, fixing v4→v5 migration errors (object syntax, gcTime, isPending, keepPreviousData), or debugging SSR/hydration issues with streaming server components.
accelint-nextjs-best-practices
IncludedNext.js performance optimization and best practices. Use when writing Next.js code (App Router or Pages Router); implementing Server Components, Server Actions, or API routes; optimizing RSC serialization, data fetching, or server-side rendering; reviewing Next.js code for performance issues; fixing authentication in Server Actions; or implementing Suspense boundaries, parallel data fetching, or request deduplication.