0
0
NextJSframework~15 mins

Request modification in NextJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Modify a Request in Next.js API Route
📖 Scenario: You are building a Next.js API route that receives a JSON request with a user's name and age. You want to modify the request data by adding a new field before sending the response.
🎯 Goal: Create a Next.js API route that reads the incoming JSON request body, adds a new field isAdult based on the age, and returns the modified JSON object.
📋 What You'll Learn
Create an API route handler function named handler that accepts req and res parameters
Read the JSON body from req.body containing name and age
Add a new boolean field isAdult which is true if age is 18 or more, otherwise false
Return the modified object as JSON in the response using res.status(200).json()
💡 Why This Matters
🌍 Real World
API routes in Next.js are used to handle backend logic like processing form data, modifying requests, and sending responses in web applications.
💼 Career
Understanding how to modify request data and send JSON responses is essential for backend development in Next.js, a popular React framework used in many companies.
Progress0 / 4 steps
1
Create the API route handler function
Create an async function called handler that takes req and res as parameters.
NextJS
Need a hint?

Start by defining the function with the exact name handler and parameters req and res.

2
Extract the JSON body from the request
Inside the handler function, create a constant called data and assign it the value of req.body.
NextJS
Need a hint?

Use const data = req.body to get the JSON data sent in the request.

3
Add the isAdult field based on age
Create a new constant called modifiedData that copies all properties from data and adds a new property isAdult which is true if data.age is 18 or more, otherwise false.
NextJS
Need a hint?

Use object spread syntax { ...data, isAdult: data.age >= 18 } to add the new field.

4
Send the modified data as JSON response
Use res.status(200).json(modifiedData) to send the modified data back as a JSON response inside the handler function.
NextJS
Need a hint?

Use res.status(200).json(modifiedData) to send the response with status code 200.