🚦 Understanding React Interceptors: Making API Calls Smarter

Hey devs! 👋
If you're working with React and making API calls using Axios, you might’ve come across the term interceptor. At first, it might sound complicated, but trust me, it’s a super helpful concept that can make your code cleaner and smarter.
In this blog, I’ll explain what interceptors are, why they’re useful, and how to use them in your React app. No complex jargon — just real, human-friendly talk. Let’s dive in! 🏊♂️
🤔 What is an Interceptor?
Imagine you’re sending a letter (your API request). Before the letter goes out, you want to:
Attach your name on it.
Check if it’s going to the right address.
Maybe log it for your records.
Similarly, interceptors let you intercept your request before it’s sent, or intercept the response before it reaches your app.
In simple words:
Interceptors are functions that run before a request is sent or before a response is received.
🔧 Why Use Interceptors?
Here’s why interceptors are super useful in a React app:
✅ Add Auth Tokens Automatically: Add your JWT or access token to every request without repeating code.
🚫 Handle Errors Globally: For example, redirect to login if a 401 error is returned.
📦 Transform Data: Modify request or response data if needed.
📋 Logging: Log every request or response for debugging.
🛠️ How to Use Axios Interceptors in React
import axios from 'axios';
// Create the axios instance
const axiosInstance = axios.create({
baseURL: 'https://dummyjson.com', // Replace with your API base URL
timeout: 1000,
headers: { 'Content-Type': 'application/json' }
});
// Add a request interceptor
axiosInstance.interceptors.request.use(
function (config) {
// Do something before the request is sent
// For example, add an authentication token to the headers
const token = localStorage.getItem('authToken'); // taking auth token from local Storage
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
function (error) {
// Handle the error
return Promise.reject(error);
}
);
🎯 Final Thoughts
React interceptors might feel like magic, but really, they’re just middlemen that help you automate, clean up, and centralize your API logic. Once you start using them, it’s hard to go back!
If you found this helpful, give it a 💙 or share it with your dev buddy. Got questions? Drop them in the comments — I’d love to help!
Subscribe to my newsletter
Read articles from Sarvesh Gupta directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
