0
0
NextjsHow-ToBeginner · 3 min read

How to Get Request Body in Next.js API Routes

In Next.js API routes, you get the request body from the req.body property inside the handler function. Make sure to use POST or other methods that send a body, and Next.js automatically parses JSON bodies for you.
📐

Syntax

Next.js API routes export a default function that receives two parameters: req (request) and res (response). You access the request body using req.body. This works when the client sends data in the request body, typically with POST, PUT, or PATCH methods.

Next.js automatically parses JSON request bodies, so you get a JavaScript object directly.

javascript
export default function handler(req, res) {
  const data = req.body;
  res.status(200).json({ receivedData: data });
}
💻

Example

This example shows a Next.js API route that reads JSON data sent in the request body and responds with a confirmation message including the received data.

javascript
export default function handler(req, res) {
  if (req.method === 'POST') {
    const { name, age } = req.body;
    res.status(200).json({ message: `Hello, ${name}! You are ${age} years old.` });
  } else {
    res.status(405).json({ error: 'Method not allowed' });
  }
}
Output
{"message":"Hello, Alice! You are 30 years old."}
⚠️

Common Pitfalls

  • Not using the correct HTTP method: Request body is usually sent with POST, PUT, or PATCH. Using GET will not have a body.
  • Forgetting to parse JSON on the client: When sending data, ensure the client sets Content-Type: application/json and sends a JSON string.
  • Trying to parse body manually: Next.js parses JSON automatically, so manual parsing is unnecessary and can cause errors.
javascript
/* Wrong way: Trying to parse JSON manually */
export default function handler(req, res) {
  const data = JSON.parse(req.body); // This will cause error because req.body is already parsed
  res.status(200).json({ data });
}

/* Right way: Use req.body directly */
export default function handler(req, res) {
  const data = req.body;
  res.status(200).json({ data });
}
📊

Quick Reference

Remember these key points when working with request bodies in Next.js API routes:

  • Use req.body to access the parsed request body.
  • Send data with POST, PUT, or PATCH methods.
  • Set Content-Type: application/json on the client when sending JSON.
  • Next.js automatically parses JSON bodies; no manual parsing needed.
  • Handle unsupported methods by returning a 405 status.

Key Takeaways

Access the request body in Next.js API routes using req.body inside the handler function.
Ensure the client sends JSON with the correct Content-Type header and uses POST or similar methods.
Next.js automatically parses JSON request bodies; do not parse them manually.
Return 405 status for unsupported HTTP methods to handle errors gracefully.
Request bodies are not available on GET requests; use appropriate HTTP methods.