How do you read query parameters and the request body inside a route handler?
Short answer
You access query parameters through the request URL's searchParams property, and read the request body by calling a method like json on the request object, which returns a promise that resolves to the parsed body data sent by the client.
Advertisement
AModel answer
You access query parameters through the request URL's searchParams property, and read the request body by calling a method like json on the request object, which returns a promise that resolves to the parsed body data sent by the client.
export async function POST(request) {
const { searchParams } = new URL(request.url);
const category = searchParams.get('category');
const body = await request.json();
return Response.json({ category, received: body });
}Real-world example
A search endpoint reads a category filter from the query string while also accepting a JSON body containing search preferences, combining both sources of input inside a single route handler.
Likely follow-ups
- How is reading the request body different between GET and POST route handlers?
- What happens if the request body is not valid JSON?
Related topics