Axios Interceptor
Axios interceptors are functions that run before a request is sent or after a response is received, allowing you to modify requests or handle responses globally. They are useful for adding authentication headers, logging requests, handling errors, or transforming response data. You can add interceptors using axios.interceptors.request.use for requests and axios.interceptors.response.use for responses.
Install dependencies
1npm i axios
Axios Interceptor Template
1import axios from 'axios';2import { BASE_URL } from '../env';34// Utility function to retrieve the token5const getToken = () => localStorage.getItem('authToken');67// Create an Axios instance with default configurations8const request = axios.create({9baseURL: BASE_URL, // Set the base API URL10withCredentials: true, // Enable cross-origin requests with credentials11headers: {12'Content-Type': 'application/json',13},14});1516// Request Interceptor: Attaches Authorization token to every request17request.interceptors.request.use(18(config) => {19const token = getToken();20if (token) {21config.headers['Authorization'] = `Bearer ${token}`;22}23return config;24},25(error) => Promise.reject(error)26);2728// Response Interceptor: Handles API response and errors29request.interceptors.response.use(30(response) => response,31(error) => handleErrorResponse(error)32);3334// Function to handle error responses35const handleErrorResponse = (error) => {36if (!error.response) {37console.error('❌ Network error or no response received:', error);38return Promise.reject({ message: 'Network Error', error });39}4041const { status } = error.response;42const currentPath = window.location.pathname;4344switch (status) {45case 401: // Unauthorized - Clear token and redirect to home46console.warn('⚠️ Unauthorized request (401) - Redirecting to login...');47localStorage.removeItem('authToken');48if (currentPath !== '/') window.location.href = '/';49break;5051case 429: // Too Many Requests - Retry mechanism (optional)52console.warn('⚠️ Too Many Requests (429) - Consider retrying...');53break;5455case 500: // Internal Server Error56console.error('🔥 Server Error (500):', error.response.data);57break;5859default:60console.error(`⚠️ API Error (${status}):`, error.response.data);61return Promise.reject(error);62}63};6465export default request;
Usage
1import request from './axios';23const getUser = async () => {4try {5const response = await request.get('/api/users');6return response.data; // Ensure the function returns useful data7} catch (error) {8console.error('Error fetching user:', error);9throw error; // Re-throw to allow calling function to handle it10}11};
⭐️ Got a question or feedback?
Feel free to reach out!