Problem Statement
How do you create a POST endpoint using Route Handlers in App Router with request validation?
Explanation
Create an app/api/users/route.js file and export an async POST function that receives a Request object, use await request.json() to parse the JSON body, validate the data using a schema validator like Zod or Yup to ensure required fields and correct types, and return appropriate responses using new Response or NextResponse with status codes.
Handle errors with try-catch blocks returning 400 for validation errors or 500 for server errors, set proper headers like Content-Type application/json, and consider using TypeScript for type safety throughout.
You can access headers with request.headers, query parameters from the URL, and dynamic route params from the function's second parameter, and return NextResponse.json(data, { status: 201 }) for successful creation or NextResponse.json({ error: 'message' }, { status: 400 }) for validation failures.