Skip to content

Axios Transform Data — Complete Guide with Examples

DodaTech Updated 2026-06-28 5 min read

In this tutorial, you'll learn about Axios data transformation. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.

Axios transformData and transformResponse let you automatically modify request payloads before sending and response data after receiving, centralizing data formatting logic.

What You'll Learn

By the end of this tutorial, you'll use transformRequest to serialize and format outgoing data, transformResponse to parse and normalize incoming data, chain multiple transformers, and handle dates and nested objects.

Why It Matters

Raw API data rarely matches your application's format. Dates come as ISO strings, numbers as strings, nested objects need flattening. Transform functions centralize this logic so individual components don't repeat conversion code.

Real-World Use

DodaZIP's API client transforms requests by automatically converting file size numbers to strings for an API that expects string format. On the response side, it converts ISO date strings to Date objects and snake_case keys to camelCase automatically.

Where This Fits in Your Learning Path

flowchart LR
    A["Response Schema"] --> B["**Transform Data**"]
    B --> C["Cancellation"]
    C --> D["Progress Events"]
    D --> E["Axios Advanced"]
    style B fill:#f97316,stroke:#c2410c,color:#fff
    style A fill:#e5e7eb,stroke:#9ca3af,color:#374151
    style E fill:#22c55e,stroke:#16a34a,color:#fff

transformRequest

transformRequest runs before the request is sent. It receives the request data and headers.

const instance = axios.create({
  transformRequest: [
    function(data, headers) {
      // Convert all numbers to strings
      for (const key in data) {
        if (typeof data[key] === 'number') {
          data[key] = String(data[key])
        }
      }
      return JSON.stringify(data)
    },
    ...axios.defaults.transformRequest
  ]
})

await instance.post('/api/items', { id: 123, quantity: 5 })

Expected output: The request body is {"id":"123","quantity":"5"} with numbers converted to strings before JSON Serialization.

transformResponse

transformResponse runs after the response is received but before the promise resolves.

const instance = axios.create({
  transformResponse: [
    ...axios.defaults.transformResponse,
    function(data) {
      if (typeof data === 'object' && data !== null) {
        // Convert ISO dates to Date objects
        for (const key in data) {
          if (typeof data[key] === 'string' && /^\d{4}-\d{2}-\d{2}T/.test(data[key])) {
            data[key] = new Date(data[key])
          }
        }
      }
      return data
    }
  ]
})

const { data } = await instance.get('/api/events/1')
console.log(data.eventDate instanceof Date)  // true
console.log(data.eventDate.toLocaleDateString())  // formatted date

Expected output: The eventDate string is automatically converted to a real Date object, allowing method calls like .toLocaleDateString().

Snake Case to Camel Case

Transform response keys from snake_case to camelCase for consistent JavaScript naming.

function snakeToCamel(obj) {
  if (Array.isArray(obj)) return obj.map(snakeToCamel)
  if (obj !== null && typeof obj === 'object') {
    return Object.keys(obj).reduce((acc, key) => {
      const camelKey = key.replace(/_([a-z])/g, (_, c) => c.toUpperCase())
      acc[camelKey] = snakeToCamel(obj[key])
      return acc
    }, {})
  }
  return obj
}

const instance = axios.create({
  transformResponse: [
    ...axios.defaults.transformResponse,
    snakeToCamel
  ]
})

const { data } = await instance.get('/api/user')
console.log(data.firstName)  // instead of data.first_name
console.log(data.lastName)   // instead of data.last_name

Expected output: The API's snake_case keys (first_name, last_name) are automatically converted to camelCase (firstName, lastName).

Chaining Multiple Transformers

Multiple transformers execute in order, each receiving the result of the previous one.

const instance = axios.create({
  transformRequest: [
    function removeNulls(data) {
      for (const key in data) {
        if (data[key] === null) delete data[key]
      }
      return data
    },
    function formatDates(data) {
      if (data.birthDate && data.birthDate instanceof Date) {
        data.birthDate = data.birthDate.toISOString().split('T')[0]
      }
      return data
    },
    ...axios.defaults.transformRequest  // JSON.stringify runs last
  ]
})

Expected output: Null values are removed first, then dates are formatted to YYYY-MM-DD, then the data is JSON-serialized for sending.

Common Mistakes

1. Forgetting to include default transformers

If you replace transformRequest entirely, you lose the default JSON.stringify behavior. Always spread ...axios.defaults.transformRequest at the end.

2. Mutating the original data object

Transformers receive the original data object. Mutating it affects all references. Return a new object if immutability is needed.

3. Assuming response data is always an object

transformResponse can receive non-object data (string, blob). Always check typeof data === 'object' before accessing properties.

4. Throwing errors in transformers without handling

An error in transformResponse causes the entire promise to reject. Wrap transformation logic in try/catch or handle edge cases defensively.

5. Using async/await in transformers

Transformers must be synchronous. Axios does not await promises returned from transformer functions.

Practice Questions

  1. What does transformRequest do? It modifies request data before it is sent to the server. Common uses include formatting, serialization, and null removal.

  2. How do you preserve default transformation behavior? Spread the default transformers: ...axios.defaults.transformRequest.

  3. Can transformers be async? No. Transformers must be synchronous. Axios does not support async transformers.

  4. What happens if a transformer throws? The request/response promise rejects with the thrown error.

  5. How do you transform nested objects in responses? Use a recursive function that traverses all properties and applies the transformation.

Challenge

Build a transformer that automatically wraps all API responses in a standard envelope. The response interceptor should return { data, status, timestamp, transformed: true } instead of the raw response.

FAQ

Can I have different transformers for different instances?

Yes. Each instance can have its own transformRequest and transformResponse arrays.

Do transformers run for every request?

transformsRequest runs for every request. transformResponse runs for every successful response.

Can I skip transformation for a specific request?

No per-request skip is available. Use a conditional check inside the transformer function based on config properties.

What is the order of transformer execution?

transformRequest runs in array order (index 0 first). transformResponse runs in array order too.

Can transformers access the response status code?

transformResponse receives only the parsed data. Use response interceptors if you need access to the full response.


Mini Project

Build a fully transformed API client. Requests automatically remove null fields, convert Date objects to ISO strings, and add a request timestamp. Responses convert snake_case to camelCase, ISO strings to Date objects, and wrap data in a standardized format.

function prepareRequest(data) {
  if (typeof data !== 'object' || data === null) return data
  const result = { ...data }
  for (const key in result) {
    if (result[key] === null) delete result[key]
    if (result[key] instanceof Date) result[key] = result[key].toISOString()
  }
  result._clientTimestamp = new Date().toISOString()
  return result
}

const api = axios.create({
  transformRequest: [prepareRequest, ...axios.defaults.transformRequest],
  transformResponse: [...axios.defaults.transformResponse, snakeToCamel, convertDates]
})

// Now use api for all API calls with automatic transformation
// const { data } = await api.post('/users', { name: 'Alice', birthDate: new Date('1990-01-01'), deleted: null })
// Server receives: {"name":"Alice","birthDate":"1990-01-01T00:00:00.000Z","_clientTimestamp":"2026-06-28T..."}

What's Next

Learn about request cancellation:

Tutorial What You'll Learn
Cancellation Cancel in-flight requests with AbortController
Progress Events Track upload and download progress

Related topics: JavaScript object transformation, date formatting and parsing.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro