transformResponse in Axios
transformResponse runs on the response data before your then or catch code receives it, so you can parse and reshape the payload in one place.
How it works
- Start from raw JSON text. The offline adapter returns the body as a JSON string. With no custom transform, the first call prints
typeof dataasobject: the default transform parsed it. [1] - Add your own transforms. The instance sets
transformResponseto an array of two functions. The first parses the string, the second turnsprice_centsinto apricein dollars. [1] - Read the final data.
response.dataholds what the second function returned, so the caller works with prices and a total, not cents. [2]
Run and edit it
It runs in your browser, in a sandboxed frame that cannot see this site; the packages load from esm.sh only after you press Run.
import axios from 'axios';
// The adapter returns raw JSON text, like a server body
const rawJson = async (config) => ({
data: '{"items":[{"id":1,"name":"Pen","price_cents":199},{"id":2,"name":"Notebook","price_cents":450}],"total_cents":649}',
status: 200,
statusText: 'OK',
headers: { 'content-type': 'application/json' },
config,
});
// 1) Default transforms
const plain = await axios.get('/cart', { adapter: rawJson });
console.log('default typeof data:', typeof plain.data);
console.log('default data:', JSON.stringify(plain.data));
// 2) Custom transforms on an instance
const shop = axios.create({
adapter: rawJson,
transformResponse: [
(data) => JSON.parse(data),
(data) => ({
items: data.items.map((item) => ({ id: item.id, name: item.name, price: item.price_cents / 100 })),
total: data.total_cents / 100,
}),
],
});
const { data } = await shop.get('/cart');
console.log('transformed items:');
for (const item of data.items) {
console.log(` #${item.id} ${item.name.padEnd(9)} $${item.price.toFixed(2)}`);
}
console.log('total: $' + data.total.toFixed(2));
The console shows the default parsed data first, then the reshaped data from the custom transforms. Code written by AgentGid [1].
The console shows the default parsed data first, then the reshaped data from the custom transforms. Code written by AgentGid [1].Checked Oct 12, 2026: it starts without errors in Chromium with axios 1.20.0. Needs WebGL.
More Axios examples
Custom adapters in Axios Creating an instance in Axios Interceptors in Axios Error handling in Axios
Sources
Explanations written by AgentGid from the official docs; the numbers in brackets point here. The code marked "written by AgentGid" is ours and free to copy.