POST request handlers
This page explains how to implement POST request handlers in Next.js route handlers.
Creating a POST handler
To handle POST requests, export an async function named POST
in your route handler file:
export async function POST(request: Request) { const comment = await request.json();
// Process the comment and return a response return Response.json(comment, { status: 201 });}
Example implementation
Here’s a complete example of a POST handler that adds a new comment:
interface Comment { id: number; text: string;}
let comments: Comment[] = [];
export async function POST(request: Request) { try { const body = await request.json();
const newComment = { id: comments.length + 1, text: body.text, };
comments.push(newComment);
return Response.json(newComment, { status: 201, headers: { "Content-Type": "application/json", }, }); } catch (error) { return new Response("Invalid request body", { status: 400 }); }}
Status codes
Common status codes for POST requests:
201
: Resource created successfully400
: Bad request (invalid input)401
: Unauthorized403
: Forbidden500
: Internal server error
Request validation
Validate incoming data before processing:
export async function POST(request: Request) { try { const body = await request.json();
if (!body.text || typeof body.text !== "string") { return new Response("Invalid comment text", { status: 400 }); }
// Process valid comment... } catch (error) { return new Response("Invalid request body", { status: 400 }); }}
Good to know
- POST handlers receive the Request object as their first parameter
- Always validate input data before processing
- Use appropriate status codes in responses