Response modification lets you change what the server sends back to the browser. This helps you add headers, change status codes, or modify the content before the user sees it.
0
0
Response modification in NextJS
Introduction
You want to add security headers like Content-Security-Policy to protect your site.
You need to set cookies or clear cookies in the response.
You want to change the status code to show errors or redirects.
You want to modify the response body before sending it to the client.
You want to add caching headers to improve performance.
Syntax
NextJS
export async function GET(request) { const response = await fetch('https://api.example.com/data'); const data = await response.json(); return new Response(JSON.stringify(data), { status: 200, headers: { 'Content-Type': 'application/json', 'Cache-Control': 'max-age=3600' } }); }
You create a new Response object to modify what is sent back.
Headers, status, and body can all be changed in the Response constructor.
Examples
Simple text response with status 200 and plain text content type.
NextJS
export async function GET() { return new Response('Hello World', { status: 200, headers: { 'Content-Type': 'text/plain' } }); }
Response with 404 status and custom status text, no body.
NextJS
export async function GET() { return new Response(null, { status: 404, statusText: 'Not Found' }); }
Sets a cookie in the response headers.
NextJS
export async function GET() { const headers = new Headers(); headers.set('Set-Cookie', 'user=123; Path=/; HttpOnly'); return new Response('Cookie set', { status: 200, headers }); }
Sample Program
This Next.js API route fetches data from an external API, then modifies the response by adding a custom header before sending it back to the client.
NextJS
export async function GET() { // Fetch data from external API const response = await fetch('https://jsonplaceholder.typicode.com/todos/1'); const data = await response.json(); // Modify response: add custom header and change status return new Response(JSON.stringify(data), { status: 200, headers: { 'Content-Type': 'application/json', 'X-Custom-Header': 'MyHeaderValue' } }); }
OutputSuccess
Important Notes
Always set the correct Content-Type header to match your response body.
You can create and modify Headers objects for more control.
Remember to handle errors when fetching or modifying responses.
Summary
Response modification lets you control what the server sends back.
You can change headers, status codes, and the response body.
This helps improve security, caching, and user experience.