Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Node.js: ReferenceError: fetch is not defined

Global fetch arrived in Node 18. An older runtime, a stripped global or a browser-only bundle explains the reference error, not a missing import.

~5 min readNode.js
#nodejs#fetch#undici#runtime-errors
Bold white headline reading FETCH UNDEFINED beside a cyan Node crate missing an amber network plug.

Introduction & Quick Summary

A script that works in the browser or in a test dies on the server:

code
ReferenceError: fetch is not defined at getUsers (/app/src/api.js:8:20) at process.processTicksAndRejections (node:internal/process/task_queues:95:5)

Quick answer: fetch is a global only on Node.js 18 and newer. On Node 16 or 17, on an older Electron main process, inside a vm context, and in some test environments, globalThis.fetch does not exist, so the identifier is unresolved. Either move the project to a supported LTS release, or import a concrete implementation instead of relying on the global:

js
// Node 18+ : nothing to import const res = await fetch("https://api.example.com/users") // any Node version import { fetch } from "undici"

This is a runtime error, not a bundler error and not a TypeScript error: the code compiles because a DOM-typed project declares fetch in lib.dom, and then the process that runs it has no such global. That split explains why the same file passes tsc and fails on the server. Below: how to confirm which Node version actually runs the code, how the alternatives differ, and the environments where an upgrade alone is not enough.

Core Mechanics, Signatures & Reproducible Setup

Node.js added an experimental fetch in 17.5 behind --experimental-fetch, enabled it by default in 18.0.0, and made it stable in 21.0.0. It is implemented with undici, the HTTP client bundled into the runtime, and exposes the WHATWG fetch, Request, Response, Headers, FormData and AbortController APIs.

bash
node -p "process.versions.node" # 16.20.2 node -e "console.log(typeof fetch)" # undefined on 16, function on 18+ node --experimental-fetch -e "console.log(typeof fetch)" # function on 17.5 through 17.x

A reproducible case that fails on every unsupported runtime and passes on 18+:

js
// check-fetch.mjs const target = "https://example.com/" if (typeof globalThis.fetch !== "function") { console.error("no fetch on", process.versions.node) process.exit(1) } const res = await fetch(target, { method: "HEAD" }) console.log(res.status, res.headers.get("content-type"))
bash
node check-fetch.mjs npx -y node@18 check-fetch.mjs # same script, different runtime

The second command is the fastest way to prove the runtime is the problem: if it passes under Node 18 and fails under the default node, no code change is needed. Note that npx node@18 spawns a different binary; it does not change the version your service manager, container or CI uses.

{ "engines": { "node": ">=20.0.0" }, "scripts": { "start": "node dist/server.js" } }

Declaring engines makes a mismatched runtime visible at install time with npm's EBADENGINE warning, which is far cheaper than the ReferenceError at request time.

Key Comparison Table

Node.js versionfetch globalHow to enable
16 and earlierabsentinstall undici or node-fetch
17.5 to 17.xbehind a flagnode --experimental-fetch
18.x, 19.xpresent, experimentaldefault, --no-experimental-fetch disables
20.xpresentdefault
21 and laterpresent, stabledefault
ClientImport styleNode supportNotes
global fetchnone18+same code as the browser
undiciimport { fetch } from "undici"16+explicit version, custom dispatchers
node-fetch v3import fetch from "node-fetch"12.20+ESM only, fails from require
node-fetch v2const fetch = require("node-fetch")10+CommonJS, older API surface
axiosimport axios from "axios"14+different response shape, no Web API
SymptomActual causeFix
fetch is not defined on Node 16no globalupgrade or import undici
works locally, fails in Dockerimage pins an old Node tagupdate the base image
works in node, fails under nodemona different runtime on PATHcheck process.execPath
fails only inside vmfresh context has no Node globalsinject the constructor
fails only in Jestjsdom environment without fetchpolyfill or switch environment

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

1. Confirm the runtime that actually executes the request

node -v in your terminal says nothing about the process serving traffic. Log both the version and the executable from inside the failing code:

js
console.error({ node: process.versions.node, exec: process.execPath, fetch: typeof globalThis.fetch, })

A container image pinned to node:16-alpine, a nvm default left behind, a systemd unit with ExecStart=/usr/bin/node, and a serverless runtime set to nodejs16.x all produce the same error while the developer's shell reports Node 22. For Cloud Functions or Lambda, the runtime version is a deployment setting, so the fix is a configuration change plus a redeploy, not a package.

2. Use undici when the runtime cannot move

When the deployed runtime is fixed, import the client explicitly. It is the same implementation Node ships, so behaviour matches a later upgrade:

js
import { fetch, Agent, setGlobalDispatcher } from "undici" setGlobalDispatcher(new Agent({ connect: { timeout: 10_000 } })) const res = await fetch("https://api.example.com/orders", { headers: { authorization: `Bearer ${token}` }, }) if (!res.ok) throw new Error(`orders: ${res.status}`)

undici also exposes Pool, ProxyAgent and MockAgent, which the global does not. Pinning its major version in package.json is what makes the behaviour reproducible across machines, since the global's version is whatever the runtime bundles.

3. node-fetch v3 and the ESM trap

node-fetch v3 is ESM only. From CommonJS the require fails with ERR_REQUIRE_ESM, which some readers mistake for the original error:

js
// CJS file, node-fetch 3 const fetch = require("node-fetch") // Error [ERR_REQUIRE_ESM]: require() of ES Module ... not supported

Use a dynamic import, or stay on v2 if the project is CommonJS:

js
const { default: fetch } = await import("node-fetch")

Mixing both clients in one process is fine, but only one of them should own the global if you assign it: globalThis.fetch = fetch in an entry file is a common polyfill, and it must run before any module that reads the global at import time.

4. TypeScript and bundler targets

A project with "lib": ["ES2022", "DOM"] gets fetch types from the DOM library, so tsc is satisfied even if the runtime is Node 16. A project with only @types/node older than 18 sees Cannot find name 'fetch' instead. Both are type-level answers to a runtime question; align them with reality:

{ "compilerOptions": { "lib": ["ES2022"], "types": ["node"], "target": "ES2022" } }

Bundlers that target node16 or inject a polyfill can also mask the issue in development while leaving the production bundle untouched. When the only difference between two environments is the bundler, compare the emitted artifact rather than the source.

5. Proxies, TLS and timeouts behave differently from the browser

Node's fetch does not read HTTP_PROXY or HTTPS_PROXY automatically, and it does not accept a self-signed certificate without configuration. Code ported from a browser or from curl therefore fails in new ways after the ReferenceError is fixed:

js
import { ProxyAgent, setGlobalDispatcher } from "undici" const proxy = process.env.HTTPS_PROXY if (proxy) setGlobalDispatcher(new ProxyAgent(proxy))

Reproducing a request with curl -v is the quickest way to separate a proxy problem from a TLS problem; the curl command generator builds the flags from a request description, and the environment variable formatter helps when a .env file holds the proxy and token together.

6. Tests and injected contexts

Jest with testEnvironment: "jsdom" provides browser globals but not always fetch; Vitest with environment: "node" on Node 16 has none at all. A vm context, a worker with vm.createContext, and some sandboxed plugin hosts start with an empty global object:

js
import vm from "node:vm" const ctx = vm.createContext({}) vm.runInContext("typeof fetch", ctx) // 'undefined' const withFetch = vm.createContext({ fetch: globalThis.fetch }) vm.runInContext("typeof fetch", withFetch) // 'function'

Inject the implementation explicitly in those tests instead of assigning a global, so the isolation the test was built for stays intact.

Common Compilation/Runtime Mistakes & Version Gotchas

  • Blaming the bundler. The error is thrown by the engine when it evaluates the identifier; no bundler change removes it, and no polyfill is applied to a Node process that never bundles.
  • Upgrading @types/node only. Types do not add runtime globals; the ReferenceError remains until the process runs a version that has fetch.
  • Relying on a transitive polyfill. A library that assigns globalThis.fetch when imported makes the code work only if that import runs first; an entry-point polyfill is explicit and survives refactors.
  • Version notes. The flag --experimental-fetch exists only in 17.5 through 17.x and in early 18; --no-experimental-fetch disables the global in 18 and 19 but is unnecessary in 21+, where fetch is stable. Deno and Bun provide fetch natively, so a script that runs under one of them says nothing about Node.
  • Different fetch semantics. Node's implementation rejects some browser-only options and does not follow the redirect: "error" behaviour in exactly the same way; after fixing the reference error, test the failure paths too.

Official documentation: fetch in Node.js globals and the Node.js 21 release announcement, which records the move to stable.

Official references

primary documentation

The Node.js documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit Node.js work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Node.js guides

More in Node.js

All Node.js guides

The guides filed next to this one in Node.js, in library order.