Send Custom HTTP Headers in Node.js and Browser Requests
Adding custom HTTP headers lets you convey extra metadata such as authentication tokens, locale settings, or feature flags directly with each request, giving servers the context they need to respond correctly. Whether you are building a backend service with Node.js or a front‑end application that runs in the browser, the same principle applies: you create a request object, attach the desired header name/value pairs, and then dispatch the request.
What You'll Need
- Node.js installed (v12 or newer recommended)
- A modern browser (Chrome, Firefox, Edge, Safari) for client‑side testing
- Basic knowledge of JavaScript and HTTP concepts
- Optional: npm packages like
axiosornode-fetchif you prefer a higher‑level API
Step‑By‑Step
- Choose the environment. Decide whether the code will run in Node.js or in the browser. The APIs differ slightly: Node.js offers the built‑in
http/httpsmodules, while browsers providefetchandXMLHttpRequest. - Set up a simple server to test against. Create a quick Express server (or any HTTP server) that echoes back received headers so you can verify that your custom headers arrive correctly.
const express = require('express'); const app = express(); app.use(express.json()); app.get('/echo', (req, res) => { res.json({ receivedHeaders: req.headers }); }); app.listen(3000, () => console.log('Test server listening on :3000')); - Node.js – using the native
httpsmodule.
Theconst https = require('https'); const options = { hostname: 'localhost', port: 3000, path: '/echo', method: 'GET', headers: { 'X-Custom-Token': 'abc123', 'X-Requested-With': 'MyApp' } }; const req = https.request(options, (res) => { let data = ''; res.on('data', (chunk) => data += chunk); res.on('end', () => console.log(JSON.parse(data))); }); req.on('error', (e) => console.error(e)); req.end();headersobject insideoptionsis where you place any custom name/value pairs. Node will automatically format them as "Header‑Name: value" lines. - Node.js – using
axios(recommended for most projects).const axios = require('axios'); axios.get('http://localhost:3000/echo', { headers: { 'X-User-Id': '42', 'X-Feature-Flag': 'beta' } }) .then(response => console.log(response.data)) .catch(err => console.error(err));axiosmerges the custom headers with any defaults you may have set globally, making it easy to keep a consistent header set across many calls. - Node.js – using
node-fetch(Fetch API polyfill).
The syntax mirrors the browserconst fetch = require('node-fetch'); fetch('http://localhost:3000/echo', { method: 'GET', headers: { 'X-Session-Id': 'session‑789', 'Accept-Language': 'en-US' } }) .then(res => res.json()) .then(json => console.log(json)) .catch(err => console.error(err));fetchAPI, so you can reuse the same code in both environments with minimal changes. - Browser – using the native
fetchAPI.
Browsers automatically add standard headers likefetch('http://localhost:3000/echo', { method: 'GET', headers: { 'X-Client-Version': '1.2.3', 'X-Device-Type': 'mobile' } }) .then(r => r.json()) .then(data => console.log(data)) .catch(err => console.error('Fetch error:', err));AcceptandUser-Agent. Your custom headers appear alongside them. - Browser – using
XMLHttpRequest(legacy support).
Even thoughconst xhr = new XMLHttpRequest(); xhr.open('GET', 'http://localhost:3000/echo'); xhr.setRequestHeader('X-Legacy-Header', 'legacy‑value'); xhr.setRequestHeader('X-Another-Header', 'value2'); xhr.onreadystatechange = function () { if (xhr.readyState === XMLHttpRequest.DONE) { if (xhr.status === 200) { console.log(JSON.parse(xhr.responseText)); } else { console.error('XHR error', xhr.status); } } }; xhr.send();XMLHttpRequestis older, thesetRequestHeadermethod works the same way as the newer APIs. - Handle CORS pre‑flight when sending custom headers from a browser. Browsers treat any header that is not in the "simple" whitelist (Accept, Content‑Type, etc.) as a trigger for a pre‑flight
OPTIONSrequest. The server must respond withAccess-Control-Allow-Headerslisting the custom names, otherwise the actual request will be blocked.
If you control the server, add the required header; if you do not, you cannot force the browser to send the custom header without server cooperation.// Example Express CORS setup const cors = require('cors'); app.use(cors({ origin: 'http://localhost:8080', allowedHeaders: ['Content-Type', 'X-Client-Version', 'X-Device-Type'] })); - Verify the headers on the server side. In the test server above,
req.headerscontains a lower‑cased map of all incoming headers. Look for the keys you set (e.g.,x‑custom‑token) to confirm they arrived. - Reuse a header configuration. When you have many requests that share the same set of custom headers, create a helper function.
This pattern reduces duplication and ensures consistency.function createHeaders(extra = {}) { return Object.assign({ 'X-App-Id': 'my‑app', 'X-Request-Id': crypto.randomUUID() }, extra); } // Usage with fetch fetch(url, { headers: createHeaders({ 'X-User': userId }) });
Common Mistakes
- Using illegal header names. Header names must be ASCII, cannot contain control characters, and cannot start with a colon. Names like
Content‑Lengthare managed by the runtime and should not be set manually. - Forgetting to set
Access-Control-Allow-Headerson the server. When a browser sends a custom header, the pre‑flight request will fail if the server does not explicitly whitelist the header. - Overriding essential headers unintentionally. Adding a
Content-Typeheader with an incorrect value can break JSON payload parsing on the server. - Sending headers with the wrong case. While HTTP header names are case‑insensitive, many libraries normalise them to lower case. If you later read them in a case‑sensitive context, you might miss them.
- Attempting to set headers after the request body has been sent. In
http.requestyou must callreq.setHeaderbeforereq.end(). Infetch, the headers object must be fully built before the call.
Tips
- Store frequently used values (e.g., auth tokens) in a central place like an environment variable or a dedicated module, then inject them into the header builder.
- Use
crypto.randomUUID()or a similar method to generate unique request identifiers for tracing. - When debugging, log
JSON.stringify(headers, null, 2)before sending to ensure the object shape is correct. - Leverage browser dev tools – the Network tab shows the exact request headers that were transmitted.
- In Node.js, enable the
--trace-warningsflag to surface any attempts to set forbidden headers.
Troubleshooting
Problem: The server reports that a custom header is missing.
- Check the spelling and case of the header name in your client code.
- Confirm that the request is actually reaching the server (look at the Network tab or server logs).
- If you are in a browser, verify that the server’s CORS configuration includes the header name in
Access-Control-Allow-Headers. - Make sure you are not accidentally overwriting the header with a later call to
setRequestHeaderthat uses the same name but a different value.
Problem: A pre‑flight OPTIONS request returns 403.
- Ensure the server endpoint handling
OPTIONSreturns a 200 status with the required CORS headers. - Check that the
Originheader sent by the browser matches theAccess‑Control‑Allow‑Originvalue configured on the server. - If you are using a proxy, make sure it forwards the
OPTIONSrequest unchanged.
Problem: Node.js throws ERR_INVALID_ARG_TYPE when adding headers.
- Headers must be strings. If you pass a number or object, convert it using
String(value). - Do not include undefined or null values; filter them out before constructing the header object.
Problem: The request hangs or never resolves.
- Make sure you call
req.end()(or the equivalent finish method) after setting headers and writing the body. - In fetch, verify that you are not awaiting a response that never arrives because the server is waiting for a header that never gets sent.
- Check network connectivity and firewall rules that might block the target port.
Frequently Asked Questions
Can I set the Host header manually?
In most environments the runtime sets Host automatically based on the request URL. Overriding it is discouraged and may be blocked by the library for security reasons.
Do custom headers increase request size significantly?
Each header adds a line of text (name, colon, space, value, CRLF). In typical use the overhead is negligible, but extremely large values can affect payload size limits.
Are custom headers sent with cross‑origin fetch calls by default?
Yes, but they trigger a CORS pre‑flight unless the header is part of the simple whitelist. The server must explicitly allow them.
How do I send the same header on every request without repeating code?
Create a wrapper function or configure a global interceptor (e.g., axios.interceptors.request.use) that injects the header into each outgoing config.
What is the difference between setRequestHeader and the headers option in fetch?
setRequestHeader is a method on XMLHttpRequest that mutates a mutable header collection. The headers option in fetch accepts an object, Headers instance, or iterable, and is immutable once the request is created.
Can I use custom headers with WebSocket upgrades?
WebSocket handshakes are HTTP GET requests, so you can include custom headers during the upgrade. The server must read them during the handshake phase.