Node.js Reference ยท Web APIs in Node.js
Node.js fetch() function
Reference for the global fetch() in Node.js: send GET and POST requests, read JSON and streams, handle errors, redirects, timeouts and aborts.
fetch() sends an HTTP request and returns a promise for a Response. It is a global function in Node.js and follows the same standard as the browser version, so code that uses it is portable. Node implements it with the bundled undici HTTP client.
The promise resolves as soon as the response headers arrive. The body is read separately with response.json(), response.text() and similar methods, or as a stream. A response with status 404 or 500 is not an error for fetch(): the promise only rejects for network failures, aborts and invalid requests.
const response = await fetch('http://localhost:3000/data'); const data = await response.json();
Try it
The examples start a small HTTP server on loopback, because the example runner has no outside network. The fetch() calls are exactly what you would write against a real API.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Syntax
fetch(resource[, init]): Promise<Response>
| Name | Description |
|---|---|
resource |
A URL string, a URL object or a Request. URLs must be absolute; there is no base URL in Node. |
init.method |
HTTP method, default 'GET'. |
init.headers |
A Headers object, a plain object or an array of [name, value] pairs. |
init.body |
A string, Buffer/typed array, ArrayBuffer, Blob, FormData, URLSearchParams or ReadableStream. Not allowed with GET or HEAD. |
init.signal |
An AbortSignal to cancel the request. |
init.redirect |
'follow' (default), 'manual' or 'error'. |
init.duplex |
Must be 'half' when body is a stream. |
init.keepalive, init.cache, init.credentials, init.mode, init.referrer, init.integrity |
Accepted for compatibility; most have no effect outside browsers. |
init.dispatcher |
A non-standard undici option: the agent or pool that makes the connection (proxies, timeouts, mock agents). |
Returns: a promise for a Response.
Errors: the promise rejects with a TypeError whose message is fetch failed and whose cause holds the underlying error (ECONNREFUSED, ENOTFOUND, UND_ERR_CONNECT_TIMEOUT, a certificate error and so on). An aborted request rejects with AbortError (or TimeoutError for AbortSignal.timeout()), or with the reason you pass to abort(). A malformed URL or illegal combination (such as a GET with a body) rejects with a TypeError as well.
Usage notes
- Check
response.ok. Statuses 200 to 299 giveok === true. Anything else, including 4xx and 5xx, still resolves, so test the status before parsing. - Always consume or cancel the body. An unread body keeps the connection busy. Call
await response.text(),await response.arrayBuffer(), orawait response.body.cancel()when you do not need the content. - A body can be read once. Use
response.clone()first if you need it twice. SeeResponse. - Set no
Content-TypeforFormData. Node adds the multipart boundary for you; setting the header yourself breaks it. - There is no built-in timeout apart from undici's connect and header limits (about 5 minutes for headers). Pass
AbortSignal.timeout(ms)for any request that must finish in time. - Redirects: up to 20 are followed;
redirect: 'manual'in Node gives you the real 3xx response (not an opaque one as in browsers). - Cookies are not stored. Node has no cookie jar; read
response.headers.getSetCookie()and send aCookieheader yourself. - Proxies and custom TLS are configured through undici, with a
dispatcher, not withfetch()options; seeundici. - Streaming uploads need
duplex: 'half'whenbodyis aReadableStreamor async iterable. - Added in Node 18 (experimental), stable since Node 21, with Node 24 using a recent undici.
Related
Headers,Request,Response,FormData,AbortSignal,undici- Lessons: The HTTP client, Abort signals