Axios Automatic Request Header Transformations

Axios simplifies API communication by automatically transforming and managing HTTP request headers based on the payload type, default configurations, and custom transformation pipelines. Instead of requiring developers to manually configure standard headers for every call, Axios inspects request data, applies intelligent defaults, normalizes header casing, and allows programmatic modification through internal transformation functions and interceptors.

Automatic Content-Type Detection

Axios dynamically sets the Content-Type header by evaluating the type of data passed into the request body:

Header Normalization and Merging

Header names are case-insensitive in HTTP specifications, but conflicting casings can cause duplication errors. Axios normalizes all header names by managing them through an internal AxiosHeaders class.

When a request is initiated, Axios merges headers from three distinct levels in a specific order of precedence:

  1. Library Defaults: Global fallbacks such as Accept: application/json, text/plain, */*.
  2. Instance Defaults: Custom headers defined on an axios.create({...}) instance.
  3. Request Configuration: Per-request headers defined directly in the method call (e.g., axios.post(url, data, { headers: {...} })).

During this merge, duplicate keys with different casings (such as content-type and Content-Type) are reconciled into a single canonical entry.

The transformRequest Pipeline

Axios handles data and header transformations through the transformRequest pipeline. By default, this pipeline contains built-in functions that iterate over the payload:

axios.defaults.transformRequest = [
  function (data, headers) {
    // Normalizes headers and serializes JSON objects
    if (isObject(data) && !isFile(data) && !isBlob(data)) {
      headers.set('Content-Type', 'application/json');
      return JSON.stringify(data);
    }
    return data;
  }
];

Developers can override or append to this array to implement custom transformations, such as automatic encryption, custom serialization, or applying custom dynamic headers prior to transmission.

Programmatic Modification via Interceptors

Before the transformRequest pipeline executes, Axios passes the request configuration through any registered request interceptors. This mechanism allows developers to inspect or alter headers asynchronously—such as injecting OAuth bearer tokens or dynamic API keys—before the final serialization and header normalization take place.