October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
Axios

Axios Set Headers: The Complete Guide for 2026

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Set an Axios request header in the request configuration: await axios.get('/api/data', { headers: { 'X-Request-ID': 'abc123' } }); Use an Axios instance for stable headers shared by one API, and a request interceptor for values that must be calculated at request time, such as a refreshed access token. Axios resolves configuration from library defaults, then instance defaults, then the individual request, with later values taking precedence.

Set a header on one Axios request

Every Axios request method accepts a configuration object. For GET, the configuration is the second argument. For POST, it follows the request body.

import axios from 'axios';

const response = await axios.get('/api/data', {
  headers: {
    'X-Request-ID': 'abc123',
    Authorization: `Bearer ${token}`,
  },
});

await axios.post('/users', { name: 'Ada' }, {
  headers: { 'X-Request-ID': requestId },
});

This is the clearest choice when a header applies to one endpoint, one operation, or one temporary override. Keep request-specific values beside the call that uses them.

Choose the right header scope

Use request configuration for one-off values

A request-level headers object is explicit and has the highest precedence. It is suitable for an idempotency key, correlation ID, upload-specific media type, or a token that should not be reused by other calls.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use an Axios instance for one API

Create a client when several calls share a base URL and stable headers:

import axios from 'axios';

const api = axios.create({
  baseURL: 'https://api.example.com',
  headers: {
    'X-App-Version': '2.0.0',
  },
});

api.defaults.headers.common['Authorization'] = `Bearer ${token}`;

const { data } = await api.get('/users');

An instance keeps credentials and defaults attached to the service that needs them. Avoid placing an authorization token in axios.defaults.headers.common when the same global client might call multiple domains: that global value can be sent to every such domain. Axios’s official repository documents this configuration model and precedence at github.com/axios/axios.

Use a request interceptor for dynamic values

An interceptor runs as a request is prepared, so it can read the current token rather than a value captured when the client was created:

const api = axios.create({ baseURL: 'https://api.example.com' });

api.interceptors.request.use((config) => {
  const token = getAuthToken();
  config.headers.set('Authorization', `Bearer ${token}`);
  return config;
});

Axios initializes the headers object during interceptor and transformer processing. Prefer config.headers.set() with modern Axios rather than assigning properties directly. If the interceptor performs only synchronous work, Axios also documents a synchronous: true interceptor option; otherwise the default asynchronous behavior is acceptable.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Understand Axios configuration precedence

Axios merges configuration in this order:

  1. Library defaults.
  2. Defaults on the Axios instance.
  3. The configuration supplied to the individual request.

The later layer wins when the same setting is supplied more than once. Consequently, this request overrides the instance’s value:

const api = axios.create({
  headers: { 'X-Environment': 'production' },
});

await api.get('/status', {
  headers: { 'X-Environment': 'staging' },
});

The request body is separate from headers. data belongs to a particular request and is not inherited or deep-merged from defaults.

Work with AxiosHeaders safely

HTTP header names are case-insensitive. Axios’s AxiosHeaders API provides set, get, has, iteration, and conversion to JSON-compatible values. Axios preserves the existing spelling of a matching header for presentation, but servers do not treat X-Trace-ID and x-trace-id as different names.

api.interceptors.request.use((config) => {
  config.headers.set('X-Trace-ID', makeTraceId());
  return config;
});

set(name, value, rewrite) controls replacement. The default replaces an existing value unless that value is marked false; false refuses replacement, and true forces it. Axios uses null and false as internal skip or opt-out markers rather than ordinary strings sent on the wire. Use these controls only when a real default-versus-override conflict requires them.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

FormData: do not hard-code the multipart boundary

In browsers, web workers, and React Native, leave Content-Type unset when sending FormData. The runtime adds a boundary parameter, for example multipart/form-data; boundary=..., which the server needs to parse the body.

const form = new FormData();
form.append('avatar', file);
form.append('description', 'Profile image');

await axios.post('/profile', form);

Setting only Content-Type: multipart/form-data manually can omit the boundary and produce an unreadable upload. Axios also supports setting a header value to false to opt out of a header it might otherwise install, allowing the browser to choose the correct FormData content type.

In Node.js, some FormData implementations expose getHeaders(). Axios copies those headers by default for v1 compatibility. For custom or untrusted Node FormData, the documented formDataHeaderPolicy: 'content-only' copies only Content-Type and Content-Length; add any other headers explicitly in the request configuration. Check the option against the Axios release installed in your project because the v1 branch is mutable.

Browser CORS can block a correctly written header

Axios cannot override browser networking policy. A cross-origin custom header commonly triggers an OPTIONS preflight. The server must allow the requesting origin, method, and header name before the browser sends the actual request.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Authorization needs explicit permission

For a browser request using Authorization, the preflight response must list Authorization in Access-Control-Allow-Headers. A wildcard does not cover this header for the browser’s CORS check.

Debug a missing header

  1. Open the browser’s Network panel and inspect the request. Determine whether an OPTIONS preflight occurred.
  2. Inspect the preflight response. Confirm that the origin, method, and every requested header are allowed.
  3. If the header is browser-controlled or forbidden, changing Axios casing or syntax will not help; script code cannot set it.
  4. When cookies or other credentials are included, verify that the server enables credentialed CORS and does not pair credentials with a wildcard allowed origin.

Node.js requests are not subject to browser CORS enforcement, although Node still has its own HTTP and redirect behavior.

XSRF headers and credentials are different settings

withXSRFToken controls whether Axios reads an XSRF cookie and writes the configured XSRF header in browser requests. Its default behavior is same-origin only. Set it to true to attempt the behavior for cross-origin calls, false to disable it, or provide a callback for per-request decisions.

withCredentials controls whether cross-site requests include cookies and HTTP authentication. It does not itself turn on the XSRF header. If a cross-origin call needs both an XSRF header and cookies, configure withXSRFToken: true and withCredentials: true, then configure the server’s CORS policy accordingly.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Protect secret headers across Node.js redirects

The Axios Node HTTP adapter accepts a sensitiveHeaders array for custom secret-bearing names such as X-API-Key. When following a redirect to a different origin, the adapter removes headers listed there; same-origin redirects retain them.

await axios.get('https://service.example/start', {
  headers: { 'X-API-Key': process.env.API_KEY },
  sensitiveHeaders: ['X-API-Key'],
});

This option applies to the documented Node redirect case. If maxRedirects: 0 disables redirects, sensitiveHeaders is not used. Still scope credentials to the correct Axios instance and avoid following untrusted redirect destinations.

Inspect response headers separately

Request headers are values you send; response headers are values the server returns. Axios exposes response header names in lower case regardless of the server’s spelling:

const response = await axios.get('/health');

console.log(response.headers['content-type']);
console.log(response.headers.get('content-type'));

Use the response object when you need caching, content type, rate-limit, or server-request identifiers returned by the API.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Common errors and fixes

“The server never sees my custom header”

In a browser, inspect for a failed preflight and fix the server’s CORS allow-origin, allow-methods, and allow-headers response. In Node.js, log the final request configuration and check that an interceptor did not overwrite or mark the header as skipped.

“Authorization is rejected by CORS”

Add Authorization explicitly to the server’s Access-Control-Allow-Headers. Do not rely on * for this header.

“My multipart upload is empty or malformed”

Remove the manually assigned multipart Content-Type in browser code so the runtime supplies the boundary. For Node, verify that the chosen FormData implementation exposes the headers Axios expects.

“A token leaks to another host”

Replace global axios.defaults with a dedicated axios.create() client. Review redirect behavior and use sensitiveHeaders for secret custom headers in Node.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

“An interceptor sees no headers object”

Use the AxiosHeaders API shown above and ensure the interceptor returns its config. Avoid deprecated direct property manipulation in new code.

“My header is present locally but forbidden in production”

Check whether the code is running in a browser rather than Node.js. Browser-controlled headers such as User-Agent and Connection cannot be set by application JavaScript.

Performance, reliability, and security practices

  • Keep static values on a narrowly scoped instance instead of rebuilding header objects in every call.
  • Read rotating tokens in a request interceptor, and coordinate refresh logic so concurrent requests do not each perform an unnecessary refresh.
  • Use request IDs for tracing, but never place passwords, private keys, or long-lived secrets in headers that might be exposed to browser JavaScript.
  • Send only the headers an endpoint needs. Extra custom headers can trigger a CORS preflight and add latency.
  • Test both same-origin and cross-origin paths, including preflight responses and credentialed requests.
  • Pin and review your Axios version when relying on newer options such as withXSRFToken, sensitiveHeaders, or formDataHeaderPolicy.

Or skip the browser setup

If your goal is to capture a page rather than configure Axios networking, ScreenshotNeo provides a website screenshot API and MCP server. One request returns a PNG, JPEG, WebP, or PDF, while its capture flow accepts cookie banners and removes more than 60 known consent platforms, newsletter popups, and chat widgets before the shot. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing result.

cURL:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

Python:

import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)

Node.js:

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

See the full parameter list in the ScreenshotNeo documentation. The service also has an MCP server with take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients. The Free plan includes 1,000 screenshots each month with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Frequently Asked Questions

Can I set headers after creating an Axios instance?

Yes. Update the instance’s defaults, or use a request interceptor when the value must be resolved for each call.

Are Axios header names case-sensitive?

No. HTTP header names are case-insensitive; AxiosHeaders preserves a matching name’s existing style.

Does withCredentials add an XSRF header?

No. withCredentials controls cross-site credentials, while withXSRFToken controls Axios’s XSRF-cookie-to-header behavior.

Can browser JavaScript set User-Agent or Connection?

No. Browsers reserve forbidden or controlled headers; Axios cannot bypass those restrictions.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Read next

Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.