User Agents

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 axios or node-fetch if you prefer a higher‑level API

Step‑By‑Step

  1. 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/https modules, while browsers provide fetch and XMLHttpRequest.
  2. 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'));
    
  3. Node.js – using the native https module.
    const 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();
    
    The headers object inside options is where you place any custom name/value pairs. Node will automatically format them as "Header‑Name: value" lines.
  4. 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));
    
    axios merges the custom headers with any defaults you may have set globally, making it easy to keep a consistent header set across many calls.
  5. Node.js – using node-fetch (Fetch API polyfill).
    const 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));
    
    The syntax mirrors the browser fetch API, so you can reuse the same code in both environments with minimal changes.
  6. Browser – using the native fetch API.
    fetch('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));
    
    Browsers automatically add standard headers like Accept and User-Agent. Your custom headers appear alongside them.
  7. Browser – using XMLHttpRequest (legacy support).
    const 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();
    
    Even though XMLHttpRequest is older, the setRequestHeader method works the same way as the newer APIs.
  8. 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 OPTIONS request. The server must respond with Access-Control-Allow-Headers listing the custom names, otherwise the actual request will be blocked.
    // Example Express CORS setup
    const cors = require('cors');
    app.use(cors({
      origin: 'http://localhost:8080',
      allowedHeaders: ['Content-Type', 'X-Client-Version', 'X-Device-Type']
    }));
    
    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.
  9. Verify the headers on the server side. In the test server above, req.headers contains a lower‑cased map of all incoming headers. Look for the keys you set (e.g., x‑custom‑token) to confirm they arrived.
  10. Reuse a header configuration. When you have many requests that share the same set of custom headers, create a helper function.
    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 }) });
    
    This pattern reduces duplication and ensures consistency.

Common Mistakes

  • Using illegal header names. Header names must be ASCII, cannot contain control characters, and cannot start with a colon. Names like Content‑Length are managed by the runtime and should not be set manually.
  • Forgetting to set Access-Control-Allow-Headers on 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-Type header 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.request you must call req.setHeader before req.end(). In fetch, 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-warnings flag 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 setRequestHeader that uses the same name but a different value.

Problem: A pre‑flight OPTIONS request returns 403.

  • Ensure the server endpoint handling OPTIONS returns a 200 status with the required CORS headers.
  • Check that the Origin header sent by the browser matches the Access‑Control‑Allow‑Origin value configured on the server.
  • If you are using a proxy, make sure it forwards the OPTIONS request 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.