How to Integrate Axios
How to Integrate Axios Axios is a powerful, promise-based HTTP client for JavaScript that simplifies the process of making API requests in both browser and Node.js environments. Unlike the native Fetch API, Axios provides built-in features like request and response interception, automatic JSON data transformation, request cancellation, and robust error handling — making it a preferred choice for d
How to Integrate Axios
Axios is a powerful, promise-based HTTP client for JavaScript that simplifies the process of making API requests in both browser and Node.js environments. Unlike the native Fetch API, Axios provides built-in features like request and response interception, automatic JSON data transformation, request cancellation, and robust error handling making it a preferred choice for developers building modern web applications. Integrating Axios into your project can significantly improve the reliability, maintainability, and performance of your frontend or backend HTTP communications. Whether you're working with React, Vue, Angular, or a Node.js server, Axios offers a consistent, intuitive interface that reduces boilerplate code and enhances developer productivity. This comprehensive guide walks you through every aspect of integrating Axios into your application, from installation to advanced configuration, best practices, real-world examples, and troubleshooting common issues.
Step-by-Step Guide
Step 1: Understand Axios and Its Advantages
Before diving into integration, its essential to understand why Axios stands out among other HTTP clients. Axios is built on top of the XMLHttpRequest object in browsers and the http module in Node.js. It supports both Promise-based and async/await syntax, enabling clean, readable code. Key advantages include:
- Automatic transformation of JSON data (request and response)
- Interceptors for modifying requests or responses globally
- Request cancellation support
- Client-side protection against XSRF (Cross-Site Request Forgery)
- Progress tracking for uploads and downloads
- Works seamlessly in both browser and server environments
These features make Axios particularly valuable in applications that interact with RESTful APIs, handle authentication tokens, or require consistent error handling across multiple endpoints.
Step 2: Install Axios in Your Project
The installation process varies depending on your environment. Below are the most common scenarios.
Using npm (Node.js or React, Vue, Angular projects)
If youre working with a modern JavaScript framework or a Node.js backend, open your terminal in the project root directory and run:
npm install axios
This installs the latest stable version of Axios and adds it to your projects package.json under dependencies.
Using yarn
If your project uses Yarn instead of npm:
yarn add axios
Using CDN (for simple HTML/JavaScript projects)
For lightweight applications or prototyping without a build system, you can include Axios via a CDN. Add the following script tag to your HTML file, preferably just before the closing </body> tag:
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
Once included, Axios becomes available globally as the axios object.
Step 3: Import Axios in Your Application
Depending on your module system, youll need to import Axios differently.
ES6 Modules (React, Vue, Webpack, Vite)
In JavaScript or TypeScript files, import Axios using:
import axios from 'axios';
This is the most common method in modern frameworks. You can now use axios throughout your component or module.
CommonJS (Node.js, older projects)
If you're using Node.js without ES6 module support, require Axios as follows:
const axios = require('axios');
Global (CDN)
If you used the CDN method, no import is needed. Simply use:
axios.get('https://api.example.com/data');
Step 4: Make Your First HTTP Request
Once Axios is installed and imported, you can begin making HTTP requests. Axios supports all standard HTTP methods: GET, POST, PUT, DELETE, PATCH, HEAD, and OPTIONS.
GET Request
To fetch data from an API endpoint:
axios.get('https://jsonplaceholder.typicode.com/posts/1')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error('Error fetching data:', error);
});
Alternatively, using async/await for cleaner syntax:
async function fetchPost() {
try {
const response = await axios.get('https://jsonplaceholder.typicode.com/posts/1');
console.log(response.data);
} catch (error) {
console.error('Error fetching data:', error);
}
}
fetchPost();
POST Request
To send data to a server:
axios.post('https://jsonplaceholder.typicode.com/posts', {
title: 'My New Post',
body: 'This is the content of my post.',
userId: 1
})
.then(response => {
console.log('Post created:', response.data);
})
.catch(error => {
console.error('Error creating post:', error);
});
PUT and PATCH Requests
Use PUT to update a resource entirely, and PATCH for partial updates:
// PUT - full update
axios.put('https://jsonplaceholder.typicode.com/posts/1', {
id: 1,
title: 'Updated Title',
body: 'Updated content',
userId: 1
})
.then(response => console.log(response.data));
// PATCH - partial update
axios.patch('https://jsonplaceholder.typicode.com/posts/1', {
title: 'Partially Updated Title'
})
.then(response => console.log(response.data));
DELETE Request
To remove a resource:
axios.delete('https://jsonplaceholder.typicode.com/posts/1')
.then(response => {
console.log('Post deleted:', response.status);
})
.catch(error => {
console.error('Error deleting post:', error);
});
Step 5: Configure Axios with Default Settings
To avoid repeating configuration across multiple requests, you can set default values for your Axios instance. This is especially useful for authentication headers, base URLs, and timeout settings.
Setting a Base URL
If your application communicates with a single API domain, set it as the default:
axios.defaults.baseURL = 'https://api.example.com/v1';
Now, all requests will prepend this base URL:
axios.get('/users'); // Requests https://api.example.com/v1/users
Adding Authentication Headers
Many APIs require authentication via tokens. Set a default Authorization header:
axios.defaults.headers.common['Authorization'] = 'Bearer YOUR_ACCESS_TOKEN';
For dynamic tokens (e.g., after login), you can update the header programmatically:
function setAuthToken(token) {
if (token) {
axios.defaults.headers.common['Authorization'] = Bearer ${token};
} else {
delete axios.defaults.headers.common['Authorization'];
}
}
Configuring Timeouts
Prevent hanging requests by setting a reasonable timeout:
axios.defaults.timeout = 10000; // 10 seconds
Step 6: Create a Reusable Axios Instance
While axios.defaults applies globally, creating a custom Axios instance offers better isolation and configuration control especially in large applications with multiple API endpoints.
Create a new file, e.g., apiClient.js:
import axios from 'axios';
const apiClient = axios.create({
baseURL: 'https://api.example.com/v1',
timeout: 10000,
headers: {
'Content-Type': 'application/json',
},
});
// Add a request interceptor
apiClient.interceptors.request.use(
config => {
const token = localStorage.getItem('authToken');
if (token) {
config.headers.Authorization = Bearer ${token};
}
return config;
},
error => {
return Promise.reject(error);
}
);
// Add a response interceptor
apiClient.interceptors.response.use(
response => response,
error => {
if (error.response?.status === 401) {
// Handle unauthorized access (e.g., redirect to login)
localStorage.removeItem('authToken');
window.location.href = '/login';
}
return Promise.reject(error);
}
);
export default apiClient;
Now, import and use this instance throughout your application:
import apiClient from './apiClient';
async function fetchUsers() {
try {
const response = await apiClient.get('/users');
return response.data;
} catch (error) {
console.error('Failed to fetch users:', error);
throw error;
}
}
Step 7: Handle Responses and Errors Effectively
Axios responses contain structured data. Always inspect the full response object:
axios.get('/data')
.then(response => {
console.log('Data:', response.data); // Actual response body
console.log('Status:', response.status); // HTTP status code (e.g., 200)
console.log('Headers:', response.headers); // Response headers
console.log('Config:', response.config); // Request configuration
})
.catch(error => {
if (error.response) {
// Server responded with error status
console.error('Server Error:', error.response.status, error.response.data);
} else if (error.request) {
// Request was made but no response received
console.error('Network Error:', error.request);
} else {
// Something else happened
console.error('Error:', error.message);
}
});
Always handle errors in production applications. Never leave catch blocks empty.
Step 8: Integrate with Frameworks
React
In React, use Axios inside hooks like useEffect to fetch data on component mount:
import React, { useState, useEffect } from 'react';
import axios from 'axios';
function UserList() {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
const fetchUsers = async () => {
try {
const response = await axios.get('https://jsonplaceholder.typicode.com/users');
setUsers(response.data);
} catch (error) {
console.error('Failed to load users:', error);
} finally {
setLoading(false);
}
};
fetchUsers();
}, []);
if (loading) return <p>Loading...</p>;
return (
<ul>
{users.map(user => <li key={user.id}>{user.name}</li>)}
</ul>
);
}
Vue 3 (Composition API)
<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';
const users = ref([]);
const loading = ref(true);
onMounted(async () => {
try {
const response = await axios.get('https://jsonplaceholder.typicode.com/users');
users.value = response.data;
} catch (error) {
console.error('Failed to load users:', error);
} finally {
loading.value = false;
}
});
</script>
<template>
<div v-if="loading">Loading...</div>
<ul v-else>
<li v-for="user in users" :key="user.id">{{ user.name }}</li>
</ul>
</template>
Node.js Backend
Use Axios to call external APIs from your server:
const express = require('express');
const axios = require('axios');
const app = express();
app.get('/api/external-data', async (req, res) => {
try {
const response = await axios.get('https://jsonplaceholder.typicode.com/posts');
res.json(response.data);
} catch (error) {
res.status(500).json({ error: 'Failed to fetch external data' });
}
});
app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
Best Practices
1. Always Use a Custom Axios Instance
Global defaults are convenient but can lead to unintended side effects in large applications. Create a dedicated instance per API endpoint or service to isolate configurations especially when dealing with multiple third-party APIs.
2. Centralize API Calls
Organize your HTTP requests in a dedicated folder (e.g., /api) with separate files for each resource:
/api/users.js/api/posts.js/api/auth.js
This improves code maintainability and enables easy testing and mocking.
3. Implement Request and Response Interceptors
Interceptors are powerful tools for global logic. Use them to:
- Attach authentication tokens automatically
- Log request/response timing for debugging
- Transform response data before it reaches components
- Handle token refresh on 401 responses
4. Avoid Hardcoding URLs
Use environment variables to manage API endpoints:
// .env
VITE_API_BASE_URL=https://api.example.com/v1
// In code
const apiClient = axios.create({
baseURL: import.meta.env.VITE_API_BASE_URL,
});
This allows seamless switching between development, staging, and production environments.
5. Handle Loading and Error States
Always reflect the state of your requests in the UI. Use loading spinners, error banners, and retry buttons to enhance user experience.
6. Cancel Unnecessary Requests
In SPAs, users may navigate away before a request completes. Use Axioss cancellation feature to prevent memory leaks and unnecessary server load:
const CancelToken = axios.CancelToken;
const source = CancelToken.source();
axios.get('/data', {
cancelToken: source.token
})
.then(response => {
console.log(response.data);
})
.catch(thrown => {
if (axios.isCancel(thrown)) {
console.log('Request canceled:', thrown.message);
} else {
// Handle other errors
}
});
// Cancel the request when needed
source.cancel('Operation canceled by the user.');
In React, use useEffect cleanup to cancel on unmount:
useEffect(() => {
const source = axios.CancelToken.source();
const fetchData = async () => {
try {
const response = await axios.get('/data', { cancelToken: source.token });
setData(response.data);
} catch (error) {
if (!axios.isCancel(error)) {
setError(error);
}
}
};
fetchData();
return () => {
source.cancel('Component unmounted');
};
}, []);
7. Validate and Sanitize Input
Never trust client-side data. Always validate payloads before sending them via Axios. Use libraries like zod or joi to ensure data integrity.
8. Use TypeScript for Type Safety
If you're using TypeScript, define interfaces for your API responses:
interface User {
id: number;
name: string;
email: string;
}
const response = await axios.get<User[]>('/users');
const users: User[] = response.data;
This provides autocompletion, compile-time error detection, and improved documentation.
9. Monitor and Log API Performance
Use interceptors to log request duration:
apiClient.interceptors.request.use(
config => {
config.startTime = new Date().getTime();
return config;
}
);
apiClient.interceptors.response.use(
response => {
const duration = new Date().getTime() - response.config.startTime;
console.log(Request to ${response.config.url} took ${duration}ms);
return response;
}
);
Tools and Resources
Official Documentation
The official Axios GitHub repository and documentation are essential references:
Development Tools
- Postman Test API endpoints and generate Axios code snippets.
- Insomnia Open-source alternative to Postman with excellent code generation.
- Browser DevTools Monitor network requests and inspect Axios payloads.
- React Developer Tools Debug state and API calls in React apps.
Mocking Libraries
For testing, mock Axios responses to avoid hitting real APIs:
- MockAdapter Axios-specific mocking library. Ideal for unit tests.
- MSW (Mock Service Worker) Intercept network requests at the browser level.
- jest-mock-axios Jest-specific mocking utilities.
Example Mock with MockAdapter
import MockAdapter from 'axios-mock-adapter';
import axios from 'axios';
const mock = new MockAdapter(axios);
mock.onGet('/users').reply(200, [
{ id: 1, name: 'John Doe' },
{ id: 2, name: 'Jane Smith' }
]);
// Now your app will receive mocked data without a real API call
Performance Monitoring
- Sentry Track Axios errors in production.
- Datadog Monitor API latency and error rates.
- LogRocket Record user sessions and API failures.
Real Examples
Example 1: Authentication Flow with Axios
Heres a complete authentication system using Axios:
// api/auth.js
import axios from 'axios';
const apiClient = axios.create({
baseURL: 'https://auth.example.com',
});
export const login = async (email, password) => {
const response = await apiClient.post('/login', { email, password });
localStorage.setItem('authToken', response.data.token);
return response.data;
};
export const register = async (userData) => {
const response = await apiClient.post('/register', userData);
return response.data;
};
export const logout = () => {
localStorage.removeItem('authToken');
delete axios.defaults.headers.common['Authorization'];
};
export const getCurrentUser = async () => {
const token = localStorage.getItem('authToken');
if (!token) return null;
try {
const response = await apiClient.get('/me');
return response.data;
} catch (error) {
logout();
throw error;
}
};
Usage in React component:
import { useState } from 'react';
import { login, getCurrentUser } from './api/auth';
function Login() {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState('');
const handleSubmit = async (e) => {
e.preventDefault();
try {
await login(email, password);
window.location.href = '/dashboard';
} catch (err) {
setError('Login failed. Check credentials.');
}
};
return (
<form onSubmit={handleSubmit}>
<input type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="Email" />
<input type="password" value={password} onChange={(e) => setPassword(e.target.value)} placeholder="Password" />
<button type="submit">Login</button>
{error && <p style={{color: 'red'}}>{error}</p>}
</form>
);
}
Example 2: File Upload with Progress Tracking
Axios supports upload progress events:
const uploadFile = async (file) => {
const formData = new FormData();
formData.append('file', file);
try {
const response = await axios.post('/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data',
},
onUploadProgress: (progressEvent) => {
const percentCompleted = Math.round(
(progressEvent.loaded * 100) / progressEvent.total
);
console.log(Upload progress: ${percentCompleted}%);
},
});
console.log('Upload complete:', response.data);
} catch (error) {
console.error('Upload failed:', error);
}
};
Example 3: Batch Requests with Promise.all
Fetch multiple resources concurrently:
const fetchAllData = async () => {
try {
const [users, posts, comments] = await Promise.all([
apiClient.get('/users'),
apiClient.get('/posts'),
apiClient.get('/comments'),
]);
return {
users: users.data,
posts: posts.data,
comments: comments.data,
};
} catch (error) {
console.error('One or more requests failed:', error);
throw error;
}
};
FAQs
Is Axios better than Fetch API?
Axios offers more features out of the box than the native Fetch API including automatic JSON parsing, request/response interception, and better error handling. Fetch requires manual handling of many edge cases (e.g., network errors arent rejected on HTTP 4xx/5xx statuses). For production applications, Axios is generally preferred.
Can I use Axios in React Native?
Yes. Axios works seamlessly in React Native. Install it via npm and import as usual. It uses the native networking stack under the hood.
Does Axios support TypeScript?
Axios has built-in TypeScript definitions. You can use generics to type your requests and responses for full type safety.
How do I handle expired tokens with Axios?
Use a response interceptor to detect 401 responses. Trigger a token refresh request, retry the original request, then continue. Store the retry queue if multiple requests fail simultaneously.
Can I use Axios in a Chrome extension?
Yes. Include Axios via CDN or bundle it with your extensions background script or content script. Be mindful of CORS policies in manifest permissions.
Whats the difference between axios.create() and axios.defaults?
axios.defaults modifies the global Axios instance, affecting all future requests. axios.create() creates a new instance with its own configuration, allowing you to have multiple clients with different settings (e.g., one for public API, one for authenticated API).
Is Axios still actively maintained?
Yes. Axios has a large, active community and is regularly updated. Its one of the most downloaded packages on npm and is trusted by thousands of production applications.
How do I test Axios calls in Jest?
Use jest.mock('axios') to mock the module, then define return values for specific endpoints. Alternatively, use axios-mock-adapter for more realistic testing.
Can Axios handle cookies automatically?
In browsers, Axios sends cookies if the server sets them, provided you configure withCredentials: true in your request:
axios.get('/protected', { withCredentials: true });
This is essential for sessions and CSRF protection.
Conclusion
Integrating Axios into your JavaScript application is a straightforward yet transformative step toward building robust, scalable, and maintainable HTTP communication layers. From simple GET requests to complex authentication flows and file uploads, Axios provides the tools you need to handle real-world API interactions with elegance and reliability. By following the best practices outlined in this guide using custom instances, interceptors, environment variables, and proper error handling youll create code thats not only functional but also easy to test, debug, and extend.
Whether youre developing a React frontend, a Node.js microservice, or a hybrid application, Axios remains one of the most dependable HTTP clients available. Its consistent API across environments, rich feature set, and strong community support make it an indispensable tool in the modern developers toolkit. Start by implementing a custom Axios instance today, and youll quickly see improvements in code clarity, error resilience, and overall application performance. As your application grows, so too will the value of a well-structured Axios integration making it an investment that pays dividends across your entire development lifecycle.