How to Override transformRequest in Axios
In Axios, the transformRequest property allows you to
mutate request data and headers before a request is dispatched to the
server. By default, Axios applies a built-in array of transformer
functions that automatically serialize payloads into formats like JSON.
You can completely replace this default behavior or extend it by
providing an array of custom transformer functions at the request level,
instance level, or global defaults level.
Per-Request Override
To override transformRequest for a specific API call,
pass an array of transformer functions inside the request config object.
Each function takes data and headers as
arguments and must return the modified data.
import axios from 'axios';
axios.post('/api/users', { name: 'Alice' }, {
transformRequest: [
(data, headers) => {
// Modify headers if needed
headers['Content-Type'] = 'text/plain';
// Custom transformation logic
return JSON.stringify(data).toUpperCase();
}
]
});When you define an array directly on the request config, it completely bypasses Axios's default transformers.
Instance-Level Override
To override default transformers for all requests made by a specific
Axios instance, define transformRequest when calling
axios.create().
import axios from 'axios';
const apiClient = axios.create({
baseURL: 'https://api.example.com',
transformRequest: [
(data, headers) => {
// Custom serialization
return new URLSearchParams(data).toString();
}
]
});
export default apiClient;Global Override
To change the default transformation pipeline across the entire
application, assign a new array directly to
axios.defaults.transformRequest.
import axios from 'axios';
axios.defaults.transformRequest = [
(data, headers) => {
// Custom global transformation
return data;
}
];Preserving and Extending Default Transformers
If you want to add custom behavior without losing Axios's default serialization (such as automatic JSON conversion), you can merge your custom transformer with the default array using array concatenation or the spread operator.
Prepending a Custom Transformer
Run custom logic before the standard Axios transformation:
axios.post('/api/data', payload, {
transformRequest: [
(data, headers) => {
// Pre-processing step
data.timestamp = Date.now();
return data;
},
...axios.defaults.transformRequest
]
});Appending a Custom Transformer
Run custom logic after the standard Axios transformation:
axios.post('/api/data', payload, {
transformRequest: [
...axios.defaults.transformRequest,
(data, headers) => {
// Post-processing step on the serialized output
return data;
}
]
});Important Requirements
- Return Types: The final function in the
transformRequestarray must return one of the following types:string,ArrayBuffer,Buffer,FormData, orStream. - Execution Order: Transformers are executed
synchronously in the order they appear in the array. The return value of
one function is passed as the
dataparameter to the next function in the chain.