"Axios Interceptor"
Bootstrap 4.1.1 Snippet by Arjunverma

<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <!------ Include the above in your HEAD tag ----------> <div class="container"> <div class="row"> <h2>Axios Interceptor</h2> </div> </div>
import axios from 'axios' // Create Axios instance const apiClient = axios.create({ baseURL: process.env.REACT_APP_API_URL || 'http://localhost:5000', // API base URL headers: { 'Content-Type': 'application/json', }, }); // Request Interceptor apiClient.interceptors.request.use( (config) => { // Add Authorization token if available const token = localStorage.getItem('token'); if (token) { config.headers['Authorization'] = `Bearer ${token}`; } return config; }, (error) => { // Handle request errors return Promise.reject(error); } ); // Response Interceptor apiClient.interceptors.response.use( (response) => response, // Pass through successful responses (error) => { // Handle errors globally if (error.response && error.response.status === 401) { // Example: Redirect to login if unauthorized window.location.href = '/login'; } return Promise.reject(error); } ); export default apiClient;

Related: See More


Questions / Comments: