+

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

+

+

+

+

+

+
+
+
Consider supporting us on our Open Collective:
+
+
+

+
+
+---
+
+**You might be looking for the [v2 docs](https://github.com/node-fetch/node-fetch/tree/2.x#readme)**
@@ -20,32 +27,53 @@ A light-weight module that brings `window.fetch` to Node.js
- [Difference from client-side fetch](#difference-from-client-side-fetch)
- [Installation](#installation)
- [Loading and configuring the module](#loading-and-configuring-the-module)
+- [Upgrading](#upgrading)
- [Common Usage](#common-usage)
- - [Plain text or HTML](#plain-text-or-html)
- - [JSON](#json)
- - [Simple Post](#simple-post)
- - [Post with JSON](#post-with-json)
- - [Post with form parameters](#post-with-form-parameters)
- - [Handling exceptions](#handling-exceptions)
- - [Handling client and server errors](#handling-client-and-server-errors)
+ - [Plain text or HTML](#plain-text-or-html)
+ - [JSON](#json)
+ - [Simple Post](#simple-post)
+ - [Post with JSON](#post-with-json)
+ - [Post with form parameters](#post-with-form-parameters)
+ - [Handling exceptions](#handling-exceptions)
+ - [Handling client and server errors](#handling-client-and-server-errors)
+ - [Handling cookies](#handling-cookies)
- [Advanced Usage](#advanced-usage)
- - [Streams](#streams)
- - [Buffer](#buffer)
- - [Accessing Headers and other Meta data](#accessing-headers-and-other-meta-data)
- - [Extract Set-Cookie Header](#extract-set-cookie-header)
- - [Post data using a file stream](#post-data-using-a-file-stream)
- - [Post with form-data (detect multipart)](#post-with-form-data-detect-multipart)
- - [Request cancellation with AbortSignal](#request-cancellation-with-abortsignal)
+ - [Streams](#streams)
+ - [Accessing Headers and other Metadata](#accessing-headers-and-other-metadata)
+ - [Extract Set-Cookie Header](#extract-set-cookie-header)
+ - [Post data using a file](#post-data-using-a-file)
+ - [Request cancellation with AbortSignal](#request-cancellation-with-abortsignal)
- [API](#api)
- - [fetch(url[, options])](#fetchurl-options)
- - [Options](#options)
- - [Class: Request](#class-request)
- - [Class: Response](#class-response)
- - [Class: Headers](#class-headers)
- - [Interface: Body](#interface-body)
- - [Class: FetchError](#class-fetcherror)
-- [License](#license)
+ - [fetch(url[, options])](#fetchurl-options)
+ - [Options](#options)
+ - [Default Headers](#default-headers)
+ - [Custom Agent](#custom-agent)
+ - [Custom highWaterMark](#custom-highwatermark)
+ - [Insecure HTTP Parser](#insecure-http-parser)
+ - [Class: Request](#class-request)
+ - [new Request(input[, options])](#new-requestinput-options)
+ - [Class: Response](#class-response)
+ - [new Response([body[, options]])](#new-responsebody-options)
+ - [response.ok](#responseok)
+ - [response.redirected](#responseredirected)
+ - [response.type](#responsetype)
+ - [Class: Headers](#class-headers)
+ - [new Headers([init])](#new-headersinit)
+ - [Interface: Body](#interface-body)
+ - [body.body](#bodybody)
+ - [body.bodyUsed](#bodybodyused)
+ - [body.arrayBuffer()](#bodyarraybuffer)
+ - [body.blob()](#bodyblob)
+ - [body.formData()](#formdata)
+ - [body.json()](#bodyjson)
+ - [body.text()](#bodytext)
+ - [Class: FetchError](#class-fetcherror)
+ - [Class: AbortError](#class-aborterror)
+- [TypeScript](#typescript)
- [Acknowledgement](#acknowledgement)
+- [Team](#team)
+ - [Former](#former)
+- [License](#license)
@@ -53,253 +81,418 @@ A light-weight module that brings `window.fetch` to Node.js
Instead of implementing `XMLHttpRequest` in Node.js to run browser-specific [Fetch polyfill](https://github.com/github/fetch), 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 Matt Andrews' [isomorphic-fetch](https://github.com/matthew-andrews/isomorphic-fetch) or Leonardo Quixada's [cross-fetch](https://github.com/lquixada/cross-fetch) for isomorphic usage (exports `node-fetch` for server-side, `whatwg-fetch` for client-side).
+See Jason Miller's [isomorphic-unfetch](https://www.npmjs.com/package/isomorphic-unfetch) or Leonardo Quixada's [cross-fetch](https://github.com/lquixada/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](https://streams.spec.whatwg.org/) implementation details, document known differences.
-- Use native promise but allow substituting it with [insert your favorite promise library].
-- Use native Node streams for body on both request and response.
-- Decode content encoding (gzip/deflate) properly and convert string output (such as `res.text()` and `res.json()`) to UTF-8 automatically.
-- Useful extensions such as timeout, redirect limit, response size limit, [explicit errors](ERROR-HANDLING.md) for troubleshooting.
+- 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](LIMITS.md) for details.
+- See known differences:
+ - [As of v3.x](docs/v3-LIMITS.md)
+ - [As of v2.x](docs/v2-LIMITS.md)
- 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 (`2.x`)
+Current stable release (`3.x`) requires at least Node.js 12.20.0.
```sh
-$ npm install node-fetch
+npm install node-fetch
```
## Loading and configuring the module
-We suggest you load the module via `require` until the stabilization of ES modules in node:
+
+### ES Modules (ESM)
+
```js
-const fetch = require('node-fetch');
+import fetch from 'node-fetch';
```
-If you are using a Promise library other than native, set it through `fetch.Promise`:
+### 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.
+
+```sh
+npm install node-fetch@2
+```
+
+Alternatively, you can use the async `import()` function from CommonJS to load `node-fetch` asynchronously:
+
```js
-const Bluebird = require('bluebird');
+// 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:
-fetch.Promise = Bluebird;
+```js
+// 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](docs/v3-UPGRADE-GUIDE.md)
+- [1.x to 2.x upgrade guide](docs/v2-UPGRADE-GUIDE.md)
+- [Changelog](https://github.com/node-fetch/node-fetch/releases)
+
## Common Usage
-NOTE: The documentation below is up-to-date with `2.x` releases; see the [`1.x` readme](https://github.com/bitinn/node-fetch/blob/1.x/README.md), [changelog](https://github.com/bitinn/node-fetch/blob/1.x/CHANGELOG.md) and [2.x upgrade guide](UPGRADE-GUIDE.md) for the differences.
+NOTE: The documentation below is up-to-date with `3.x` releases, if you are using an older version, please check how to [upgrade](#upgrading).
+
+### Plain text or HTML
-#### Plain text or HTML
```js
-fetch('https://github.com/')
- .then(res => res.text())
- .then(body => console.log(body));
+import fetch from 'node-fetch';
+
+const response = await fetch('https://github.com/');
+const body = await response.text();
+
+console.log(body);
```
-#### JSON
+### JSON
```js
+import fetch from 'node-fetch';
+
+const response = await fetch('https://api.github.com/users/github');
+const data = await response.json();
-fetch('https://api.github.com/users/github')
- .then(res => res.json())
- .then(json => console.log(json));
+console.log(data);
```
-#### Simple Post
+### Simple Post
+
```js
-fetch('https://httpbin.org/post', { method: 'POST', body: 'a=1' })
- .then(res => res.json()) // expecting a json response
- .then(json => console.log(json));
+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
+### Post with JSON
```js
-const body = { a: 1 };
-
-fetch('https://httpbin.org/post', {
- method: 'post',
- body: JSON.stringify(body),
- headers: { 'Content-Type': 'application/json' },
- })
- .then(res => res.json())
- .then(json => console.log(json));
+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 in Node.js as of v7.5.0. See [official documentation](https://nodejs.org/api/url.html#url_class_urlsearchparams) for more usage methods.
+### Post with form parameters
+
+`URLSearchParams` is available on the global object in Node.js as of v10.0.0. See [official documentation](https://nodejs.org/api/url.html#url_class_urlsearchparams) 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:
```js
-const { URLSearchParams } = require('url');
+import fetch from 'node-fetch';
const params = new URLSearchParams();
params.append('a', 1);
-fetch('https://httpbin.org/post', { method: 'POST', body: params })
- .then(res => res.json())
- .then(json => console.log(json));
+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 for more information.
+### Handling exceptions
+
+NOTE: 3xx-5xx responses are _NOT_ exceptions, and should be handled in `then()`, see the next section.
-Adding a catch to the fetch promise chain will catch *all* exceptions, such as errors originating from node core libraries, network errors and operational errors, which are instances of FetchError. See the [error handling document](ERROR-HANDLING.md) for more details.
+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.
```js
-fetch('https://domain.invalid/')
- .catch(err => console.error(err));
+import fetch from 'node-fetch';
+
+try {
+ await fetch('https://domain.invalid/');
+} catch (error) {
+ console.log(error);
+}
```
-#### Handling client and server errors
+### 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:
```js
-function checkStatus(res) {
- if (res.ok) { // res.status >= 200 && res.status < 300
- return res;
- } else {
- throw MyCustomError(res.statusText);
- }
+import fetch from 'node-fetch';
+
+class HTTPResponseError extends Error {
+ constructor(response, ...args) {
+ super(`HTTP Error Response: ${response.status} ${response.statusText}`, ...args);
+ this.response = response;
+ }
}
-fetch('https://httpbin.org/status/400')
- .then(checkStatus)
- .then(res => console.log('will not get here...'))
+const checkStatus = response => {
+ if (response.ok) {
+ // response.status >= 200 && response.status < 300
+ return response;
+ } else {
+ throw new HTTPResponseError(response);
+ }
+}
+
+const response = await fetch('https://httpbin.org/status/400');
+
+try {
+ checkStatus(response);
+} catch (error) {
+ console.error(error);
+
+ const errorBody = await error.response.text();
+ console.error(`Error body: ${errorBody}`);
+}
```
+### 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](#extract-set-cookie-header) for details.
+
## Advanced Usage
-#### Streams
-The "Node.js way" is to use streams when possible:
+### Streams
+
+The "Node.js way" is to use streams when possible. You can pipe `res.body` to another stream. This example uses [stream.pipeline](https://nodejs.org/api/stream.html#stream_stream_pipeline_streams_callback) to attach stream error handlers and wait for the download to complete.
```js
-fetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png')
- .then(res => {
- const dest = fs.createWriteStream('./octocat.png');
- res.body.pipe(dest);
- });
+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'));
```
-#### Buffer
-If you prefer to cache binary data in full, use buffer(). (NOTE: `buffer()` is a `node-fetch`-only API)
+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.
```js
-const fileType = require('file-type');
+import fetch from 'node-fetch';
-fetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png')
- .then(res => res.buffer())
- .then(buffer => fileType(buffer))
- .then(type => { /* ... */ });
+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);
+}
```
-#### Accessing Headers and other Meta data
+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.
+
```js
-fetch('https://github.com/')
- .then(res => {
- console.log(res.ok);
- console.log(res.status);
- console.log(res.statusText);
- console.log(res.headers.raw());
- console.log(res.headers.get('content-type'));
- });
-```
+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();
+ });
+ });
+};
-#### Extract Set-Cookie Header
+try {
+ const response = await fetch('https://httpbin.org/stream/3');
+ await read(response.body);
+} catch (err) {
+ console.error(err.stack);
+}
+```
-Unlike browsers, you can access raw `Set-Cookie` headers manually using `Headers.raw()`. This is a `node-fetch` only API.
+### Accessing Headers and other Metadata
```js
-fetch(url).then(res => {
- // returns an array of values, instead of a string of comma-separated values
- console.log(res.headers.raw()['set-cookie']);
-});
+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'));
```
-#### Post data using a file stream
+### Extract Set-Cookie Header
+
+Unlike browsers, you can access raw `Set-Cookie` headers manually using `Headers.raw()`. This is a `node-fetch` only API.
```js
-const { createReadStream } = require('fs');
+import fetch from 'node-fetch';
-const stream = createReadStream('input.txt');
+const response = await fetch('https://example.com');
-fetch('https://httpbin.org/post', { method: 'POST', body: stream })
- .then(res => res.json())
- .then(json => console.log(json));
+// Returns an array of values, instead of a string of comma-separated values
+console.log(response.headers.raw()['set-cookie']);
```
-#### Post with form-data (detect multipart)
+### Post data using a file
```js
-const FormData = require('form-data');
+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)
+```
-const form = new FormData();
-form.append('a', 1);
+node-fetch comes with a spec-compliant [FormData] implementations for posting
+multipart/form-data payloads
-fetch('https://httpbin.org/post', { method: 'POST', body: form })
- .then(res => res.json())
- .then(json => console.log(json));
+```js
+import fetch, { FormData, File, fileFrom } from 'node-fetch'
-// OR, using custom headers
-// NOTE: getHeaders() is non-standard API
+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' })
-const form = new FormData();
-form.append('a', 1);
+formData.set('greeting', 'Hello, world!')
+formData.set('file-upload', abc, 'new name.txt')
-const options = {
- method: 'POST',
- body: form,
- headers: form.getHeaders()
-}
+const response = await fetch(httpbin, { method: 'POST', body: formData })
+const data = await response.json()
-fetch('https://httpbin.org/post', options)
- .then(res => res.json())
- .then(json => console.log(json));
+console.log(data)
```
-#### Request cancellation with AbortSignal
+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.
-> NOTE: You may cancel streamed requests only on Node >= v8.0.0
+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.
+
+```js
+formData.append('upload', {
+ [Symbol.toStringTag]: 'Blob',
+ size: 3,
+ *stream() {
+ yield new Uint8Array([97, 98, 99])
+ },
+ arrayBuffer() {
+ return new Uint8Array([97, 98, 99]).buffer
+ }
+}, 'abc.txt')
+```
+
+### Request cancellation with AbortSignal
You may cancel requests with `AbortController`. A suggested implementation is [`abort-controller`](https://www.npmjs.com/package/abort-controller).
An example of timing out a request after 150ms could be achieved as the following:
```js
-import AbortController from 'abort-controller';
+import fetch, { AbortError } from 'node-fetch';
+
+// AbortController was added in node v14.17.0 globally
+const AbortController = globalThis.AbortController || await import('abort-controller')
const controller = new AbortController();
-const timeout = setTimeout(
- () => { controller.abort(); },
- 150,
-);
-
-fetch(url, { signal: controller.signal })
- .then(res => res.json())
- .then(
- data => {
- useData(data)
- },
- err => {
- if (err.name === 'AbortError') {
- // request was aborted
- }
- },
- )
- .finally(() => {
- clearTimeout(timeout);
- });
+const timeout = setTimeout(() => {
+ controller.abort();
+}, 150);
+
+try {
+ const response = await fetch('https://example.com', {signal: controller.signal});
+ const data = await response.json();
+} catch (error) {
+ if (error instanceof AbortError) {
+ console.log('request was aborted');
+ }
+} finally {
+ clearTimeout(timeout);
+}
```
-See [test cases](https://github.com/bitinn/node-fetch/blob/master/test/test.js) for more examples.
-
+See [test cases](https://github.com/node-fetch/node-fetch/blob/master/test/) for more examples.
## API
@@ -311,47 +504,51 @@ See [test cases](https://github.com/bitinn/node-fetch/blob/master/test/test.js)
Perform an HTTP(S) fetch.
-`url` should be an absolute url, such as `https://example.com/`. A path-relative URL (`/file/under/root`) or protocol-relative URL (`//can-be-http-or-https.com/`) will result in a rejected `Promise`.
+`url` should be an absolute URL, such as `https://example.com/`. A path-relative URL (`/file/under/root`) or protocol-relative URL (`//can-be-http-or-https.com/`) will result in a rejected `Promise`.