Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

doc: improved fetch docs #57296

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions doc/api/globals.md
Original file line number Diff line number Diff line change
Expand Up @@ -531,6 +531,40 @@ changes:

A browser-compatible implementation of the [`fetch()`][] function.

```mjs
const res = await fetch('https://nodejs.org/api/documentation.json');
if (res.ok) {
const data = await res.json();
console.log(data);
}
```

The implementation is based upon [undici](https://undici.nodejs.org), an HTTP/1.1 client written from scratch for Node.js. You can figure out which version of `undici` is bundled in your Node.js process reading the `process.versions.undici` property.

## Custom dispatcher

You can use a custom dispatcher to dispatch requests passing it in fetch's options object.
The dispatcher must be compatible with `undici`'s [`Dispatcher` class](https://undici.nodejs.org/#/docs/api/Dispatcher.md).

```js
fetch(url, { dispatcher: new MyAgent() });
```

It is possible to change the global dispatcher in Node.js using:

```js
globalThis[Symbol.for('undici.globalDispatcher.1')] = yourDispatcher;
Copy link
Member

@marco-ippolito marco-ippolito Mar 12, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@nodejs/undici I think we should provide an api in Node to override the global dispatcher, its being used in the wild
https://github.com/search?q=globalThis%5BSymbol.for%28%27undici.globalDispatcher.1%27%29%5D&type=code

Copy link
Member

@mcollina mcollina Mar 12, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would not recommend to use the Symbol. Let's recommend to install undici and call setGlobalDispatcher().

@marco-ippolito we have a session for this at the collab summit in Paris.

```

## Related classes

The following globals are available to use with `fetch`:

* [`FormData`](https://nodejs.org/api/globals.html#class-formdata)
* [`Headers`](https://nodejs.org/api/globals.html#class-headers)
* [`Request`](https://nodejs.org/api/globals.html#request)
* [`Response`](https://nodejs.org/api/globals.html#response).

## Class: `File`

<!-- YAML
Expand Down
Loading