Next.js fetch vs Axios

December 3, 2023 by
Next.js fetch vs Axios
Hamed Mohammadi
| No comments yet

Next.js extends the native Web fetch() API to allow each request on the server to set its own persistent caching semantics.

Axios is a simple promise based HTTP client for the browser and node.js. Axios provides a simple to use library in a small package with a very extensible interface.

In this article we compare fetch and Axios for making HTTP requests in JavaScript.

  1. Fetch API:

    • The Fetch API is built into modern browsers and provides a way to make network requests.
    • It is readily available in all modern browsers.
    • Fetch uses the fetch() method defined on the window object.
    • Basic syntax for sending a POST request with custom headers using Fetch:
      const url = "https://jsonplaceholder.typicode.com/todos";
      const options = {
        method: "POST",
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json;charset=UTF-8",
        },
        body: JSON.stringify({ a: 10, b: 20 }),
      };
      
      fetch(url, options)
        .then((response) => response.json())
        .then((data) => {
          console.log(data);
        });
      
    • Fetch requires manual parsing of the response data using .json() method.
    • It is capable of reproducing key features of Axios.
  2. Axios:

    • Axios is a popular library for making HTTP requests.
    • It provides an easy-to-use interface and automatic data transformation.
    • Axios automatically converts data to JSON and handles response data.
    • Basic syntax for sending a POST request with custom headers using Axios:
      const url = "https://jsonplaceholder.typicode.com/posts";
      const data = { a: 10, b: 20 };
      
      axios
        .post(url, data, {
          headers: {
            Accept: "application/json",
            "Content-Type": "application/json;charset=UTF-8",
          },
        })
        .then(({ data }) => {
          console.log(data);
        });
      
    • Axios simplifies error handling and response data access.
    • It’s a better choice for projects that require proper error handling.

In summary, if you’re building a small project with one or two requests, using fetch is fine. However, for easy and proper error handling, Axios is a better solution.

Next.js fetch vs Axios
Hamed Mohammadi December 3, 2023
Share this post
Tags
Archive
Sign in to leave a comment