Loading content…
Loading content…
Build a GET/POST route handler in Next.js (`/api/feedback/route.ts`). The handler must validate the POST body (requires an email and message), return a 400 Bad Request error if validation fails, and return a 201 Created response on success.
Expected Output
A Next.js API route handler script handling payload assertions and returning status codes.
Click to toggle the recommended code solution
Architectural Explanation
The API handler imports Next server classes, parses inputs inside try-catch blocks, validates the inputs, and returns appropriate HTTP status codes.Code Snippet
import { NextRequest, NextResponse } from "next/server";
export async function POST(req: NextRequest) {
try {
const body = await req.json();
const { email, message } = body;
if (!email || !email.includes("@") || !message) {
return NextResponse.json(
{ error: "Valid email and message parameters are required." },
{ status: 400 }
);
}
return NextResponse.json(
{ success: true, message: "Feedback submitted successfully." },
{ status: 201 }
);
} catch (error) {
return NextResponse.json(
{ error: "Malformed request payload." },
{ status: 400 }
);
}
}How to pitch this solution during technical interviews
I compile route handlers using App Router API folders. I parse incoming payloads inside try-catch scopes to prevent crashes, validate body fields against Zod schemas, and issue standardized JSON error payloads and HTTP status codes.