Axios Integration
Axios Integration covers shared clients, service functions, interceptors, error objects, retries, and how Axios compares with Fetch.
Course: React — Routing & API Integration Lesson: 09
Learning objectives
Install Axios, create a reusable client, configure base URLs and interceptors, handle response errors, and compare Axios with Fetch.
What Axios provides
Axios is an HTTP client for browser and server-side JavaScript environments. It offers a convenient API for common request patterns, automatic JSON transformation in typical cases, request/response interceptors, timeout configuration, and consistent error objects.
Install it:
npm install axios
Create a shared client
import axios from "axios";export const apiClient = axios.create({baseURL: import.meta.env.VITE_API_BASE_URL,timeout: 15000,headers: {Accept: "application/json"}});
A shared client avoids repeating configuration in every service. The base URL should be environment-specific. Never place confidential server credentials in browser-exposed configuration.
Write service functions
import { apiClient } from "./apiClient";export async function fetchOrders(params) {const response = await apiClient.get("/orders", { params });return response.data;}export async function createOrder(payload) {const response = await apiClient.post("/orders", payload);return response.data;}
Axios exposes the response payload through response.data. Keep service functions focused on endpoint contracts and let feature-level code decide how to present results.
Interceptors
A request interceptor can add shared metadata or attach an access token obtained through the application's approved authentication mechanism. A response interceptor can normalize errors or handle a centralized session-expiry policy.
apiClient.interceptors.response.use(response => response,error => {// Normalize or report the error according to application policy.return Promise.reject(error);});
Interceptors are global to the configured client. Avoid redirecting or retrying every failure indiscriminately. A 403 is not the same as an expired session, and a retry may be unsafe for a non-idempotent operation.
Axios and Fetch comparison
- Fetch is built into modern browsers; Axios is an additional dependency.
- Fetch requires explicit
response.okchecks. - Axios rejects its Promise for responses outside its configured success range by default.
- Both support request cancellation.
- Axios provides interceptors and client instances; Fetch can achieve similar architecture through wrappers.
Choose based on application needs and team conventions, not habit alone.
Error handling
Axios errors can include response when the server responded, request when no response was received, and configuration information. Avoid exposing raw error objects to users. Normalize them into safe application messages.
Common mistakes
- Creating a new Axios client in every component.
- Putting secret API keys in frontend code.
- Treating every 401/403 as the same condition.
- Adding automatic retries to all methods without considering idempotency.
- Forgetting to eject dynamically registered interceptors when their lifecycle requires it.
Best practices
Use one configured client per API boundary, centralize error normalization, define service functions, configure timeouts, and keep authentication behavior consistent with the backend's security design.
Interview questions & answers
Interview preparation
5 questions grouped by difficulty — expand any card for a model answer and follow-up probe.
Beginner
1What are Axios interceptors?
BeginnerModel answer
Hooks on a client instance that run for every request or response—useful for shared headers, auth attachment, and centralized error normalization.
2When can automatic retries be dangerous?
BeginnerModel answer
Retrying non-idempotent mutations (payments, creates) can duplicate side effects unless the backend supports idempotency or duplicate protection.
Intermediate
3How does Axios error handling differ from Fetch?
IntermediateModel answer
Axios rejects for responses outside its success range by default and exposes structured error fields, while Fetch requires explicitresponse.okchecks.4How do you avoid exposing secrets in frontend code?
IntermediateModel answer
Never put private API keys or server secrets in browser-exposed env vars; only public configuration belongs in the client bundle.
Advanced
5Why create an Axios instance?
AdvancedModel answer
A shared instance centralizesbaseURL, timeouts, headers, and interceptors so every service reuses one consistent API boundary.
Practice
Create an Axios client for an order API with base URL, timeout, request logging in development, and centralized safe error normalization.