Skip to content

Axios Request Configuration — Complete Guide with Examples

DodaTech Updated 2026-06-28 6 min read

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

Axios request configuration provides detailed control over every HTTP request: URL parameters, custom headers, authentication, response type, timeout behavior, and validation rules.

What You'll Learn

By the end of this tutorial, you'll configure params, headers, authentication, response types, timeout handling, proxy settings, and custom validation for Axios requests.

Why It Matters

Real-world APIs demand precise configuration. You need to send auth tokens, format query parameters, handle different response formats, set proper timeouts for different endpoints, and validate responses consistently.

Real-World Use

DodaZIP's API client configures requests with specific responseType for binary file downloads, custom timeout for large archive operations, and validateStatus to handle partial success responses from extraction endpoints.

Where This Fits in Your Learning Path

flowchart LR
    A["Instance & Config"] --> B["**Request Configuration**"]
    B --> C["Response Schema"]
    C --> D["Transform Data"]
    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

URL Parameters (params)

The params option adds query parameters to the URL. Axios handles Serialization automatically.

const response = await axios.get('/api/users', {
  params: {
    page: 2,
    limit: 10,
    sort: 'name',
    filter: { role: 'admin', active: true }
  }
})
// URL: /api/users?page=2&limit=10&sort=name&filter%5Brole%5D=admin&filter%5Bactive%5D=true

Expected output: The request URL includes serialized query parameters. Nested objects are serialized using bracket notation.

Custom Headers

Set custom headers for authentication, content negotiation, and custom metadata.

const response = await axios.get('/api/protected/data', {
  headers: {
    'Authorization': `Bearer ${localStorage.getItem('token')}`,
    'X-Request-ID': crypto.randomUUID(),
    'X-API-Version': '2.1',
    'Accept-Language': 'en-US'
  }
})

Expected output: The request includes all specified headers. The server can use X-Request-ID for request tracing.

Authentication (auth)

The auth option sets HTTP Basic authentication headers automatically.

const response = await axios.get('/api/secure/data', {
  auth: {
    username: 'admin',
    password: 'secret123'
  }
})
// Equivalent to: Authorization: Basic YWRtaW46c2VjcmV0MTIz

Expected output: Axios encodes the credentials as Base64 and sets the Authorization header for HTTP Basic auth.

Response Type

Control how Axios interprets the response body with responseType.

// Download binary data as a Blob
const imageResponse = await axios.get('/images/logo.png', {
  responseType: 'blob'
})
const imageUrl = URL.createObjectURL(imageResponse.data)

// Stream response (Node.js only)
const streamResponse = await axios.get('/api/large-file', {
  responseType: 'stream'
})

// Get raw text without JSON parsing
const textResponse = await axios.get('/api/data.txt', {
  responseType: 'text'
})

Expected output: The image download creates a blob URL for display. Stream responses allow chunked processing. Text responses skip JSON Parsing.

Timeout Behavior

Configure timeout duration and timeout error message.

try {
  const response = await axios.get('/api/slow-endpoint', {
    timeout: 3000,
    timeoutErrorMessage: 'The server took too long to respond. Please try again.'
  })
} catch (error) {
  if (error.code === 'ECONNABORTED') {
    console.log('Request timed out:', error.message)
  }
}

Expected output: If the server doesn't respond within 3 seconds, Axios aborts the request and throws an error with the custom message.

validateStatus

Control which HTTP status codes are considered successful.

const response = await axios.get('/api/users', {
  validateStatus: function(status) {
    return status >= 200 && status < 300 || status === 304
  }
})

// Custom: treat 400 as valid for form validation responses
const formResponse = await axios.post('/api/validate', data, {
  validateStatus: status => status < 500
})

Expected output: The first request treats 304 Not Modified as success. The second request treats any status below 500 (including 400) as success, useful for form validation APIs.

Proxy Configuration

Configure an HTTP proxy for requests (commonly used in Node.js environments).

const response = await axios.get('https://api.example.com/data', {
  proxy: {
    host: '127.0.0.1',
    port: 8080,
    protocol: 'http',
    auth: {
      username: 'proxyUser',
      password: 'proxyPass'
    }
  }
})

Expected output: The request is routed through the specified proxy server before reaching the target API.

Common Mistakes

1. Passing params as strings instead of objects

// Wrong: manual string concatenation
axios.get('/api/users?page=2&limit=10')

// Correct: use params object
axios.get('/api/users', { params: { page: 2, limit: 10 } })

2. Forgetting to set responseType for binary downloads

Without responseType: 'blob', Axios attempts to parse binary data as JSON, corrupting the result.

3. Using auth option for Bearer tokens

The auth option is for Basic auth only. Use headers for Bearer tokens: headers: { Authorization: 'Bearer ...' }.

4. Setting timeout too low for file uploads

File uploads need longer timeouts or timeout: 0 (no timeout). A 3-second timeout for a 100MB upload will always fail.

5. Not customizing validateStatus for error-response APIs

Some APIs return 200 with error codes in the body. Others return 400 with validation errors. Adjust validateStatus accordingly.

Practice Questions

  1. How do you set query parameters in Axios? Use the params config option with an object. Axios serializes it into the URL.

  2. What does responseType: 'blob' do? It tells Axios to return the response data as a Blob object, useful for downloading files.

  3. How do you set HTTP Basic auth? Use the auth config option with username and password properties.

  4. What does validateStatus control? It determines which HTTP status codes resolve the promise vs reject it.

  5. How do you configure a proxy in Axios? Use the proxy config option with host, port, protocol, and optional auth.

Challenge

Create a configurable request function that accepts a URL, data, and options object. It should merge default config (timeout, headers, validateStatus) with per-request overrides and support automatic retries on timeout.

FAQ

Can I set paramsSerializer for custom serialization?

Yes. The paramsSerializer option lets you provide a custom function to serialize query parameters, useful for APIs with specific serialization requirements.

What is the maxRedirects config?

It controls how many HTTP redirects Axios follows (default 5). Set to 0 to disable redirect following.

Does Axios support HTTP/2 in the browser?

Browsers handle HTTP/2 transparently. In Node.js, use the http2 adapter or the axios-http2 package.

Can I cancel a request based on configuration?

Yes. Use the signal config option with an AbortController to cancel requests programmatically.

How do I send cookies with cross-origin requests?

Set withCredentials: true in the config. The server must also include Access-Control-Allow-Credentials: true.


Mini Project

Build a download manager function that configures Axios requests for different file types: images (blob responseType), JSON data (auto-parse), text files (text responseType), and large files (stream with progress).

async function downloadFile(url, type) {
  const configs = {
    image: { responseType: 'blob', timeout: 10000 },
    json: { responseType: 'json', timeout: 5000 },
    text: { responseType: 'text', timeout: 5000 },
    large: { responseType: 'blob', timeout: 0, onDownloadProgress: (e) => {
      console.log(`Downloaded ${Math.round(e.loaded / e.total * 100)}%`)
    }}
  }

  const config = configs[type] || {}
  const response = await axios.get(url, {
    ...config,
    headers: { 'X-Download-Type': type },
    validateStatus: status => status === 200
  })
  return response.data
}

// Usage
// const img = await downloadFile('/images/photo.jpg', 'image')
// const largeFile = await downloadFile('/archives/backup.zip', 'large')

What's Next

Understand the response object in depth:

Tutorial What You'll Learn
Response Schema Full response object structure and properties
Transform Data Transform request and response data

Related topics: HTTP request and response fundamentals, REST API best practices.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro