0
0
NextJSframework~5 mins

Response formatting in NextJS

Choose your learning style9 modes available
Introduction

Response formatting helps you send data back to the user in a clear and useful way. It makes sure the information looks right and is easy to understand.

When you want to send JSON data from an API route to a web page.
When you need to return a custom message or error from your server.
When you want to control the status code and headers of your response.
When you want to format data before sending it to a client app or browser.
Syntax
NextJS
export async function GET(request) {
  return new Response(JSON.stringify({ message: 'Hello' }), {
    status: 200,
    headers: { 'Content-Type': 'application/json' }
  });
}
Use Response to create a response with body, status, and headers.
Always set Content-Type header to tell the client what type of data you send.
Examples
Sends plain text response with status 200.
NextJS
export async function GET() {
  return new Response('Hello World', {
    status: 200,
    headers: { 'Content-Type': 'text/plain' }
  });
}
Sends JSON data with correct content type.
NextJS
export async function GET() {
  const data = { name: 'Alice', age: 30 };
  return new Response(JSON.stringify(data), {
    status: 200,
    headers: { 'Content-Type': 'application/json' }
  });
}
Sends a 404 error message in JSON format.
NextJS
export async function GET() {
  return new Response(JSON.stringify({ error: 'Not found' }), {
    status: 404,
    headers: { 'Content-Type': 'application/json' }
  });
}
Sample Program

This Next.js API route sends a JSON response with user data. The client will receive the user info as JSON with status 200.

NextJS
export async function GET() {
  const user = { id: 1, name: 'John Doe' };
  const json = JSON.stringify(user);
  return new Response(json, {
    status: 200,
    headers: { 'Content-Type': 'application/json' }
  });
}
OutputSuccess
Important Notes

Always stringify objects before sending in the response body.

Set the correct Content-Type header so browsers and clients know how to handle the data.

You can customize status codes to indicate success or errors.

Summary

Response formatting controls how your server sends data back.

Use Response with body, status, and headers for clear communication.

Always set Content-Type to match your data format.