Documentation Python quickstart Blog Free tools Enterprise solutions hello@quanticdata.ioLog in

Node fetch headers: the defaults, setting your own and reading the response

The request headers Node.js sends by default, echoed by a server on 20 November 2026: the built-in fetch of Node 22 sent 6 headers with User-Agent node, and the node-fetch 2.7.0 package sent 4; the code window shows a fetch call with Authorization and User-Agent set, and the card lists the default values.
The request headers Node.js sends by default, echoed by a server on 20 November 2026: the built-in fetch of Node 22 sent 6 headers with User-Agent node, and the node-fetch 2.7.0 package sent 4; the code window shows a fetch call with Authorization and User-Agent set, and the card lists the default values.

In Node.js, pass request headers to fetch in the headers option, as a plain object, an array of pairs or a Headers instance: fetch(url, { headers: { Authorization: 'Bearer ...' } }). Read response headers with res.headers.get('content-type'). With no option at all, Node 22 sends six headers, including User-Agent: node.

Everything below was run on 20 November 2026 with Node v22.23.2 against httpbin.org, which echoes the headers it receives, directly and through a QuanticData Residential Premium line. Two clients are covered: the fetch built into Node (available without a flag since Node 18) and the older node-fetch package.

The default headers of Node fetch

const res = await fetch('https://httpbin.org/headers');
console.log((await res.json()).headers);
{
  "Accept": "*/*",
  "Accept-Encoding": "br, gzip, deflate",
  "Accept-Language": "*",
  "Host": "httpbin.org",
  "Sec-Fetch-Mode": "cors",
  "User-Agent": "node"
}

Six headers. Through the proxy the site received exactly the same six: the proxy login travels in a separate header to the proxy and does not reach the site.

import { ProxyAgent } from 'undici';
const dispatcher = new ProxyAgent('http://USER-country-us:PASS@residentialpremium.quanticdata.io:8080');
const res = await fetch('https://httpbin.org/headers', { dispatcher });   // same six headers, User-Agent: node

The names of the client differ with what you import, which matters if a server or a log filters on User-Agent:

ClientHeaders sentUser-AgentAccept-Encoding
Built-in fetch, Node v22.23.26nodebr, gzip, deflate
fetch imported from the undici package6undicibr, gzip, deflate
node-fetch 2.7.04node-fetch/1.0 (+https://github.com/bitinn/node-fetch)gzip,deflate

node-fetch sends no Accept-Language and no Sec-Fetch-Mode. How these compare with curl, Python and a browser is in HTTP headers explained; the proxy agent for each client is set up in node-fetch and fetch through a proxy.

Set headers on a request

Give headers an object. Names can be written in any case:

const res = await fetch('https://httpbin.org/headers', { dispatcher, headers: {
  'Accept': 'application/json', 'Accept-Language': 'en-US,en;q=0.9',
  'User-Agent': 'price-monitor/1.0 (+https://example.com/bot)',
  'Authorization': 'Bearer TOKEN123', 'x-client-tag': 'run-42' } });
console.log(res.status, JSON.stringify((await res.json()).headers, null, 2));
200 {
  "Accept": "application/json",
  "Accept-Encoding": "br, gzip, deflate",
  "Accept-Language": "en-US,en;q=0.9",
  "Authorization": "Bearer TOKEN123",
  "Host": "httpbin.org",
  "Sec-Fetch-Mode": "cors",
  "User-Agent": "price-monitor/1.0 (+https://example.com/bot)",
  "X-Client-Tag": "run-42"
}

Our values replaced the defaults for Accept, Accept-Language and User-Agent; the two new headers were added; the defaults we did not mention stayed. A User-Agent that names your program and gives a contact address, as here, is the honest choice for a script: the site's operator can see who is calling and reach you. You can check what any client sends with our user agent checker.

Authorization

The most searched case is a token. Bearer tokens and Basic credentials are both ordinary headers:

headers: { Authorization: 'Bearer ' + token }
headers: { Authorization: 'Basic ' + Buffer.from(user + ':' + pass).toString('base64') }

The Bearer form is what the echo above shows arriving; the Basic form, tested with the pair user and pass, arrived as Authorization: Basic dXNlcjpwYXNz. Keep tokens out of the source file (an environment variable is enough) and send them only over https:// URLs.

An array of pairs, and repeated names

const r2 = await fetch('https://httpbin.org/headers', { dispatcher,
  headers: [['Accept', 'text/html'], ['X-Client-Tag', 'a'], ['x-client-tag', 'b']] });
  "Accept": "text/html",
  "X-Client-Tag": "a, b"

The same name given twice, in different case, became one header with the values joined by a comma. Names are case-insensitive; the array form is how you send a repeated header on purpose.

The Headers object

Headers is a global class in Node. It is what res.headers is, and you can build one for a request:

const h = new Headers({ 'Content-Type': 'application/json' });
h.set('X-Trace', 'one');
h.append('Accept', 'application/json');
h.append('Accept', 'text/plain');
console.log(h.get('accept'), h.has('CONTENT-TYPE'), [...h]);
h.delete('x-trace');
console.log([...h.keys()]);
application/json, text/plain true [
  [ 'accept', 'application/json, text/plain' ],
  [ 'content-type', 'application/json' ],
  [ 'x-trace', 'one' ]
]
[ 'accept', 'content-type' ]
MethodWhat it did in the run
set(name, value)Created x-trace; on an existing name it replaces the value
append(name, value)Added a second Accept value: "application/json, text/plain"
get(name)Returned the joined value, whatever the case of the name
has(name)true for "CONTENT-TYPE" although it was set as "Content-Type"
delete(name)Removed x-trace
Iteration ([...h], keys(), entries())Names in lower case, sorted alphabetically

The class also validates. A name with a space, or a value with a line break, is refused before any request is made:

TypeError: Headers.append: "bad name" is an invalid header name.
TypeError: Headers.append: "line1
line2" is an invalid header value.

That second check is a safety feature: a line break inside a value is how header injection works, so never strip the error, fix the value.

Headers that fetch sets for you

Some headers describe the body or the connection, and fetch fills them in. A POST with a string body and no headers at all:

await fetch('https://httpbin.org/post', { dispatcher, method: 'POST', body: JSON.stringify({ q: 'proxy' }) });
  "Content-Length": "13",
  "Content-Type": "text/plain;charset=UTF-8",

The length is right; the type is not what a JSON API expects. This is the most common fetch bug: a string body is labelled plain text. Say what it is, and the server parses it:

await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ q: 'proxy' }) });      // server-side: "json": { "q": "proxy" }

await fetch(url, { method: 'POST', body: new URLSearchParams({ q: 'proxy' }) });
// Content-Type: application/x-www-form-urlencoded;charset=UTF-8, server-side: "form": { "q": "proxy" }

A URLSearchParams body got the form type by itself. We also tried to override the headers that belong to the transport, and to send the ones a browser forbids to scripts:

Header we setWhat the server received
Cookie: session=abcSent as written
Referer, OriginSent as written
Accept-Encoding: identitySent as written, replacing "br, gzip, deflate"
Host: example.orgHost: httpbin.org: taken from the URL, ours was not used
Sec-Fetch-Mode: navigatecors: set by fetch
Content-Length: 5, Connection: closeNeither appeared on a request without a body

So in Node, unlike in a browser page, a script may set Cookie and Referer itself. There is no cookie jar in fetch: a cookie you want to send back is a header you write. What cookies are and how they return is in HTTP cookies explained.

Read the response headers

const r = await fetch('https://httpbin.org/response-headers?X-Demo=1&Set-Cookie=a%3D1&Set-Cookie=b%3D2', { dispatcher });
r.status                          // 200
r.headers.get('Content-Type')     // 'application/json'
r.headers.get('content-type')     // 'application/json'
r.headers.get('x-demo')           // '1'
r.headers.get('x-nope')           // null
r.headers.get('set-cookie')       // 'a=1, b=2'
r.headers.getSetCookie()          // [ 'a=1', 'b=2' ]
Object.fromEntries(r.headers)['set-cookie']   // 'b=2'
  • get() ignores case and returns null for a header that is absent, so test for null, not for an empty string.
  • Several Set-Cookie lines need getSetCookie(). get() joined the two cookies with a comma, which cannot be split safely because cookie dates contain commas. getSetCookie() returned them as an array.
  • Converting to a plain object loses repeats. Object.fromEntries(r.headers) kept only the last cookie. Convert for logging if you like, never for cookies.

On a real site the list is longer. A HEAD request, which asks for the headers without the body, to www.wikipedia.org through the same proxy line:

const w = await fetch('https://www.wikipedia.org/', { dispatcher, method: 'HEAD' });
console.log(w.status, [...w.headers].length, w.headers.get('content-type'),
  w.headers.get('content-encoding'), w.headers.getSetCookie().length);
200 25 text/html gzip 5

Twenty-five header lines, five of them cookies. Useful ones for a scraper are content-type (is this HTML or JSON?), cache-control and etag (may I reuse my copy?), and retry-after with the ratelimit family when a server asks you to slow down, covered in rate limiting. The body, once you have decided to read it, goes to reading JSON in JavaScript or to a parser as in web scraping with cheerio.

Headers in node-fetch

The node-fetch package predates the built-in and is still in many projects. Request headers are set the same way. The differences we saw with version 2.7.0:

const nodeFetch = require('node-fetch');
const { HttpsProxyAgent } = require('https-proxy-agent');
const agent = new HttpsProxyAgent('http://USER-country-us:PASS@residentialpremium.quanticdata.io:8080');

const r = await nodeFetch('https://httpbin.org/response-headers?Set-Cookie=a%3D1&Set-Cookie=b%3D2', { agent });
r.headers.get('set-cookie')        // 'a=1, b=2'
r.headers.raw()['set-cookie']      // [ 'a=1', 'b=2' ]
Built-in fetch (Node 22)node-fetch 2.7.0
InstallNothingnpm install node-fetch
Default headers6, User-Agent node4, User-Agent node-fetch/1.0 (+https://github.com/bitinn/node-fetch)
Proxy optiondispatcher (undici ProxyAgent)agent (https-proxy-agent)
Several Set-Cookieheaders.getSetCookie()headers.raw()['set-cookie']

If you use Axios instead, its header and proxy options are in Axios through a proxy.

Headers through a proxy

All the proxied requests above went through one Residential Premium line with the country set to the United States in the username, and the echo shows what that means for headers: the site received what our code set and what fetch adds, nothing about the proxy. The proxy changes the address the request comes from; the headers stay yours to write. Plans and countries for residential proxies and mobile proxies are on their pages.

Sources & further reading

FAQ

Quick answers on node fetch headers.

Something else? Ask us

How do I set headers in Node fetch?

Pass a headers option: fetch(url, { headers: { 'Accept': 'application/json', 'Authorization': 'Bearer TOKEN' } }). It accepts a plain object, an array of name and value pairs, or a Headers instance. In our test the server echoed every header we set.

What headers does Node fetch send by default?

Six on Node v22.23.2: Accept: */*, Accept-Encoding: br, gzip, deflate, Accept-Language: *, Host, Sec-Fetch-Mode: cors and User-Agent: node. The node-fetch 2.7.0 package sent four, with its own User-Agent.

How do I read response headers in Node fetch?

Use res.headers.get('content-type'); the name can be in any case and a missing header gives null. Iterate with for (const [name, value] of res.headers). A HEAD request to www.wikipedia.org returned 25 headers in our run.

How do I send an Authorization header with fetch in Node?

Add it to headers: Authorization: 'Bearer ' + token, or for Basic auth 'Basic ' + Buffer.from(user + ':' + pass).toString('base64'). Use an https:// URL so the token is encrypted in transit.

How do I get all Set-Cookie headers in Node fetch?

Call res.headers.getSetCookie(), which returns an array: ['a=1', 'b=2'] in our test. get('set-cookie') joins them with a comma. In node-fetch 2 use res.headers.raw()['set-cookie'].

Can I change the User-Agent of Node fetch?

Yes, set 'User-Agent' in headers; it replaces the default node. Our request arrived with price-monitor/1.0 (+https://example.com/bot). A string that names your program and a contact address lets site operators identify it.

Why does my JSON POST arrive as text/plain?

Because a string body gets Content-Type: text/plain;charset=UTF-8 by default, as our echo showed. Add 'Content-Type': 'application/json' to the headers; the server then parsed the body as JSON.

Send your Node requests from the country you need

Residential and mobile proxies with the country in the username; your headers arrive as you wrote them.

Related reading