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
Elvis Sautet
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

Let’s connect and build something great together! 🚀

Featured ones: