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! 🚀

productivity Article's
30 articles in total
Productivity tools and practices enhance efficiency and help individuals and teams achieve more in less time.
Favicon
🚨 The Dangers of Developers Relying Exclusively on AI Without Understanding Fundamental Concepts
Favicon
🕒 What’s your most productive time of the day?
Favicon
The Career Killer Checklist: 10 Common Pitfalls to Avoid in 2025
Favicon
⚖️FROM Burn-Out TO Balance-Out (2/4)
Favicon
5 Free AI Design Tools For Designers!
Favicon
Vinny built CoverletterGPT to $500/month, a good read
Favicon
➡️💡Guide, Innovate, Succeed: Becoming a Software Development Leader 🚀
Favicon
🚀 New Book Release: "Navigate the Automation Seas" – A Practical Guide to Building Automation Frameworks
Favicon
Top 10 Web3 Careers for Success: Part 1
Favicon
got Tired of analysis paralyysis so i built an extensioon to get into flow faster
Favicon
Make Better Decisions as a Software Engineer Using the Pugh Matrix
Favicon
[Free Tool] I made an AI-powered content generator for RedNoteApp/Xiaohongshu
Favicon
5 Tools Every Developer Should Know in 2025
Favicon
The Perils of Presumption: Why Making Assumptions in Development is Bad
Favicon
[Boost]
Favicon
#131 — Use Association Table to Handle Interval Association
Favicon
How Project Time Tracking Can Enhance Budget Management and Resource Allocation
Favicon
Building An SAAS in 2025-Week 1
Favicon
[Boost]
Favicon
[Boost]
Favicon
🎁 20 Open Source Projects You Shouldn't Miss in 2025
Favicon
🌐 Embracing the Future: Cryptocurrency, Blockchain, and AI Synergy 🌐
Favicon
Ctrl Yourself! VS Code Shortcuts🎛️
Favicon
Top 50 Websites a Backend Developer Must Know 🖥️🔧🚀
Favicon
Unlocking the Power of GitHub Copilot: Your AI Pair Programmer
Favicon
Moving Apple Music MP3 Playlists To Android
Favicon
Digital Warm Up
Favicon
💡 How Do You Generate Your Cover Images for Blog Posts?
Favicon
What would you say are going to be the Top Trending Topics this 2025?
Favicon
Procrastinator’s Guide to Glory: Turning Wasted Time Into Career Gold with Open Source

Featured ones: