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. Whether you're building a single-page application with React, Vue, or Angular, or developing a server-side application with Node.js, Axios provides a clean, consistent, and feature-rich interface for handling HTTP communic

Nov 10, 2025 - 08:32
Nov 10, 2025 - 08:32
 0

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. Whether you're building a single-page application with React, Vue, or Angular, or developing a server-side application with Node.js, Axios provides a clean, consistent, and feature-rich interface for handling HTTP communication. Unlike the native Fetch API, Axios offers built-in support for request and response interception, automatic JSON data transformation, request cancellation, and robust error handling — making it the preferred choice for developers seeking reliability and flexibility in their HTTP workflows.

Integrating Axios into your project isn’t just about installing a library — it’s about establishing a scalable, maintainable, and efficient communication layer between your frontend or backend and external services. Proper integration ensures your application remains performant, secure, and easy to debug. In this comprehensive guide, we’ll walk you through every step of integrating Axios, from installation to advanced configuration, and equip you with best practices, real-world examples, and essential tools to master HTTP requests in modern web development.

Step-by-Step Guide

Step 1: Install Axios

Before you can use Axios, you must install it in your project. The installation method depends on your package manager of choice. If you’re using npm (Node Package Manager), open your terminal in the root directory of your project and run:

npm install axios

If you prefer Yarn, use:

yarn add axios

For projects using pnpm:

pnpm add axios

Axios will be added to your package.json under dependencies. After installation, verify it was added correctly by checking your node_modules folder or running:

npm list axios

This confirms the package is installed and shows the version number. Always ensure you’re installing the latest stable version to benefit from security patches and performance improvements.

Step 2: Import Axios in Your Project

Once installed, you need to import Axios into the JavaScript file where you intend to use it. The syntax varies slightly depending on your module system.

In modern ES6+ environments (React, Vue, Node.js with ES modules), use:

import axios from 'axios';

If you're working in a CommonJS environment (legacy Node.js without ES module support), use:

const axios = require('axios');

It’s important to import Axios at the top of your file to ensure it’s available throughout the module scope. Avoid importing Axios inside functions or conditionals unless you have a specific reason — doing so can hinder tree-shaking and increase bundle size unnecessarily.

Step 3: Make a Basic GET Request

The most common use case for Axios is retrieving data from an API. Here’s how to make a basic GET request:

import axios from 'axios';

axios.get('https://jsonplaceholder.typicode.com/posts/1')

.then(response => {

console.log(response.data);

})

.catch(error => {

console.error('Error fetching data:', error);

});

In this example:

  • axios.get() sends an HTTP GET request to the specified URL.
  • The .then() block handles the successful response. The response object contains properties like data, status, headers, and statusText.
  • The .catch() block catches any network errors, timeouts, or HTTP errors (like 404 or 500).

Always log or handle the error appropriately. Ignoring errors can lead to silent failures in production.

Step 4: Make POST, PUT, and DELETE Requests

Axios supports all standard HTTP methods. Here’s how to handle data submission and updates.

POST Request

To send data to a server, use axios.post(). The second parameter is the data payload:

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('Failed to create post:', error);

});

Axios automatically serializes JavaScript objects to JSON and sets the Content-Type header to application/json — no manual configuration needed.

PUT Request

PUT is used to update existing resources:

axios.put('https://jsonplaceholder.typicode.com/posts/1', {

title: 'Updated Title',

body: 'Updated content here.',

userId: 1

})

.then(response => {

console.log('Post updated:', response.data);

})

.catch(error => {

console.error('Update failed:', error);

});

DELETE Request

To delete a resource, use axios.delete():

axios.delete('https://jsonplaceholder.typicode.com/posts/1')

.then(response => {

console.log('Post deleted:', response.status);

})

.catch(error => {

console.error('Delete failed:', error);

});

Note: DELETE requests typically don’t include a body, but Axios allows you to pass one if the API requires it.

Step 5: Configure Request Headers

Many APIs require authentication headers, such as API keys or JWT tokens. You can set headers globally or per request.

Per-Request Headers

Pass headers as the third argument in a request configuration object:

axios.get('https://api.example.com/data', {

headers: {

'Authorization': 'Bearer your-jwt-token-here',

'Content-Type': 'application/json',

'Accept': 'application/json'

}

})

.then(response => console.log(response.data))

.catch(error => console.error(error));

Global Headers

To avoid repeating headers across every request, set them globally on the Axios instance:

axios.defaults.headers.common['Authorization'] = 'Bearer your-jwt-token-here';

axios.defaults.headers.post['Content-Type'] = 'application/json';

Global headers apply to all subsequent requests. Be cautious with sensitive data — avoid hardcoding tokens in client-side code. Use environment variables and secure token storage instead (see Best Practices section).

Step 6: Use Axios Interceptors

Axios interceptors allow you to modify requests or responses before they are handled by then() or catch(). This is essential for tasks like adding authentication tokens, logging, or handling refresh tokens.

Request Interceptor

Use a request interceptor to automatically attach tokens:

axios.interceptors.request.use(

config => {

const token = localStorage.getItem('authToken');

if (token) {

config.headers.Authorization = Bearer ${token};

}

return config;

},

error => {

return Promise.reject(error);

}

);

This runs before every request. If a token exists in local storage, it’s added to the Authorization header.

Response Interceptor

Use a response interceptor to handle global error patterns, like token expiration:

axios.interceptors.response.use(

response => response,

error => {

if (error.response?.status === 401) {

// Token expired or invalid

localStorage.removeItem('authToken');

window.location.href = '/login'; // Redirect to login

}

return Promise.reject(error);

}

);

Interceptors are powerful because they centralize logic. Instead of checking for 401 errors in every API call, you handle it once.

Step 7: Create a Reusable Axios Instance

For larger applications, creating a dedicated Axios instance with default configurations improves maintainability and reduces code duplication.

Create a file named api.js (or axiosConfig.js) in your project:

import axios from 'axios';

const api = axios.create({

baseURL: 'https://api.example.com/v1',

timeout: 10000,

headers: {

'Content-Type': 'application/json',

'Accept': 'application/json'

}

});

// Request interceptor

api.interceptors.request.use(

config => {

const token = localStorage.getItem('authToken');

if (token) {

config.headers.Authorization = Bearer ${token};

}

return config;

},

error => {

return Promise.reject(error);

}

);

// Response interceptor

api.interceptors.response.use(

response => response,

error => {

if (error.response?.status === 401) {

localStorage.removeItem('authToken');

window.location.href = '/login';

}

return Promise.reject(error);

}

);

export default api;

Now, import and use this instance everywhere in your app:

import api from './api';

api.get('/users')

.then(response => console.log(response.data))

.catch(error => console.error('API Error:', error));

This pattern keeps your API configuration centralized, testable, and scalable.

Step 8: Handle Async/Await Syntax

While promises work fine, modern JavaScript favors async/await for cleaner, more readable code. Here’s how to convert Axios calls to async/await:

const fetchUser = async () => {

try {

const response = await api.get('/users/1');

console.log(response.data);

return response.data;

} catch (error) {

console.error('Failed to fetch user:', error.message);

throw error;

}

};

// Usage

fetchUser();

Always wrap async calls in a try...catch block. This ensures errors are caught and handled gracefully, preventing unhandled promise rejections.

Step 9: Cancel Requests

In dynamic UIs (like search boxes or paginated lists), you may need to cancel ongoing requests to prevent stale data from overwriting current state. Axios supports cancellation via AbortController.

const controller = new AbortController();

const fetchSearchResults = async (query) => {

try {

const response = await axios.get(

https://api.example.com/search?q=${query},

{ signal: controller.signal }

);

console.log(response.data);

} catch (error) {

if (axios.isCancel(error)) {

console.log('Request cancelled:', error.message);

} else {

console.error('Network error:', error);

}

}

};

// Call this when user types or navigates away

controller.abort(); // Cancels the request

This is especially useful in React components with useEffect hooks to avoid memory leaks.

Step 10: Test Your Integration

After setting up Axios, test each endpoint manually and programmatically. Use browser DevTools > Network tab to inspect requests and responses. Check:

  • Correct HTTP method and URL
  • Proper headers (Authorization, Content-Type)
  • Status codes (200, 404, 500)
  • Response data structure

For automated testing, use Jest with Mock Service Worker (MSW) or axios-mock-adapter to simulate API responses without hitting real endpoints.

Best Practices

1. Avoid Hardcoding API URLs

Never hardcode base URLs or API keys in your source code. Use environment variables to manage configuration across different environments (development, staging, production).

In your .env file:

REACT_APP_API_BASE_URL=https://api.example.com/v1

REACT_APP_API_KEY=your-key-here

In your code:

const api = axios.create({

baseURL: process.env.REACT_APP_API_BASE_URL,

headers: {

'Authorization': Bearer ${process.env.REACT_APP_API_KEY}

}

});

Ensure environment variables are prefixed with REACT_APP_ in React apps, or use a tool like dotenv in Node.js.

2. Use HTTPS Exclusively

Always use HTTPS for API endpoints. Axios supports HTTPS by default, but ensure your backend is configured to serve content securely. Mixed content (HTTP on HTTPS pages) will be blocked by modern browsers.

3. Implement Proper Error Handling

Axios errors are not just network failures. They include HTTP status codes, timeouts, and validation errors. Always check the structure of the error object:

catch(error => {

if (error.response) {

// Server responded with error status (4xx, 5xx)

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);

}

});

Never display raw error messages to users. Log them server-side and show user-friendly messages instead.

4. Set Reasonable Timeouts

Unlimited request timeouts can cause UI freezing or memory leaks. Set a timeout of 5–10 seconds based on your API’s expected response time:

axios.create({

timeout: 8000

});

Adjust this value based on geographic distance to your API server and network conditions.

5. Use Axios Instances for Different APIs

If your app interacts with multiple APIs (e.g., internal backend, third-party services), create separate Axios instances with different base URLs and headers:

// Internal API

const internalApi = axios.create({ baseURL: 'https://internal-api.example.com' });

// Third-party API

const externalApi = axios.create({ baseURL: 'https://api.thirdparty.com' });

export { internalApi, externalApi };

This prevents header conflicts and improves code organization.

6. Secure Token Storage

Never store authentication tokens in localStorage if security is a priority. Use HTTP-only cookies for sensitive tokens. If you must use localStorage, ensure your app is protected against XSS attacks with Content Security Policy (CSP) and sanitize all user inputs.

7. Optimize Performance with Caching

Axios doesn’t cache responses by default. For frequently requested static data, implement caching using libraries like axios-cache-adapter or memoize functions:

const cachedGet = memoize(async (url) => {

const response = await api.get(url);

return response.data;

});

This reduces redundant requests and improves load times.

8. Log API Activity for Debugging

Implement logging for development and staging environments:

api.interceptors.request.use(

config => {

console.log('Request:', config.method.toUpperCase(), config.url);

return config;

}

);

api.interceptors.response.use(

response => {

console.log('Response:', response.status, response.config.url);

return response;

}

);

Remove or disable logging in production builds to avoid performance overhead and data leaks.

9. Validate Response Data

Always validate the shape and type of data returned from APIs. Use libraries like Zod, Joi, or Yup to define schemas and catch malformed responses early:

import { z } from 'zod';

const UserSchema = z.object({

id: z.number(),

name: z.string(),

email: z.string().email()

});

const fetchUser = async (id) => {

const response = await api.get(/users/${id});

const user = UserSchema.parse(response.data); // Throws error if invalid

return user;

};

This prevents runtime errors caused by unexpected API changes.

10. Write Unit Tests for API Calls

Test your API service layer independently of UI components. Use Jest and axios-mock-adapter to simulate responses:

import axios from 'axios';

import MockAdapter from 'axios-mock-adapter';

const mock = new MockAdapter(axios);

mock.onGet('/users').reply(200, [{ id: 1, name: 'John' }]);

test('fetches users successfully', async () => {

const users = await api.get('/users');

expect(users.data.length).toBe(1);

expect(users.data[0].name).toBe('John');

});

Testing ensures your integration remains stable during refactors and updates.

Tools and Resources

1. Axios Documentation

The official Axios documentation at axios-http.com is comprehensive and regularly updated. It includes detailed API references, examples, and migration guides.

2. Axios Mock Adapter

axios-mock-adapter allows you to mock HTTP requests during testing without touching a real server. Essential for unit and integration testing.

3. Postman

Use Postman to explore, test, and document your API endpoints before integrating them into your app. It helps verify request structure, headers, and expected responses.

4. JSONPlaceholder

JSONPlaceholder is a free, fake online REST API for testing and prototyping. It’s perfect for learning Axios without needing a backend.

5. MSW (Mock Service Worker)

MSW is a powerful tool for mocking API requests in both browser and Node.js environments. It works at the network layer and is ideal for end-to-end testing.

6. Axios Cache Adapter

axios-cache-adapter adds automatic caching to Axios requests using localStorage or in-memory storage. Great for reducing redundant calls to static data.

7. VS Code Extensions

Install extensions like “REST Client” or “Thunder Client” to send HTTP requests directly from your editor. Useful for quick API testing without switching tools.

8. Browser DevTools

Use Chrome or Firefox DevTools > Network tab to inspect Axios requests in real time. Monitor request duration, headers, payload, and response size for performance optimization.

9. ESLint Plugins

Use eslint-plugin-axios or eslint-plugin-promise to enforce best practices in your codebase, such as requiring error handling in async functions.

10. API Monitoring Tools

For production applications, integrate monitoring tools like Sentry, LogRocket, or Datadog to track failed API requests, latency spikes, and error rates.

Real Examples

Example 1: React App with Axios and Context API

Here’s a practical example of integrating Axios with React’s Context API to manage global state for user authentication.

Create AuthContext.js:

import React, { createContext, useContext, useState, useEffect } from 'react';

import axios from 'axios';

const AuthContext = createContext();

export const AuthProvider = ({ children }) => {

const [user, setUser] = useState(null);

const [loading, setLoading] = useState(true);

useEffect(() => {

const fetchUser = async () => {

try {

const token = localStorage.getItem('token');

if (token) {

axios.defaults.headers.common['Authorization'] = Bearer ${token};

const response = await axios.get('/profile');

setUser(response.data);

}

} catch (error) {

localStorage.removeItem('token');

} finally {

setLoading(false);

}

};

fetchUser();

}, []);

const login = async (email, password) => {

const response = await axios.post('/login', { email, password });

const { token } = response.data;

localStorage.setItem('token', token);

axios.defaults.headers.common['Authorization'] = Bearer ${token};

setUser(response.data.user);

};

const logout = () => {

localStorage.removeItem('token');

delete axios.defaults.headers.common['Authorization'];

setUser(null);

};

return (

{children}

);

};

export const useAuth = () => useContext(AuthContext);

Wrap your app in AuthProvider in main.jsx:

import { AuthProvider } from './AuthContext';

ReactDOM.createRoot(document.getElementById('root')).render(

);

Now any component can access user data:

import { useAuth } from './AuthContext';

const Profile = () => {

const { user, loading } = useAuth(); if (loading) return

Loading...; if (!user) return

Please log in.; return

Welcome, {user.name}!

;

};

Example 2: Node.js Server with Axios for External API Integration

In a Node.js backend, Axios can fetch data from third-party services like payment gateways or weather APIs.

const express = require('express');

const axios = require('axios');

const app = express();

app.get('/weather', async (req, res) => {

const { city } = req.query;

try {

const response = await axios.get('https://api.openweathermap.org/data/2.5/weather', {

params: {

q: city,

appid: process.env.WEATHER_API_KEY,

units: 'metric'

}

});

res.json(response.data);

} catch (error) {

console.error('Weather API error:', error.message);

res.status(500).json({ error: 'Failed to fetch weather data' });

}

});

app.listen(3000, () => {

console.log('Server running on http://localhost:3000');

});

This demonstrates how Axios enables seamless integration with external services in server-side applications.

Example 3: E-commerce Product Search with Debounced Axios Calls

In a product search feature, you don’t want to make a request on every keystroke. Use a debounce function to delay requests until the user stops typing.

import { useState, useEffect } from 'react';

import axios from 'axios';

const ProductSearch = () => {

const [query, setQuery] = useState('');

const [products, setProducts] = useState([]);

const fetchProducts = async (searchTerm) => {

if (!searchTerm) return;

try {

const response = await axios.get('/api/products', {

params: { q: searchTerm }

});

setProducts(response.data);

} catch (error) {

console.error('Search failed:', error);

}

};

// Debounce function

useEffect(() => {

const handler = setTimeout(() => {

fetchProducts(query);

}, 500);

return () => {

clearTimeout(handler);

};

}, [query]);

return (

type="text"

value={query}

onChange={(e) => setQuery(e.target.value)}

placeholder="Search products..."

/>

    {products.map(product => (

  • {product.name}
  • ))}

);

};

This improves UX and reduces server load significantly.

FAQs

Is Axios better than Fetch API?

Axios offers more features out of the box than the native Fetch API. It automatically transforms JSON data, provides better error handling (including HTTP status codes), supports request cancellation, and allows request/response interceptors. Fetch requires manual handling of many of these tasks. For most applications, Axios is the more developer-friendly choice.

Can I use Axios in Node.js?

Yes. Axios works seamlessly in both browser and Node.js environments. In Node.js, it uses the http/https modules under the hood. You can use it to call REST APIs, scrape data, or interact with microservices.

Does Axios support TypeScript?

Yes. Axios has first-class TypeScript support. All types are included in the package. You can define request and response interfaces for type safety:

interface User {

id: number;

name: string;

}

const response = await axios.get('/users');

// response.data is now typed as User[]

How do I handle timeouts in Axios?

Set the timeout option in your Axios configuration (e.g., timeout: 5000). If the request exceeds the timeout, Axios throws a timeout error, which you can catch and handle like any other error.

Can I use Axios with GraphQL?

Yes. While Axios is designed for REST, you can send GraphQL queries via POST requests. Pass the query as JSON in the request body:

axios.post('/graphql', {

query: query { users { id name } }

});

How do I upgrade Axios to a new version?

Run npm update axios or yarn upgrade axios. Always check the release notes for breaking changes before upgrading in production.

Does Axios support multipart/form-data?

Yes. To send form data, use FormData and set the Content-Type header to multipart/form-data:

const formData = new FormData();

formData.append('file', fileInput.files[0]);

axios.post('/upload', formData, {

headers: {

'Content-Type': 'multipart/form-data'

}

});

What’s the difference between axios.defaults and a custom instance?

axios.defaults modifies the global Axios instance and affects all requests in your app. A custom instance (axios.create()) is isolated and reusable without affecting other parts of the codebase. Use custom instances for better modularity and testing.

Why is my Axios request not sending headers?

Check if you’re using the correct syntax: headers must be passed in the config object, not as a separate parameter. Also, ensure you’re not overriding headers elsewhere. Use DevTools to inspect the actual request headers being sent.

How do I test Axios in Jest without hitting a real API?

Use axios-mock-adapter or MSW to intercept and mock Axios requests. This allows you to simulate success, error, and timeout scenarios without network dependencies.

Conclusion

Integrating Axios into your web application is a foundational step toward building robust, scalable, and maintainable HTTP communication layers. From simple GET requests to complex interceptors and custom instances, Axios provides the tools needed to handle modern API interactions with confidence and efficiency. By following the step-by-step guide, adopting best practices, leveraging the recommended tools, and studying real-world examples, you’ve equipped yourself to implement Axios in any JavaScript project — whether it’s a React frontend, a Node.js backend, or a hybrid application.

The key to success lies not just in knowing how to install Axios, but in understanding how to structure your API layer for long-term maintainability. Use environment variables, implement error handling, create reusable instances, and test your integrations rigorously. These habits will prevent bugs, reduce technical debt, and improve user experience.

As web applications grow in complexity, the ability to manage HTTP requests cleanly becomes increasingly critical. Axios simplifies this process without sacrificing control — making it the de facto standard for JavaScript developers worldwide. Mastering its integration is not just a technical skill; it’s a professional necessity in modern development.