Logo

dev-resources.site

for different kinds of informations.

Magic of Axios Interceptors: A Deep Dive

Published at
1/14/2025
Categories
programming
beginners
productivity
frontend
Author
elvissautet
Author
11 person written this
elvissautet
open
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
Enter fullscreen mode Exit fullscreen mode

Or if you’re one of those cool kids using Yarn:

yarn add axios
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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));
Enter fullscreen mode Exit fullscreen mode

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));
Enter fullscreen mode Exit fullscreen mode

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;
});
Enter fullscreen mode Exit fullscreen mode

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);
  }
);
Enter fullscreen mode Exit fullscreen mode

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

Let’s connect and build something great together! 🚀

frontend Article's
30 articles in total
Favicon
[Boost]
Favicon
💡 Smarter UX, AI-Powered Design & HTML in 2025
Favicon
5 Fun Projects to Master ES6 Javascript Basics in 2025 đŸš€đŸ‘šâ€đŸ’»
Favicon
POST ABOUT AI'S INCREASING INFLUENCE IN CODING
Favicon
Truncating Text with Text-Overflow
Favicon
5 Tools Every Developer Should Know in 2025
Favicon
Checkout the new @defer in Angular
Favicon
Speed Up Your Frontend Development 10x with These Mock Tools 🚀
Favicon
Animated Select component using typescript, shadcn and framer-motion
Favicon
[Boost]
Favicon
Deferred loading with @defer: Optimize Your App's Performance
Favicon
Understanding React's useState with Callback Functions: A Deep Dive
Favicon
Hello World from Anti-chaos
Favicon
ćŸźć‰ç«Ż
Favicon
How to improve the Frontend part of the project using one button as an example :))))
Favicon
Things About Contexts in Front-end Projects
Favicon
37 Tip dĂ nh cho sá»± nghiệp của Frontend Develop (P1)
Favicon
How to Load Remote Components in Vue 3
Favicon
Emotional Resilience: A Key to Success Across Fields
Favicon
Middlewares: O que sĂŁo e como utilizar no Nuxt.JS
Favicon
Recreating the Interswitch Homepage with React and TailwindCSS.
Favicon
Create Stunning Gradual Div Reveals with JavaScript setTimeout and CSS Transitions
Favicon
Master GrapesJS: Build Stunning Web Pages and Seamlessly Integrate Grapes Studio SDK
Favicon
Magic of Axios Interceptors: A Deep Dive
Favicon
The Ultimate Guide to Trusting QuickBooks in Your Browser for Business Efficiency
Favicon
8 Common Front-End Developer Interview Questions For 2025
Favicon
[Boost]
Favicon
The System of UI Components in Front-end Projects
Favicon
Transform Your Web Development Workflow with These JavaScript Giants
Favicon
Animated Hover Logo using Typescript, Tailwind and Framer Motion

Featured ones: