node-fetch: An NPM Module to Make HTTP Requests in Node.js to Fetch API

When developing web applications, we don’t actually build everything from scratch. We may sometimes want to “outsource” certain tasks. For this, we can use APIs from other websites that offer services that we want to integrate into our application without lifting a finger!

To achieve such behaviour, our application must interact with external web servers to fetch or post data. We can use the built-in window.fetch() when using plain vanilla JavaScript. However, it is very likely that you will not be using vanilla JavaScript to build a web application. Here comes Node.js.

An important reason to use Node.js is the impeccable level of scalability it offers to applications, but we cannot use window.fetch() in the Node.js environment. The window object is undefined here. Node.js third-party module, node-fetch can be used instead.

In this article, we’ll explain how to use node-fetch to make HTTP requests, including how to install and import the package and send Get and POST Requests to the APIs in Node.js.

Making HTTP Requests in Node.js with node-fetch

In today’s technology-driven era, the ability to fetch and process data is the most important part of developing an application.

The Node.js environment provides developers with NPM that has various modules that can interact with APIs to fetch and manipulate data. One of them is the node-fetch module. 

The node-fetch module is nothing but a light-weight module that brings a method fetch() to make HTTP requests in Node.js. It provides support for the Fetch API in Node.js after which using the Fetch API in a Node.js project becomes super easy. Making API requests is easier here than with Axios or any other third-party module.

Getting Started with the node-fetch Module in Node.js

Let us now look at an example of creating HTTP requests using the node-fetch module in Node.js. We will create a new Node.js application for this project. So, let us start with the below steps.

Step 1: Start by initializing a Node.js project by executing the below command in a terminal.

$ npm init -y

If any error happens, make sure that you have Node.js installed on your system. If you successfully see a package.json file created with the above-shown default configurations, let’s move on to step 2.

Step 2: Create the index.js file where we will write code for performing requests and response operations.

$ touch index.js

Step 3: Install the node-fetch NPM module:

$ npm i node-fetch

added 5 packages, and audited 6 packages in 6s

2 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities

Here we have used “npm i”, instead of “npm install” to install the module, both are the same. It is just a shorter form.

Step 4: For using the module it is required first to import it in the file we want to use it, in our case it is “index.js”, so let’s import it here.

If you are using Common JS syntax, use the below syntax for importing the package:

const fetch = require('node-fetch');

If you prefer ESM, use this syntax for importing the package:

import fetch from 'node-fetch';

Note: If you are using node-fetch version 3.x.x, then make sure you only use ESM syntax for importing. Also, DO NOT forget to add set a key “type” with the value “module” in the package.json file:

"type": "module"

Perform an HTTP fetch

The node-fetch module method fetch() can be used to perform the HTTP fetch operation. Below is the syntax for using the fetch() method of the node-fetch module.

Syntax:

fetch(url[, options]);

Parameters:

The URL parameter simply contains the direct URL to the resource we want to retrieve. The function will throw an error if it is not an absolute URL. When we want to use fetch() for something other than a simple GET request, we use the optional options parameter.

Return:

The function returns a response object that has crucial functions and information about the response received.

Below are some of them.

  • text() – returns the body of the response as a string.
  • json() – converts the response body to a JSON object and returns an error if the body cannot be parsed.
  • status/statusText – contains details about the HTTP status code.
  • ok – equals true if the status code is 2xx (a successful request)
  • headers – an object containing response headers

Now that we have learned a bit about this module, let us proceed further to actually use it for making HTTP requests.

Sending GET Requests with node-fetch Module

Let us send a simple GET request to Google’s homepage.

Example:

fetch('https://google.com')
    .then(res => res.text())
    .then(text => console.log(text));

If you try to run the script using the node index.js command in the old Node version it will throw an error “ExperimentalWarning: The Fetch API is an experimental feature. This feature could change at any time”, so try using the below command instead.

node --experimental-modules index.js

Output:

$ node --experimental-modules index.js
<!doctype html>
<html itemscope="" itemtype="http://schema.org/WebPage" lang="en-IN">
<head>
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type">
<meta content="/images/branding/googleg/1x/googleg_standard_color_128dp.png" itemprop="image">

.... OUTPUT CUT OUT FOR THIS ARTICLE ....

Great! It seems the module is working perfectly fine!

Sending POST Request with node-fetch Module to an API

Let us now send a POST request to send data to an external web server. We will need an additional optional parameter, without which our request is simply a GET request.

We will use the method, headers, and body parameters. Let us send some data to JSONPlaceholder’s Todos.

let todo = {
    userId: 41,
    title: "read a book",
    completed: false
};

fetch('https://jsonplaceholder.typicode.com/todos', {
    method: 'POST',
    body: JSON.stringify(todo),
    headers: { 'Content-Type': 'application/json' }
}).then(res => res.json())
    .then(json => console.log(json));

Output:

$ node --experimental-modules index.js
{ userId: 41, title: 'read a book', completed: false, id: 201 }

Great! We have now successfully learned to send GET and POST requests using the node-fetch module.

Conclusion

Performing HTTP requests directly from a browser is easy, but when it comes to building a full-fledged server-side application it becomes completely different from client-side fetch. For server-side Node.js with fetch API gives advanced usage. Implementing Fetch API to Node.js can be done by using multiple third-party modules. One of them, the easier to implement is the node-fetch module. It helps those who want to send get, post, etc requests from the server side. The node-fetch module might be confusing for beginners, we recommend you give this module a try, which definitely helps you to wrap up the concept you have learned.

References

https://stackabuse.com/making-http-requests-in-node-js-with-node-fetch/

https://www.npmjs.com/package/node-fetch#installation

Aneesha S
Aneesha S
Articles: 172