DEV Community

Cover image for Fetch API has finally landed Node v18.0
ishan
ishan

Posted on • Updated on

Fetch API has finally landed Node v18.0

This is exciting news for Javascript developers, we can now use Fetch API in our Node application without the need of any libraries. Previously we needed to add additional packages like node-fetch or axios but we no longer need them anymore.

What is Fetch API?

The fetch API is a standard way of making web API HTTP requests. It’s a promise based which supports many high-level HTTP features, while also focusing on the most common scenario: sending simple HTTP requests.

Under the hood the API it comprises of are

fetch() entry point to initiate requests

Headers Represents response/request headers, allowing you to query them and take different actions depending on the results.

Request Represents a resource request.

Response Represents the response to a request.

Fetch API generally does work in browsers but now it does work in Node servers as well. We wont be needing any dependency as Node.js core will now support the API.

When the Fetch API is enabled, the following global functions and classes are made available: fetch(), Request, Response, Headers, FormData

Fetch implementation

Please make sure that you do have node version greater than v18.0 installed in your machine. Run the command node -v in your console to see which version you have running. If its less than 18 then you need to upgrade before you can use these new features.

We will implement three major request GET, POST, DELETE.

GET request

const getMethod = async () => {
  const res = await fetch('https://jsonplaceholder.typicode.com/posts');
  if (res.ok) {
      const data = await res.json();
      console.log(data);
  }
};

getMethod();
Enter fullscreen mode Exit fullscreen mode

POST request

  const postMethod = async () => {
    const data = {
      title: 'I love Node.js',
      body: 'Node.js is a JavaScript runtime built on Chrome\'s V8 JavaScript engine.',
      userId: 1,
    };
    const res = await fetch("https://jsonplaceholder.typicode.com/posts", {
        method: 'POST', // *GET, POST, PUT, DELETE, etc.
        mode: 'cors', // no-cors, *cors, same-origin
        cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
        credentials: 'same-origin', // include, *same-origin, omit
        headers: {
          'Content-type': 'application/json; charset=UTF-8',
            // 'Content-Type': 'application/x-www-form-urlencoded',
        },
        redirect: 'follow', // manual, *follow, error
        referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
        body: JSON.stringify(data) // body data type must match "Content-Type" header

    });
    await res.json();
};

postMethod();
Enter fullscreen mode Exit fullscreen mode

DELETE request

const deleteMethod = async () => {
  const res = await fetch("https://jsonplaceholder.typicode.com/posts/1", {
      method: 'DELETE'
});
console.log(res);
};

deleteMethod();
Enter fullscreen mode Exit fullscreen mode

Conclusion

We implemented fetch API operation with Node without the need for any library imports. The thing to note that under the hood that the fetch implementation is done based on another HTTP client, undici, which is actually a HTTP client written specifically for Node.js. It is an HTTP 1.1 only client.

This is a small improvement in the framework but brings a lot of joy for us developers. We just covered an introduction to Node.js 18 Fetch API. You can further dig deeper into this in official Node documentation here.

Happy coding!

Top comments (1)

Collapse
 
andrewbaisden profile image
Andrew Baisden

It was long overdue and a welcome new feature!