Node-Fetch
Node-Fetch brings the Web Fetch API to Node.js, providing a familiar interface for making HTTP requests in a Node.js environment. The current stable version is 3.3.2. Both the v3 (ESM-only) and v2 (CommonJS) branches are actively maintained, receiving regular bug fixes and occasional new features.
Common errors
-
ReferenceError: require is not defined
cause Attempting to use `require('node-fetch')` in a project configured for ECMAScript Modules (ESM) or a `.mjs` file when using Node-Fetch v3.fixChange `const fetch = require('node-fetch');` to `import fetch from 'node-fetch';`. Ensure your `package.json` has `"type": "module"` or use `.mjs` file extension. -
TypeError: Only absolute URLs are supported
cause Passing a relative URL (e.g., `/api/data`) to `fetch` without providing a base URL or being in a browser-like environment.fixProvide a full, absolute URL (e.g., `https://example.com/api/data`) or construct one using `new URL(relativePath, baseUrl)` before passing it to `fetch`. -
FetchError: request to http://localhost:3000/api/data failed, reason: connect ECONNREFUSED 127.0.0.1:3000
cause The server or resource you are trying to reach is not running, is inaccessible, or is blocking the connection.fixVerify that the target server is running and accessible at the specified URL and port. Check firewall rules or proxy settings if applicable. -
TypeError: Response body stream already consumed
cause Attempting to call `response.json()`, `response.text()`, `response.blob()`, etc., more than once on the same `Response` object.fixStore the result of the first body consumption (e.g., `const data = await response.json();`) into a variable. If you need to read the body in multiple formats or multiple times, use `const clonedResponse = response.clone();` before the first consumption. -
FetchError: AbortError: The user aborted a request.
cause A `fetch` request was cancelled using an `AbortController`'s `signal.abort()` method, often due to a configured timeout or explicit cancellation.fixThis is often an expected error for timeouts. Catch `AbortError` specifically (e.g., `if (error instanceof AbortError) { console.log('Request timed out'); }`) to handle it gracefully without crashing your application.
Warnings
- breaking Node-Fetch v3 is an ECMAScript Module (ESM) and does not support CommonJS `require()` syntax directly. If you are in a CommonJS project, you must use dynamic `import()` or revert to `node-fetch` v2.
- gotcha Unlike some HTTP clients, `node-fetch` does not automatically throw an error for non-successful HTTP status codes (e.g., 404, 500). You must explicitly check `response.ok` or `response.status`.
- gotcha The `Response` body is a stream and can only be consumed once. Attempting to call methods like `response.json()`, `response.text()`, or `response.blob()` multiple times will result in an error.
- gotcha `node-fetch` (mimicking the browser Fetch API) does not have a built-in timeout option for requests. Long-running requests can hang indefinitely.
- gotcha Node-Fetch v3 officially requires Node.js v16 or greater for full support. Using it on older Node.js versions might lead to unexpected issues, despite what older `engines` fields might imply.
Install
-
npm install node-fetch -
yarn add node-fetch -
pnpm add node-fetch
Imports
- fetch
const fetch = require('node-fetch');import fetch from 'node-fetch';
- Headers
import { Headers } from 'node-fetch'; - Request
import { Request } from 'node-fetch'; - Response
import { Response } from 'node-fetch'; - AbortController
import { AbortController } from 'node-fetch'; - AbortError
import { AbortError } from 'node-fetch';
Quickstart
import fetch from 'node-fetch';
async function getTodoItem() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
console.log('Fetched TODO item:', data);
} catch (error) {
console.error('Error fetching data:', error);
}
}
getTodoItem();