0
0
NextJSframework~30 mins

Response modification in NextJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Modify HTTP Response Headers in Next.js API Route
📖 Scenario: You are building a Next.js API route that returns a JSON response. You want to add a custom HTTP header to the response to provide extra information to the client.
🎯 Goal: Create a Next.js API route that sends a JSON response with a custom HTTP header X-Custom-Header set to MyValue.
📋 What You'll Learn
Create a Next.js API route handler function named GET.
Set a custom header X-Custom-Header with the value MyValue on the response.
Return a JSON response with a message { message: 'Hello, Next.js!' }.
💡 Why This Matters
🌍 Real World
Adding custom headers is useful for sending extra information like security policies, caching instructions, or metadata to clients in web applications.
💼 Career
Understanding how to modify HTTP responses is important for backend and full-stack developers working with Next.js or other server frameworks to control client-server communication.
Progress0 / 4 steps
1
Create the API route handler function
Create an async function called GET that takes a single parameter request.
NextJS
Need a hint?

This function will handle GET requests to your API route.

2
Create the JSON response body
Inside the GET function, create a constant called jsonData and set it to the object { message: 'Hello, Next.js!' }.
NextJS
Need a hint?

This object will be sent as the JSON response body.

3
Create the Response object with custom header
Still inside the GET function, create a constant called response and set it to a new Response object. Pass JSON.stringify(jsonData) as the body, and an object with headers containing 'Content-Type': 'application/json' and 'X-Custom-Header': 'MyValue'.
NextJS
Need a hint?

The Response constructor lets you set headers along with the body.

4
Return the Response object
At the end of the GET function, return the response object.
NextJS
Need a hint?

Returning the Response sends it back to the client.