typescriptbeginner
Route Handler Response Helpers
Common response patterns for Next.js route handlers with proper status codes and headers.
typescriptPress ⌘/Ctrl + Shift + C to copy
// app/api/helpers.ts
import { NextResponse } from 'next/server';
export function jsonOk<T>(data: T) {
return NextResponse.json(data, { status: 200 });
}
export function created<T>(data: T) {
return NextResponse.json(data, { status: 201 });
}
export function noContent() {
return new NextResponse(null, { status: 204 });
}
export function badRequest(message: string) {
return NextResponse.json({ error: message }, { status: 400 });
}
export function unauthorized() {
return NextResponse.json({ error: 'Authentication required' }, { status: 401 });
}
export function notFound(resource = 'Resource') {
return NextResponse.json({ error: `${resource} not found` }, { status: 404 });
}
// Usage: app/api/posts/[id]/route.ts
import { jsonOk, notFound, badRequest } from '../helpers';
export async function GET(
_req: Request,
{ params }: { params: Promise<{ id: string }> }
) {
const { id } = await params;
const post = await db.post.findUnique({ where: { id } });
if (!post) return notFound('Post');
return jsonOk(post);
}Use Cases
- API route handlers
- consistent error responses
- REST APIs
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
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
typescriptintermediate
Type-Safe API Route Handler
Next.js App Router route handler with input validation, typed responses, and proper error handling.
Best for: CRUD API endpoints
#api#route-handler
typescriptintermediate
API Route Rate Limiting
Add rate limiting to Next.js API routes with sliding window, IP-based limits, and custom responses.
Best for: API abuse prevention
#nextjs#api
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