POST Requests and Request Bodies

POST handlers typically parse JSON or form data and then validate it before performing a mutation.

Never directly trust the request body. Clients can send malformed fields, unexpected types, oversized values, or malicious input.

A good handler separates parsing, validation, authorization, business logic, and response formatting.

Validated POST Handler
import { NextResponse } from 'next/server';
import { z } from 'zod';

const schema = z.object({
  name: z.string().min(2)
});

export async function POST(request: Request) {
  const body = await request.json();
  const result = schema.safeParse(body);

  if (!result.success) {
    return NextResponse.json(
      { error: 'Invalid request' },
      { status: 400 }
    );
  }

  const user = await requireUser();
  const created = await createUser(result.data, user.id);

  return NextResponse.json(created, { status: 201 });
}
💡 The handler validates input, authenticates the request, performs the mutation, and returns a meaningful HTTP status.
Key Takeaways
  • Parse and validate request bodies.
  • Authenticate and authorize before protected mutations.
  • Return appropriate HTTP status codes.