next-api-helpers
v1.0.0
Published
TypeScript utilities for Next.js API routes — Zod validation, typed handlers, auth middleware, Prisma error handling, and response helpers
Maintainers
Readme
next-api-helpers
TypeScript utilities for Next.js API routes — Zod validation, typed handlers, auth middleware, Prisma error handling, and response helpers.
Install
npm install next-api-helpersQuick Start
import { z, validateZod, requireZod, ok, fail, ApiError, requireJson } from "next-api-helpers";
import { classifyPrismaError } from "next-api-helpers";
// Validate request body with Zod
const schema = z.object({ email: z.string().email(), name: z.string().min(1) });
export async function POST(request: Request) {
const body = await requireJson(request);
const result = validateZod(schema, body);
if (!result.success) {
return fail(422, result.errors.map(e => e.message).join("; "));
}
try {
const data = await prisma.user.create({ data: result.data });
return ok(data, 201);
} catch (e) {
const classified = classifyPrismaError(e);
if (classified.type === "UNIQUE") return fail(409, "Email already exists");
throw e;
}
}API
Response helpers
| Function | Returns | Use |
|----------|---------|-----|
| ok(data, status?) | ApiResponse | Success response |
| fail(status, message, code?) | ApiResponse | Error response |
Validation
| Function | Use |
|----------|-----|
| validateZod(schema, data) | Safe Zod validation with typed result |
| requireZod(schema, data) | Zod validation that throws ApiError(422) on failure |
| z | Re-exported from zod |
Body parsing
| Function | Use |
|----------|-----|
| requireJson(request) | Parse and validate JSON body |
Auth
| Function | Use |
|----------|-----|
| authenticate(request, options) | Verify JWT and extract user |
Prisma errors
| Function | Use |
|----------|-----|
| classifyPrismaError(error) | Categorize Prisma errors (UNIQUE, NOT_FOUND, CONNECTION, etc.) |
Rate limiting
| Function | Use |
|----------|-----|
| rateLimit(identifier, options) | In-memory rate limiter |
| rateLimitCheck(request, identifier, options) | Rate limit from request IP |
| rateLimitReset() | Clear all rate limit data |
Error handling
| Class/Function | Use |
|----------------|-----|
| ApiError | Typed API error with status code |
Examples per project type
Broker / Auth route
import { authenticate, ok, fail, ApiError } from "next-api-helpers";
export async function POST(request: Request) {
const user = await authenticate(request, { secret: process.env.JWT_SECRET! });
if (user.role !== "admin") return fail(403, "Admin only");
return ok({ message: "Authorized" });
}With Zod validation
import { z, validateZod, requireJson, ok, fail } from "next-api-helpers";
const loginSchema = z.object({
email: z.string().email(),
password: z.string().min(8),
});
export async function POST(request: Request) {
const body = await requireJson(request);
const result = validateZod(loginSchema, body);
if (!result.success) {
return fail(422, result.errors[0].message);
}
// result.data.email, result.data.password — fully typed
}Prisma with error classification
import { classifyPrismaError, ok, fail } from "next-api-helpers";
try {
await prisma.user.create({ data: { email } });
} catch (e) {
const err = classifyPrismaError(e);
if (err.type === "UNIQUE") return fail(409, "Email already registered");
if (err.retryable) return fail(503, "Database unavailable", "DB_ERROR");
throw e;
}Rate limiting
import { rateLimit, fail } from "next-api-helpers";
export async function POST(request: Request) {
const limiter = rateLimit(request.headers.get("ip") ?? "unknown", {
maxRequests: 5,
windowMs: 60_000,
});
if (!limiter.allowed) return fail(429, "Too many requests");
// handle request
}Features
- Zero runtime dependencies — works with any Next.js version
- Zod integration — typed validation with clear error messages
- Prisma error classification — 15+ error codes mapped to types
- JWT authentication — works with
jose(ES256, HS256, RS256, etc.) - In-memory rate limiting — simple, no external dependencies
- Tree-shakeable — only import what you use
- Fully typed — TypeScript definitions included
Peer Dependencies
| Package | Required For | Optional |
|---------|-------------|----------|
| next | Request type imports | Yes |
| zod | Validation functions | Yes |
| prisma | Error classification | Yes |
| jose | JWT authentication | Yes |
Development
npm install
npm run dev # watch mode build
npm run test # run tests
npm run build # production build
npm run typecheck # TypeScript checkLicense
MIT
