Axios transformRequest vs Request Interceptors

When working with the Axios HTTP client, developers often need to modify outgoing HTTP requests. Axios provides two primary mechanisms for this purpose: transformRequest and request interceptors. While both allow you to alter request data before it reaches the server, they serve different architectural roles, support different execution models, and operate on different parts of the request lifecycle.

What Is transformRequest?

transformRequest is a configuration option specifically designed to modify the request payload (data) and headers right before they are sent over the network.

Key characteristics of transformRequest:

axios.post('/api/user', data, {
  transformRequest: [(data, headers) => {
    // Modify headers or payload format synchronously
    headers['Content-Type'] = 'application/json';
    return JSON.stringify(data);
  }]
});

What Are Request Interceptors?

Request interceptors are middleware-style functions that run before a request is handed off to the HTTP adapter. They receive the entire Axios request configuration object (AxiosRequestConfig).

Key characteristics of request interceptors:

axios.interceptors.request.use(async (config) => {
  // Asynchronous operations are supported
  const token = await getAuthToken();
  config.headers.Authorization = `Bearer ${token}`;
  return config;
}, (error) => {
  return Promise.reject(error);
});

Key Differences

Feature transformRequest Request Interceptors
Scope Modifies only data and headers. Modifies the entire config object (URL, params, headers, data, etc.).
Async Execution Synchronous only. Supports synchronous and asynchronous (Promise) execution.
Execution Order Executes last, directly before the network adapter sends the payload. Executes early in the request pipeline.
Applicable Methods Only methods with request bodies (POST, PUT, etc.). All HTTP methods (GET, POST, DELETE, etc.).
Error Handling No built-in rejection handler. Has a dedicated error callback (onRejected).

When to Use Which