Course contentsShow
← JavaScript
Lesson 2265 of 2,72347. Networking PrimitivesFree lesson

Fetch in Node.js

Using the built-in fetch in Node 18+ or the node-fetch polyfill for earlier versions.

Fetch in Node.js

You'll learn how to use fetch in Node.js environments, whether through the built-in global or a polyfill for older versions.

The Node.js Fetch Story

For years, fetch was a browser-only feature, forcing Node.js developers to use libraries like axios or node-fetch. Starting with Node.js 18, fetch became a global built-in, meaning you can use it just like you would in the browser—no imports required.

Think of it like this: Node.js finally caught up with the browser's convenient way of making HTTP requests, so the same fetch code can now run in both environments.

Using Fetch in Node 18+

In Node.js 18 and later, fetch works exactly as you've already learned:

// No imports needed in Node 18+
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);

The global fetch is available immediately—just like console.log or Promise.

Using Fetch in Earlier Node Versions

If you're stuck on Node.js 16 or earlier, you need the node-fetch package as a polyfill:

// Install: npm install node-fetch@2
const fetch = require('node-fetch');

async function getData() {
  const response = await fetch('https://api.example.com/data');
  const data = await response.json();
  return data;
}

Note: Use node-fetch@2 for CommonJS compatibility; version 3+ is ESM-only.

Checking Your Node Version

Run node --version in your terminal. If it shows 18.0.0 or higher, you're ready to use fetch without any setup.

Key Takeaway: Node.js 18+ includes fetch as a global built-in, eliminating the need for third-party libraries in modern environments; older versions require the node-fetch polyfill.