0
0
NextjsHow-ToBeginner · 3 min read

How to Return JSON from API Route in Next.js

In Next.js, you return JSON from an API route by exporting a function that receives req and res objects and calling res.status(200).json(data) to send JSON data. This function lives inside the pages/api folder and acts as a serverless endpoint.
📐

Syntax

An API route in Next.js is a function exported as default from a file inside pages/api. It receives two arguments: req (request) and res (response). To return JSON, use res.status(statusCode).json(data).

  • req: Contains request info like method and body.
  • res: Used to send back the response.
  • status(code): Sets HTTP status code (e.g., 200 for success).
  • json(data): Sends JSON data as response.
javascript
export default function handler(req, res) {
  const data = { message: 'Hello from Next.js API!' };
  res.status(200).json(data);
}
Output
{"message":"Hello from Next.js API!"}
💻

Example

This example shows a simple API route that returns a JSON object with a greeting message. When you visit /api/hello, it responds with JSON.

javascript
export default function handler(req, res) {
  const response = {
    success: true,
    greeting: 'Hello, Next.js API!'
  };
  res.status(200).json(response);
}
Output
{"success":true,"greeting":"Hello, Next.js API!"}
⚠️

Common Pitfalls

Common mistakes when returning JSON from Next.js API routes include:

  • Not setting the status code before sending JSON, which defaults to 200 but is clearer to set explicitly.
  • Trying to send multiple responses in one request, which causes errors.
  • Forgetting to export the handler function as default.
  • Using res.send() with objects instead of res.json(), which may not set the correct headers.
javascript
/* Wrong: Missing export default */
function handler(req, res) {
  res.status(200).json({ error: 'Missing export default' });
}

/* Right: Export default function */
export default function handler(req, res) {
  res.status(200).json({ success: true });
}
📊

Quick Reference

ActionCode ExampleDescription
Create API routeCreate file in pages/api/filename.jsDefines a serverless function endpoint
Export handlerexport default function handler(req, res) {}Function to handle requests
Send JSON responseres.status(200).json({ key: 'value' })Returns JSON with HTTP status 200
Set error statusres.status(404).json({ error: 'Not found' })Returns JSON with error status code
Access request methodreq.methodCheck HTTP method like GET or POST

Key Takeaways

Export a default function in pages/api to create an API route in Next.js.
Use res.status(code).json(data) to send JSON responses with proper HTTP status.
Always set the status code explicitly for clarity and correctness.
Avoid sending multiple responses in one API call to prevent errors.
Use req and res objects to handle request data and send responses.