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:
- Payload-focused: It only accepts and alters the
request
dataandheaders. It cannot modify request URLs, query parameters, or timeouts. - Synchronous: The transformation function must run synchronously. It cannot return a Promise.
- Method limitation: It applies primarily to request
methods that carry a body (
POST,PUT,PATCH,DELETE). - Format conversion: It is commonly used to convert
JavaScript objects into formats like JSON strings,
FormData, or URL-encoded strings.
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:
- Full configuration access: You can inspect or
modify any part of the request, including
url,method,params,headers,data,timeout, andcancelToken. - Asynchronous support: Interceptor callbacks can be
asyncor return a Promise, allowing you to perform operations like fetching a refresh token from a database or storage before dispatching the request. - Error handling: Interceptors support a secondary rejection handler to catch errors occurring in earlier interceptors or during request preparation.
- Global or instance-level: Commonly registered once on an Axios instance to apply across all requests regardless of the HTTP method.
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
- Use Request Interceptors when you need to inject authorization tokens (especially asynchronous token retrieval), log requests, modify query parameters, add global headers, or rewrite request URLs.
- Use
transformRequestwhen you need low-level serialization or transformation of the request body (such as converting objects to XML, Binary, or custom Form-Data structures) immediately before transmission.