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.

Introduction & Quick Summary
A script that works in the browser or in a test dies on the server:
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:
// 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.
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.xA reproducible case that fails on every unsupported runtime and passes on 18+:
// 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"))node check-fetch.mjs
npx -y node@18 check-fetch.mjs # same script, different runtimeThe 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 version | fetch global | How to enable |
|---|---|---|
| 16 and earlier | absent | install undici or node-fetch |
| 17.5 to 17.x | behind a flag | node --experimental-fetch |
| 18.x, 19.x | present, experimental | default, --no-experimental-fetch disables |
| 20.x | present | default |
| 21 and later | present, stable | default |
| Client | Import style | Node support | Notes |
|---|---|---|---|
global fetch | none | 18+ | same code as the browser |
undici | import { fetch } from "undici" | 16+ | explicit version, custom dispatchers |
node-fetch v3 | import fetch from "node-fetch" | 12.20+ | ESM only, fails from require |
node-fetch v2 | const fetch = require("node-fetch") | 10+ | CommonJS, older API surface |
axios | import axios from "axios" | 14+ | different response shape, no Web API |
| Symptom | Actual cause | Fix |
|---|---|---|
fetch is not defined on Node 16 | no global | upgrade or import undici |
| works locally, fails in Docker | image pins an old Node tag | update the base image |
works in node, fails under nodemon | a different runtime on PATH | check process.execPath |
fails only inside vm | fresh context has no Node globals | inject the constructor |
| fails only in Jest | jsdom environment without fetch | polyfill 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:
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:
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:
// CJS file, node-fetch 3
const fetch = require("node-fetch")
// Error [ERR_REQUIRE_ESM]: require() of ES Module ... not supportedUse a dynamic import, or stay on v2 if the project is CommonJS:
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:
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:
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/nodeonly. Types do not add runtime globals; theReferenceErrorremains until the process runs a version that hasfetch. - Relying on a transitive polyfill. A library that assigns
globalThis.fetchwhen 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-fetchexists only in 17.5 through 17.x and in early 18;--no-experimental-fetchdisables the global in 18 and 19 but is unnecessary in 21+, wherefetchis stable. Deno and Bun providefetchnatively, so a script that runs under one of them says nothing about Node. - Different
fetchsemantics. Node's implementation rejects some browser-only options and does not follow theredirect: "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 documentationThe Node.js documentation that defines the behaviour this guide explains.
Try matching browser tools
All toolsSmall utilities that fit Node.js work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Node.js guides
All Node.js guidesNode.js ERR_INVALID_ARG_TYPE: the argument must be of type
ERR_INVALID_ARG_TYPE is Node's validator naming a wrong argument. Read the quoted argument, validate at the boundary and default env values.
ERR_MODULE_NOT_FOUND: Cannot find module imported from an ESM file
ESM resolves specifiers literally: extensions are required, directories do not resolve to index files, and exports maps block deep imports.
Node.js Streams: Readable, Writable, Transform, and pipeline
pipe() forwards data but not errors; pipeline() destroys the chain and rejects. Backpressure is the false return from write(), and _flush that never.
Node.js: ERR_DLOPEN_FAILED invalid ELF header
Invalid ELF header means a native addon was built for another OS or architecture. Rebuild it inside the target image instead of copying node_modules.
More in Node.js
All Node.js guidesThe guides filed next to this one in Node.js, in library order.