Next.js - Response Helpers



What are Response Helpers?

Response Helpers are methods available on Server Response Object (RES) in API routes. These methods will help you to quickly send HTTP response without manually setting headers, status codes, or JSON formatting. Response Helpers are the concepts used in pages routes of Next.js.

Response Helper Methods

Following are the response helper methods available in Next.js:

res.send()

res.send() method is used to send a text response. The method will take a string as an argument, and send the string as a text response. See the example below:

export default function handler(req, res) {
    res.send("Hello, Next.js!");
}

res.status()

res.status() method is used to set the HTTP status code of the response. The method will take a number as an argument and sets the status code to that number. For example, to set the status code to 200, you can use the following code:

export default function handler(req, res) {
    res.status(200).send("Success!");
}

res.json()

res.json() method is used to send JSON response. The method will take an object as an argument and sends the object as a JSON response. For example, to send a JSON response with a message, you can use the following code:

export default function handler(req, res) {
    res.json({ message: "Hello, Next.js!" });
}

res.redirect()

res.redirect() method is used to redirect the client to a new URL. The method will take a string as an argument and redirects the client to the specified URL.

export default function handler(req, res) {
    res.redirect("/about");
}

Create a Simple API with Response Helpers

As we discussed above, Response Helpers are used to make HTTP responses in API routes. The code below shows how to create a simple API with Response Helpers.

// /page/api/action.ts

export default function handler(req, res) {
    const { method } = req;

    if (method === "GET") {
        res.status(200).json({ message: "GET request received." });
    } else if (method === "POST") {
        res.status(201).send("POST request received.");
    } else {
        res.status(405).end(); // Method Not Allowed
    }
}

Output

The image below shows the output of the code above.

Next.js Response Helpers Simple API
Advertisements