Skip to content

Web request in Next.js

Posted on:November 14, 2023

Web Request in Next.js


What is web request?


Different ways of client-server communication


Restful API

Built on top of HTTP/s protocol.

When a client request is made via a RESTful API, information is delivered in one of several formats via HTTP: JSON (Javascript Object Notation), HTML, XLT, or plain text. JSON is the most generally popular file format to use because, despite its name, it’s language-agnostic, as well as readable by both humans and machines.


Try it out

Fetch API

const response = await fetch("https://www.boredapi.com/api/activity");

But what is await?


Asynchronous programming


More about requests


More about responses


Do you know JSON?

{
  "firstName": "Duke",
  "lastName": "Java",
  "age": 18,
  "streetAddress": "100 Internet Dr",
  "city": "JavaTown",
  "state": "JA",
  "postalCode": "12345",
  "phoneNumbers": [{ "Mobile": "111-111-1111" }, { "Home": "222-222-2222" }]
}

Building a RESTful API in Next.js

export default function handler(req, res) {
  if (req.method === "POST") {
    req.body.name === "" && res.status(401).json({ error: "Missing name!" });
    res.status(200).json({ msg: `Hello, ${req.body.name}` });
  } else {
    res.status(200).json({ msg: "Hello" });
  }
}

Cool JavaScript fact

&& is a short-circuit operator. It evaluates the second operand only if the first operand evaluates to true.


Sending data using fetch

const response = await fetch("/api/hello", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ name: text }),
});

JSON.stringify converts a JavaScript object to a JSON string.


Check if the response is successful:

if (!response.ok) {
  return {
    code: response.status,
    error: await data.error,
  };
}
return {
  code: response.status,
  msg: data.msg,
};

Resources