How to Use Fetch API in Old Browsers and Node.js

For old browsers that don't support Fetch natively, you need to use a polyfill like whatwg-fetch. Here's how you can do it:

Step 1: Use whatwg-fetch

<!-- Include the polyfill for browsers that don't support fetch natively -->
<script src="https://unpkg.com/whatwg-fetch@3.5.0/dist/fetch.umd.js"></script>

<!-- Your script that uses fetch -->
<script src="your-script.js"></script>

Or you can install it using npm and import it in your JavaScript file:

npm install whatwg-fetch

Step 2: In your JavaScript file, you can use it like this:

import "whatwg-fetch";

// Your fetch code here
fetch("https://api.example.com/data")
  .then((response) => response.json())
  .then((data) => console.log(data))
  .catch((error) => console.error("Error:", error));

While writing this article, Fetch API is natively available for Node.js v21. You don’t need to do anything extra now.

But, if you are using an older version of Node.js that don't support Fetch natively, you need use a package like node-fetch. Here's how you can do it:

Step 1: Use node-fetch

You can install the "node-fetch" package using npm:

npm install node-fetch

Step 2: In your JavaScript file, you can use it like this:

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

// Your fetch code here
fetch("https://api.example.com/data")
  .then((response) => response.json())
  .then((data) => console.log(data))
  .catch((error) => console.error("Error:", error));

Get my free, weekly JavaScript tutorials

Want to improve your JavaScript fluency?

Every week, I send a new full-length JavaScript article to thousands of developers. Learn about asynchronous programming, closures, and best practices — as well as general tips for software engineers.

Join today, and level up your JavaScript every Sunday!

Thank you, Taha, for your amazing newsletter. I’m really benefiting from the valuable insights and tips you share.

- Remi Egwuda