Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
N

node-fetch

> 开发工具
Open source

A light-weight module that brings the Fetch API to Node.js

8.9K stars0 likes4 views
WebsiteGitHub

About

A light-weight module that brings the Fetch API to Node.js


You might be looking for the v2 docs

  • Motivation
  • Features
  • Difference from client-side fetch
  • Installation
  • Loading and configuring the module
  • Upgrading
  • Common Usage
    • Plain text or HTML
    • JSON
    • Simple Post
    • Post with JSON
    • Post with form parameters
    • Handling exceptions
    • Handling client and server errors
    • Handling cookies
  • Advanced Usage
    • Streams
    • Accessing Headers and other Metadata
    • Extract Set-Cookie Header
    • Post data using a file
    • Request cancellation with AbortSignal
  • API
    • fetch(url[, options])
    • Options
      • Default Headers
      • Custom Agent
      • Custom highWaterMark
      • Insecure HTTP Parser
    • Class: Request
      • new Request(input[, options])
    • Class: Response
      • new Response([body[, options]])
      • response.ok
      • response.redirected
      • response.type
    • Class: Headers
      • new Headers([init])
    • Interface: Body
      • body.body
      • body.bodyUsed
      • body.arrayBuffer()
      • body.blob()
      • body.formData()
      • body.json()
      • body.text()
    • Class: FetchError
    • Class: AbortError
  • TypeScript
  • Acknowledgement
  • Team - Former
  • License

Motivation

Instead of implementing XMLHttpRequest in Node.js to run browser-specific Fetch polyfill, why not go from native http to fetch API directly? Hence, node-fetch, minimal code for a window.fetch compatible API on Node.js runtime.

See Jason Miller's isomorphic-unfetch or Leonardo Quixada's cross-fetch for isomorphic usage (exports node-fetch for server-side, whatwg-fetch for client-side).

Features

  • Stay consistent with window.fetch API.
  • Make conscious trade-off when following [WHATWG fetch spec][whatwg-fetch] and stream spec implementation details, document known differences.
  • Use native promise and async functions.
  • Use native Node streams for body, on both request and response.
  • Decode content encoding (gzip/deflate/brotli) properly, and convert string output (such as res.text() and res.json()) to UTF-8 automatically.
  • Useful extensions such as redirect limit, response size limit, [explicit errors][error-handling.md] for troubleshooting.

Difference from client-side fetch

  • See known differences:
    • As of v3.x
    • As of v2.x
  • If you happen to use a missing feature that window.fetch offers, feel free to open an issue.
  • Pull requests are welcomed too!

Installation

Current stable release (3.x) requires at least Node.js 12.20.0.

bash
npm install node-fetch

Loading and configuring the module

ES Modules (ESM)

javascript
import fetch from 'node-fetch';

CommonJS

node-fetch from v3 is an ESM-only module - you are not able to import it with require().

If you cannot switch to ESM, please use v2 which remains compatible with CommonJS. Critical bug fixes will continue to be published for v2.

bash
npm install node-fetch@2

Alternatively, you can use the async import() function from CommonJS to load node-fetch asynchronously:

javascript
// mod.cjs
const fetch = (...args) => import('node-fetch').then(({default: fetch}) => fetch(...args));

Providing global access

To use fetch() without importing it, you can patch the global object in node:

javascript
// fetch-polyfill.js
import fetch, {
  Blob,
  blobFrom,
  blobFromSync,
  File,
  fileFrom,
  fileFromSync,
  FormData,
  Headers,
  Request,
  Response,
} from 'node-fetch'

if (!globalThis.fetch) {
  globalThis.fetch = fetch
  globalThis.Headers = Headers
  globalThis.Request = Request
  globalThis.Response = Response
}

// index.js
import './fetch-polyfill'

// ...

Upgrading

Using an old version of node-fetch? Check out the following files:

  • 2.x to 3.x upgrade guide
  • 1.x to 2.x upgrade guide
  • Changelog

Common Usage

NOTE: The documentation below is up-to-date with 3.x releases, if you are using an older version, please check how to upgrade.

Plain text or HTML

javascript
import fetch from 'node-fetch';

const response = await fetch('https://github.com/');
const body = await response.text();

console.log(body);

JSON

javascript
import fetch from 'node-fetch';

const response = await fetch('https://api.github.com/users/github');
const data = await response.json();

console.log(data);

Simple Post

javascript
import fetch from 'node-fetch';

const response = await fetch('https://httpbin.org/post', {method: 'POST', body: 'a=1'});
const data = await response.json();

console.log(data);

Post with JSON

javascript
import fetch from 'node-fetch';

const body = {a: 1};

const response = await fetch('https://httpbin.org/post', {
	method: 'post',
	body: JSON.stringify(body),
	headers: {'Content-Type': 'application/json'}
});
const data = await response.json();

console.log(data);

Post with form parameters

URLSearchParams is available on the global object in Node.js as of v10.0.0. See official documentation for more usage methods.

NOTE: The Content-Type header is only set automatically to x-www-form-urlencoded when an instance of URLSearchParams is given as such:

javascript
import fetch from 'node-fetch';

const params = new URLSearchParams();
params.append('a', 1);

const response = await fetch('https://httpbin.org/post', {method: 'POST', body: params});
const data = await response.json();

console.log(data);

Handling exceptions

NOTE: 3xx-5xx responses are NOT exceptions, and should be handled in then(), see the next section.

Wrapping the fetch function into a try/catch block will catch all exceptions, such as errors originating from node core libraries, like network errors, and operational errors which are instances of FetchError. See the [error handling document][error-handling.md] for more details.

javascript
import fetch from 'node-fetch';

try {
	await fetch('https://domain.invalid/');
} catch (error) {
	console.log(error);
}

Handling client and server errors

It is common to create a helper function to check that the response contains no client (4xx) or server (5xx) error responses:

…

Handling cookies

Cookies are not stored by default. However, cookies can be extracted and passed by manipulating request and response headers. See Extract Set-Cookie Header for details.

Advanced Usage

Streams

The "Node.js way" is to use streams when possible. You can pipe res.body to another stream. This example uses stream.pipeline to attach stream error handlers and wait for the download to complete.

javascript
import {createWriteStream} from 'node:fs';
import {pipeline} from 'node:stream';
import {promisify} from 'node:util'
import fetch from 'node-fetch';

const streamPipeline = promisify(pipeline);

const response = await fetch('https://github.githubassets.com/images/modules/logos_page/Octocat.png');

if (!response.ok) throw new Error(`unexpected response ${response.statusText}`);

await streamPipeline(response.body, createWriteStream('./octocat.png'));

In Node.js 14 you can also use async iterators to read body; however, be careful to catch errors -- the longer a response runs, the more likely it is to encounter an error.

javascript
import fetch from 'node-fetch';

const response = await fetch('https://httpbin.org/stream/3');

try {
	for await (const chunk of response.body) {
		console.dir(JSON.parse(chunk.toString()));
	}
} catch (err) {
	console.error(err.stack);
}

In Node.js 12 you can also use async iterators to read body; however, async iterators with streams did not mature until Node.js 14, so you need to do some extra work to ensure you handle errors directly from the stream and wait on it response to fully close.

javascript
import fetch from 'node-fetch';

const read = async body => {
	let error;
	body.on('error', err => {
		error = err;
	});

	for await (const chunk of body) {
		console.dir(JSON.parse(chunk.toString()));
	}

	return new Promise((resolve, reject) => {
		body.on('close', () => {
			error ? reject(error) : resolve();
		});
	});
};

try {
	const response = await fetch('https://httpbin.org/stream/3');
	await read(response.body);
} catch (err) {
	console.error(err.stack);
}

Accessing Headers and other Metadata

javascript
import fetch from 'node-fetch';

const response = await fetch('https://github.com/');

console.log(response.ok);
console.log(response.status);
console.log(response.statusText);
console.log(response.headers.raw());
console.log(response.headers.get('content-type'));

Extract Set-Cookie Header

Unlike browsers, you can access raw Set-Cookie headers manually using Headers.raw(). This is a node-fetch only API.

javascript
import fetch from 'node-fetch';

const response = await fetch('https://example.com');

// Returns an array of values, instead of a string of comma-separated values
console.log(response.headers.raw()['set-cookie']);

Post data using a file

javascript
import fetch, {
  Blob,
  blobFrom,
  blobFromSync,
  File,
  fileFrom,
  fileFromSync,
} from 'node-fetch'

const mimetype = 'text/plain'
const blob = fileFromSync('./input.txt', mimetype)
const url = 'https://httpbin.org/post'

const response = await fetch(url, { method: 'POST', body: blob })
const data = await response.json()

console.log(data)

node-fetch comes with a spec-compliant [FormData] implementations for posting multipart/form-data payloads

javascript
import fetch, { FormData, File, fileFrom } from 'node-fetch'

const httpbin = 'https://httpbin.org/post'
const formData = new FormData()
const binary = new Uint8Array([ 97, 98, 99 ])
const abc = new File([binary], 'abc.txt', { type: 'text/plain' })

formData.set('greeting', 'Hello, world!')
formData.set('file-upload', abc, 'new name.txt')

const response = await fetch(httpbin, { method: 'POST', body: formData })
const data = await response.json()

console.log(data)

If you for some reason need to post a stream coming from any arbitrary place, then you can append a [Blob] or a [File] look-a-like item.

The minimum requirement is that it has:

  1. A Symbol.toStringTag getter or property that is either Blob or File
  2. A known size.
  3. And either a stream() method or a arrayBuffer() method that returns a ArrayBuffer.

The stream() must return any async iterable object as long as it yields Uint8Array (or Buffer) so Node.Readable streams and whatwg streams works just fine.

javascript
formData.append('upload', {
	[Symbol.toStringTag]: 'Blob',
	size: 3,
  *stream() {
    yield new Uint8Array([97, 98, 99])
	},
	arrayBuffer()

Issues· 249 open

View all issuesOpen on GitHub
  • #1913

    node-fetch 2.7.0 emits DEP0169 from parseURL when bundled on Node.js 24

    Updated Sep 22, 2026
  • #1590

    Dead link in release history

    Updated Jul 29, 2026
  • #1907

    {Unique} Attapoll Referral Code $20 (ORULC) Earn Up to $20 Signup Bonus And Referral

    Updated Jul 23, 2026
  • #1862

    Not able to handle ECONNREFUSED error

    bugUpdated Jun 25, 2026
  • #1767

    Malformed chunked response detector creates false-positive ‘premature close’ errors when HTTP Agent involved

    bugUpdated Jun 19, 2026
  • #1825

    308 Redirect plus multipart/form-data causes wrong boundary

    bugUpdated Apr 29, 2026
  • #1882

    Security notice: coordinated automated PR campaign targeting HTTP client libraries

    Updated Apr 8, 2026
  • #1880

    Security: Custom auth headers and proxy-authorization not stripped on cross-origin redirect

    Updated Mar 20, 2026
  • #1876

    This project is abandoned; please use the built-in fetch.

    Updated Mar 14, 2026
  • #917

    Bug: I get "TypeError: Illegal invocation" when using node-fetch@3 with electron

    bugUpdated Mar 9, 2026

> Tags

JavaScriptfetchfetch-apihacktoberfesthttp

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 29, 2026
Category开发工具
PricingOpen source

> Related tools

V
VS Code
流行的开源代码编辑器
G
Git
分布式版本控制系统
V
Vite
下一代前端构建工具