JavaScript logoJavaScript INTERMEDIATE

Axios

Promise-based HTTP client for browser and Node.js with automatic JSON transformation, interceptors, and request cancellation

5 min read
axioshttpapiajaxfetchrequestspromisesinterceptorsjavascriptnodejs

New to Async JavaScript? Start Here First!

This sheet covers the Fetch API for making HTTP requests. If you're new to promises, async/await, or asynchronous JavaScript patterns, we recommend starting with our async JavaScript fundamentals sheet first.

Start with Async JavaScript Fundamentals

Installation & Basic Requests

Installation & Setup

Install Axios and create your first request

javascript
✅ Works in both browser and Node.js environments (isomorphic)
💡 Automatically transforms JSON data unlike fetch API
🔍 Returns full response object with data, status, headers
⚡ Promise-based with async/await support out of the box
installationsetupimport

HTTP Request Methods

Perform GET, POST, PUT, PATCH, and DELETE requests

javascript
✅ Dedicated methods for each HTTP verb for cleaner syntax
💡 postForm/putForm/patchForm auto-set multipart/form-data
🔍 Second parameter is data, third is config for POST/PUT/PATCH
⚡ Use Promise.all() for concurrent requests to improve speed
getpostputpatchdeletemethods

Request Configuration

Configure timeout, headers, query params, and more

javascript
✅ Create instances with axios.create() for reusable config
💡 Use params object for query strings - auto URL-encoded
🔍 timeout applies to both connection and response time
⚡ Set baseURL once, use relative paths in all requests
configtimeoutheadersparamsbaseurl

Interceptors & Error Handling

Request Interceptors

Modify requests before they are sent

javascript
✅ Perfect for adding auth tokens to every request globally
💡 Multiple interceptors execute in the order they were added
🔍 Must return config object or Promise for request to proceed
⚡ Use eject() to remove interceptor if no longer needed
interceptorsrequestmiddlewareauth

Response Interceptors

Transform responses and handle errors globally

javascript
✅ Centralize error handling - no try/catch in every component
💡 Implement token refresh logic to handle expired sessions
🔍 Return response to continue, reject to trigger catch block
⚡ Use _retry flag to prevent infinite retry loops
interceptorsresponseerrorsretry

Error Handling

Handle and diagnose different error types

javascript
✅ Use axios.isAxiosError() to safely type-check error objects
💡 Check error.response first, then error.request, then error.message
🔍 error.response means server responded, request means network issue
⚡ Implement retry logic for network errors and 5xx status codes
errorserror-handlingtry-catchdebugging

Request Cancellation & Timeout

Request Cancellation with AbortController

Cancel in-flight requests using modern AbortController API

javascript
✅ AbortController is the modern standard for request cancellation
💡 Essential for search inputs to cancel outdated requests
🔍 Always cleanup controllers in useEffect/componentWillUnmount
⚡ Prevents race conditions when user types quickly in search
cancelabortabortcontrollercleanup

Timeout Configuration

Set connection and response timeouts to prevent hanging

javascript
✅ timeout applies to entire request - both connection and response
💡 Implement exponential backoff when retrying timeout errors
🔍 Use error.code === "ECONNABORTED" to detect timeout errors
⚡ Set different timeouts for fast/slow endpoints to optimize UX
timeoutretrybackoffperformance

Advanced Patterns

TypeScript Integration

Type-safe API calls with TypeScript generics

typescript
✅ Use generics to type response.data for full type safety
💡 Create wrapper class to encapsulate API logic and types
🔍 axios.isAxiosError<T> provides type-safe error handling
⚡ Define response interfaces once, reuse across all endpoints
typescripttypesgenericstype-safety

File Uploads & Downloads

Handle file uploads with progress and file downloads

javascript
✅ Use responseType: "blob" for file downloads to handle binary
💡 onUploadProgress and onDownloadProgress track transfer progress
🔍 FormData auto-sets Content-Type with proper boundary
⚡ Implement chunked uploads for files larger than 100MB
uploaddownloadfilesformdataprogress

Authentication Patterns

Implement JWT refresh, bearer tokens, and auth interceptors

typescript
✅ Store JWT in localStorage or httpOnly cookies for security
💡 Prevent multiple refresh calls with a shared promise
🔍 Use _retry flag to prevent infinite loops on failed refresh
⚡ Automatically retry failed requests after token refresh
authjwttokenrefreshsecurity