0
0
NextJSframework~5 mins

Request parsing in route handlers in NextJS

Choose your learning style9 modes available
Introduction

Request parsing helps your app understand what the user sends. It turns raw data into usable information.

When you want to get data from a form submission.
When your app needs to read JSON sent by the user.
When you want to handle query parameters from a URL.
When you need to read headers or cookies from a request.
When building APIs that accept user input.
Syntax
NextJS
export async function POST(request) {
  const data = await request.json();
  // use data here
  return new Response('Received');
}
Use request.json() to parse JSON body data.
You can also use request.text() or request.formData() depending on the data type.
Examples
Parse JSON body and greet by name.
NextJS
export async function POST(request) {
  const jsonData = await request.json();
  return new Response(`Hello, ${jsonData.name}`);
}
Read query parameter id from the URL.
NextJS
export async function GET(request) {
  const url = new URL(request.url);
  const id = url.searchParams.get('id');
  return new Response(`ID is ${id}`);
}
Parse form data sent from a form submission.
NextJS
export async function POST(request) {
  const formData = await request.formData();
  const email = formData.get('email');
  return new Response(`Email received: ${email}`);
}
Sample Program

This route handler reads JSON data sent in a POST request. It extracts name and age from the data and sends back a friendly message.

NextJS
export async function POST(request) {
  // Parse JSON data from request body
  const data = await request.json();
  // Extract name and age
  const { name, age } = data;
  // Create a response message
  const message = `Hello, ${name}! You are ${age} years old.`;
  return new Response(message);
}
OutputSuccess
Important Notes

Always check the content type before parsing to avoid errors.

Use await because parsing is asynchronous.

For GET requests, parse URL parameters instead of body data.

Summary

Request parsing turns raw user data into usable info.

Use request.json(), request.formData(), or URL parsing depending on data type.

Parsing is key to handling user input in Next.js route handlers.