dev-resources.site
for different kinds of informations.
Magic of Axios Interceptors: A Deep Dive
Imagine this: Youâre building a sleek production-ready app, and your API calls are flying left, right, and center. But then, a wild API error appears! Now youâre scrambling to figure out where your token went, why your request wasnât authorized, and whether youâve really seen every error in existence. Sounds familiar? Enter Axios interceptorsâyour new best friend for managing HTTP requests and responses like a pro.
What Are Axios Interceptors, Anyway?
Think of interceptors as bouncers for your API calls. They sit at the gate, deciding what gets in (requests) and what comes out (responses). Need to attach an authentication token to every request? Interceptor. Want to catch all your 404 errors in one place? Interceptor. Looking to log every API call? Yep, you guessed itâinterceptor.
Why Should You Care?
Hereâs the deal: if youâre using fetch
, youâre manually adding headers and handling errors for every single request. Tedious, right? Axios interceptors handle all that boilerplate in one place, saving time and brainpower for the stuff that mattersâlike naming variables better than data1
and data2
.
TL;DR:
- Centralized logic: Write it once, use it everywhere.
- Error handling: Handle errors globally, like a boss.
- Token management: Automatically attach headers or refresh tokens.
- Data transformation: Change request/response data on the fly.
- Debugging made easy: Log every call without touching a single API function.
Setting the Stage: Installing Axios
First things first, letâs install Axios:
npm install axios
Or if youâre one of those cool kids using Yarn:
yarn add axios
And boom! Axios is ready to roll.
The Mighty Request Interceptor
Request interceptors let you modify your requests before theyâre sent. Hereâs how:
Example 1: Adding Authorization Headers
import axios from 'axios';
axios.interceptors.request.use(
(config) => {
// Attach the token to every request
const token = localStorage.getItem('authToken');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
(error) => {
// Handle request error
return Promise.reject(error);
}
);
// Now every request carries your token
axios.get('/api/protected').then(console.log).catch(console.error);
Why is this great? With fetch
, you'd be doing this:
const token = localStorage.getItem('authToken');
fetch('/api/protected', {
method: 'GET',
headers: {
'Authorization': `Bearer ${token}`
}
})
.then((response) => response.json())
.then(console.log)
.catch(console.error);
Looks repetitive, doesnât it? With Axios, itâs one and done.
The Savior: Response Interceptor
Response interceptors catch data on its way back. Want to standardize error messages or log responses? Do it here.
Example 2: Global Error Handling
axios.interceptors.response.use(
(response) => {
// Do something with response data
return response.data;
},
(error) => {
// Handle errors globally
if (error.response.status === 401) {
alert('Unauthorized! Please log in again.');
} else if (error.response.status === 404) {
console.error('Resource not found:', error.config.url);
} else {
console.error('Something went wrong:', error.message);
}
return Promise.reject(error);
}
);
axios.get('/api/unknown').catch((err) => console.error(err));
With fetch
, youâd need this:
fetch('/api/unknown')
.then((response) => {
if (!response.ok) {
if (response.status === 401) {
alert('Unauthorized! Please log in again.');
} else if (response.status === 404) {
console.error('Resource not found');
}
}
return response.json();
})
.catch((err) => console.error('Fetch error:', err));
Are your wrists tired yet?
Advanced Use Cases
Example 3: Transforming Requests
Need to JSON.stringify some data before sending it? No problem.
axios.interceptors.request.use((config) => {
if (config.data) {
config.data = JSON.stringify(config.data);
}
return config;
});
Example 4: Refreshing Tokens Automatically
If your API returns a 401 because the token expired, why not refresh it automatically?
axios.interceptors.response.use(
(response) => response,
async (error) => {
if (error.response.status === 401) {
const refreshToken = localStorage.getItem('refreshToken');
const { data } = await axios.post('/api/refresh-token', { refreshToken });
localStorage.setItem('authToken', data.token);
error.config.headers.Authorization = `Bearer ${data.token}`;
return axios(error.config); // Retry the original request
}
return Promise.reject(error);
}
);
Now your users can stay logged in seamlessly.
Why Axios Interceptors Shine in Production
- Consistency: Standardize headers, error messages, and data transformations across your app.
- Efficiency: Write less code while achieving more functionality.
- Scalability: Easily adapt to changes (e.g., a new auth flow) with minimal edits.
- Security: Manage tokens securely, log sensitive actions, and avoid exposing unnecessary data.
The Verdict: Axios vs. Fetch
Feature | Axios + Interceptors | Fetch |
---|---|---|
Global Error Handling | Built-in with interceptors | Manual |
Token Management | Easy with interceptors | Repeated per request |
Request/Response Transformations | Seamless | Manual |
Learning Curve | Moderate | Low |
Fetch is great for quick and simple requests, but for production-ready apps that demand scalability, consistency, and maintainability, Axios with interceptors is the way to go.
Final Words
Axios interceptors are like the secret sauce in your API spaghetti. Theyâre powerful, versatile, and save you from a ton of repetitive work. Whether youâre managing tokens, standardizing error handling, or transforming data, interceptors let you keep your codebase clean and efficient.
So, go ahead, give your API calls the interceptor treatmentâyour future self will thank you!
đ Connect With Me
- Website: elvissautet.com â Check out my portfolio and projects!
- LinkedIn: linkedin.com/in/elvissautet
- Twitter: twitter.com/elvisautet
- Facebook Page: fb.me/elvissautet
Letâs connect and build something great together! đ
Featured ones: