Fix JavaScript ReferenceError: fetch is not defined (2025 Guide)

Fix ReferenceError: fetch is not defined in JavaScript - 2025 Guide
Posted on: March 24, 2025
Getting a "ReferenceError: fetch is not defined" in JavaScript? It’s because fetch
isn’t available in Node.js by default. Let’s fix it fast in this 2025 guide!
What Causes "ReferenceError: fetch is not defined"?
This error occurs when you use the fetch
API in Node.js, where it’s not natively supported (prior to Node.js 18). Common causes:
- Node.js Environment:
fetch
is a browser API, not part of older Node.js core. - Missing Library: No external
fetch
implementation installed. - Environment Confusion: Mixing browser and Node.js code.
Test this locally (create main.js
and run node main.js
):
// main.js
fetch('https://api.example.com')
.then(response => response.json())
.then(data => console.log(data));
// Run: node main.js
This will throw "ReferenceError: fetch is not defined."
Check a browser-compatible fetch demo (open console with F12):
How to Fix It: 3 Solutions
Let’s resolve this error with practical steps:

(Diagram: Developer uses fetch, gets error, adds node-fetch, runs successfully.)
Solution 1: Use node-fetch in Node.js
Install and use the node-fetch
package:
// Run: npm install node-fetch
const fetch = require('node-fetch');
fetch('https://api.example.com')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
Install with npm install node-fetch
and require it.
Solution 2: Use Undici (Node.js Built-in)
Use Node.js 18+ built-in undici
fetch alternative:
const { fetch } = require('undici');
fetch('https://api.example.com')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
Available in Node.js 18+ without additional installation.
Solution 3: Switch to Browser Environment
If possible, run the code in a browser:
fetch
is natively supported in browsers.
Quick Checklist
- Node.js environment? (Install node-fetch or use undici)
- Browser possible? (Use native fetch)
- Correct setup? (Verify package installation)
Conclusion
A "ReferenceError: fetch is not defined" is a common issue in Node.js, but with these 2025 solutions, you’ll handle API calls smoothly. Got another JavaScript error to solve? Let us know in the comments!
Comments
Post a Comment