Create a Next.js API Route with Validation
Use this AI prompt to generate an API route inside Next.js app router with input validation using Zod and proper response types.
🧠 What This Prompt Does
This AI prompt helps you scaffold secure API routes in Next.js using the App Router’s route.ts pattern.
It includes input validation, structured responses, and async handling — ensuring robust backend logic directly inside your Next.js project.
💬 The Prompt
You are a backend-focused Next.js developer.
Generate a validated API route file using TypeScript and Zod.
Requirements:
- Handle POST requests
- Validate request body using Zod
- Return JSON responses with status codes
- Use NextResponse for handling outputs
API purpose:
{{api_purpose}}
⚙️ Example Input
{ "api_purpose": "Create a new user with email and password" }
🚀 Example Output (AI Generated)
import { NextResponse } from 'next/server';
import { z } from 'zod';
const userSchema = z.object({
email: z.string().email(),
password: z.string().min(6),
});
export async function POST(req: Request) {
try {
const body = await req.json();
const data = userSchema.parse(body);
// Example DB call placeholder
// await db.user.create({ data });
return NextResponse.json({ success: true, user: data }, { status: 201 });
} catch (error) {
if (error instanceof z.ZodError) {
return NextResponse.json({ error: error.errors }, { status: 400 });
}
return NextResponse.json(
{ error: 'Internal Server Error' },
{ status: 500 }
);
}
}
📘 When to Use This Prompt
- To create serverless routes inside the Next.js app router.
- When building secure APIs for CRUD or integration tasks.
- When you need validation and error handling baked in.
💡 Best Practices
- Use Zod for input validation to avoid runtime issues.
- Always sanitize user data before processing.
- Include meaningful status codes for clarity.
- Consider edge deployments for speed.
🏁 Summary
This prompt helps you quickly scaffold API routes in Next.js with validation, structure, and error handling.
Perfect for teams building secure, typed serverless endpoints with minimal boilerplate.
nextjsapivalidationserverlessai-prompt
Advertisement