RuneHub
Tech Trends
RuneAI
RuneHub
Programming Education Platform

Master programming through interactive tutorials, hands-on projects, and personalized learning paths designed for every skill level.

Stay Updated

Learning Tracks

  • Programming Languages
  • Web Development
  • Data Structures & Algorithms
  • Backend Development

Practice

  • Interview Prep
  • Interactive Quizzes
  • Flashcards
  • Learning Roadmaps

Resources

  • Tutorials
  • Tech Trends
  • Search
  • RuneAI

Support

  • FAQ
  • About Us
  • Privacy Policy
  • Terms of Service
  • System Status
© 2026 RuneAI. All rights reserved.
RuneHub
Tech Trends
RuneAI
RuneHub
Programming Education Platform

Master programming through interactive tutorials, hands-on projects, and personalized learning paths designed for every skill level.

Stay Updated

Learning Tracks

  • Programming Languages
  • Web Development
  • Data Structures & Algorithms
  • Backend Development

Practice

  • Interview Prep
  • Interactive Quizzes
  • Flashcards
  • Learning Roadmaps

Resources

  • Tutorials
  • Tech Trends
  • Search
  • RuneAI

Support

  • FAQ
  • About Us
  • Privacy Policy
  • Terms of Service
  • System Status
© 2026 RuneAI. All rights reserved.
RuneHub
Tech Trends
RuneAI
RuneHub
Programming Education Platform

Master programming through interactive tutorials, hands-on projects, and personalized learning paths designed for every skill level.

Stay Updated

Learning Tracks

  • Programming Languages
  • Web Development
  • Data Structures & Algorithms
  • Backend Development

Practice

  • Interview Prep
  • Interactive Quizzes
  • Flashcards
  • Learning Roadmaps

Resources

  • Tutorials
  • Tech Trends
  • Search
  • RuneAI

Support

  • FAQ
  • About Us
  • Privacy Policy
  • Terms of Service
  • System Status
© 2026 RuneAI. All rights reserved.
RuneHub
Tech Trends
RuneAI

Programming Languages

1 topic · 323 articles

    • What is JavaScript? A Complete Beginner Guide
    • What is JavaScript Used For in Web Development
    • Is JavaScript Frontend or Backend? Full Guide
    • JavaScript vs Java: Core Differences Explained
    • How to Start Coding in JavaScript for Beginners
    • The Complete History of JavaScript Explained
    • Who Invented JavaScript? The Brendan Eich Story
    • How JavaScript Evolved from ES1 to Modern ES6+
    • The History of ECMAScript and JavaScript Guide
    • How JavaScript Works in the Browser Explained
    • What is a JavaScript Engine? A Complete Guide
    • How Browsers Read and Execute JavaScript Code
    • How to Run JavaScript in the Browser and Node
    • How to Execute JavaScript in Chrome DevTools
    • Deploying JS Apps Free with GitHub Student Plan
    • JS Variables Guide: How to Declare and Use Them
    • JavaScript Variable Naming Conventions & Rules
    • Global vs Local Variables in JavaScript Guide
    • var vs let vs const: JS Variable Declarations
    • Why You Should Stop Using var in JavaScript
    • When to Use let vs const in Modern JavaScript
    • JavaScript Data Types: A Complete Beginner Guide
    • What are Dynamic Data Types in JavaScript?
    • Primitive vs Reference Types in JS: Full Guide
    • How JavaScript Stores Primitive Values in Memory
    • JavaScript Type Conversion & Coercion Explained
    • JavaScript Implicit vs Explicit Type Conversion
    • Guide to JavaScript Template Literals & Strings
    • Creating Multi-Line Strings in JS With Backticks
    • JS Operators: Arithmetic, Logical & Comparison
    • JavaScript Operator Precedence: Complete Guide with Examples
    • How to Use the typeof Operator in JavaScript: Full Guide
    • What is NaN in JavaScript? A Complete Not a Number Guide
    • How to Check for NaN in JavaScript Using isNaN() Function
    • Undefined vs Null in JavaScript: Key Differences Explained
    • Why You Should Never Assign Undefined in JavaScript Code
    • How to Write Single and Multi-Line Comments in JavaScript
    • JavaScript Commenting Best Practices Every Coder Should Know
    • JavaScript Semicolons: Are They Required? A Complete Guide
    • Automatic Semicolon Insertion (ASI) in JavaScript Explained
    • JavaScript Strict Mode ('use strict') Explained
    • Common Errors Caught by JavaScript Strict Mode
    • JavaScript Console Methods: log, warn & errors
    • Grouping Logs Together with console.group() JS
    • Basic JavaScript Debugging Tips for Beginners
    • How to Read and Understand JavaScript Stack Traces
    • JavaScript If Statement: A Complete Beginner Guide
    • How to Write If Else Statements in JS: Full Guide
    • JavaScript Else If: Chaining Multiple Conditions
    • JS Switch Statement vs If Else: Which is Better?
    • How to Use the JavaScript Switch Case Full Guide
    • JavaScript Ternary Operator: Complete Syntax Guide
    • Chaining Ternary Operators in JavaScript Tutorial
    • JS For Loop Syntax: A Complete Guide for Beginners
    • How to Loop Through Arrays using JS For Loops Guide
    • JavaScript While Loop Explained: A Complete Guide
    • How to Avoid Infinite Loops in JS: Full Tutorial
    • JS Do-While Loop: Syntax and Practical Use Cases
    • JavaScript Break Statement: Exiting Loops Early
    • JavaScript Continue Statement: Skipping Iterations
    • How to Write Nested Loops in JavaScript: Tutorial
    • Optimizing JavaScript Loops for Fast Performance
    • What are Truthy and Falsy Values in JavaScript?
    • JavaScript Logical Short-Circuiting Complete Guide
    • What is a Function in JavaScript? Beginner Guide
    • How to Declare and Call a JavaScript Function
    • JavaScript Function Expressions vs Declarations
    • JavaScript Arrow Functions: A Complete ES6 Guide
    • When to Avoid Using Arrow Functions in JavaScript
    • JS Function Parameters vs Arguments: Differences
    • How to Use Default Parameters in JS Functions
    • JavaScript Rest Parameters: A Complete Tutorial
    • What is a Callback Function in JS? Full Tutorial
    • How to Pass a Function as an Argument in JS Guide
    • Pure vs Impure Functions in JavaScript Explained
    • Writing Pure Functions in JS: A Complete Tutorial
    • JavaScript IIFE: Immediately Invoked Functions
    • How to Use Recursion in JavaScript: Full Tutorial
    • Preventing Stack Overflow in JavaScript Recursion
    • Higher-Order Functions in JavaScript: Full Guide
    • Returning Functions from Functions in JavaScript
    • JavaScript Function Scope: Local vs Global Scope
    • Understanding JavaScript Hoisting for Beginners
    • JavaScript Execution Context: A Complete Tutorial
    • What is an Array in JavaScript? A Complete Guide
    • How to Create and Initialize JavaScript Arrays
    • Accessing and Modifying JS Array Elements Guide
    • JS Array Push and Pop Methods: A Complete Guide
    • JS Array Shift and Unshift Methods: Full Tutorial
    • JavaScript Array Slice Method: A Complete Guide
    • JavaScript Array Splice Method: Complete Tutorial
    • JS Array Slice vs Splice: What is the Difference?
    • How to Use the JavaScript Array Map Method Today
    • JavaScript Array Filter Method: Complete Tutorial
    • Using the JavaScript Array Reduce Method Guide
    • JavaScript Array forEach Loop: Complete Tutorial
    • JS Array Map vs forEach: Which Should You Use?
    • JavaScript Array Find and findIndex Methods Guide
    • JS Array Some and Every Methods: Complete Guide
    • How to Sort Arrays in JavaScript: Complete Guide
    • Sorting Numbers Correctly in JS Arrays Tutorial
    • JS Array Flat Method: Flatten Nested Arrays Fast
    • JavaScript Array flatMap Method: Complete Guide
    • JavaScript Array Destructuring: Complete Tutorial
    • JavaScript Functions Explained: From Basic to Advanced Concepts
    • JavaScript Loops Tutorial: for, while & do-while
    • JavaScript Conditional Statements: if, else & switch Guide
    • Learn JavaScript Step by Step Tutorial with Real Examples
    • JavaScript Objects & Arrays: Complete Tutorial
    • JS Spread Operator for Arrays: Complete Tutorial
    • How to Merge Two Arrays in JavaScript Full Guide
    • Removing Duplicates from JavaScript Arrays Guide
    • Top JS Array Methods Interview Questions to Know
    • What is an Object in JavaScript? Beginner Guide
    • How to Create Objects in JavaScript: Full Guide
    • Accessing Object Properties in JS: Full Tutorial
    • JS Objects: Dot Notation vs Bracket Notation
    • Adding and Deleting Properties in JS Objects
    • JavaScript Object Methods: A Complete Tutorial
    • The 'this' Keyword in JavaScript Objects Guide
    • JavaScript Object Destructuring Complete Guide
    • Renaming Variables in JS Object Destructuring
    • How to Use Object.assign in JavaScript Properly
    • JS Object Keys, Values, and Entries Full Guide
    • How to Loop Through a JavaScript Object Tutorial
    • JS Optional Chaining (?.) Syntax Complete Guide
    • JS Nullish Coalescing Operator (??) Full Guide
    • How to Clone a JavaScript Object Without Errors
    • Shallow Copy vs Deep Copy in JavaScript Objects
    • What is the DOM in JavaScript? A Beginner Guide
    • Understanding the HTML DOM Tree Structure Guide
    • Selecting DOM Elements in JavaScript Full Guide
    • How to Use JS querySelector and querySelectorAll
    • How to Use getElementById in JS: Complete Guide
    • JS getElementsByClassName vs querySelector Guide
    • How to Change Text Content Using JavaScript DOM
    • innerText vs textContent in JavaScript Explained
    • Using innerHTML Safely in JavaScript DOM Methods
    • Changing CSS Styles with JavaScript DOM Methods
    • Building Beautiful JS UIs with Inter & Outfit
    • Adding and Removing CSS Classes with JavaScript
    • How to Use classList toggle in JavaScript DOM
    • Creating HTML Elements with JavaScript DOM Guide
    • Appending Elements to the DOM in JS: Full Guide
    • Removing HTML Elements Using JavaScript Methods
    • How to Add Event Listeners in JS: Complete Guide
    • Handling Click Events in JavaScript: Full Guide
    • JavaScript Keyboard Events: keyup and keydown
    • JavaScript Event Bubbling Explained for Beginners
    • JavaScript Event Delegation: Complete Tutorial
    • Using preventDefault() in JavaScript Full Guide
    • JavaScript Form Handling and Submission Tutorial
    • Basic Form Validation with JavaScript Tutorial
    • Build a JavaScript Todo App: Beginner DOM Project
    • Build a JS Counter App: Beginner DOM Mini Project
    • Build a JS Calculator: Beginner DOM Mini Project
    • JavaScript Closures Deep Dive: Complete Guide
    • Practical Use Cases for JS Closures in Real Apps
    • How to Prevent Memory Leaks in JavaScript Closures
    • JavaScript Lexical Scope: A Complete Tutorial
    • How Lexical Environment Works in JavaScript
    • JS Execution Context Deep Dive: Full Tutorial
    • Understanding the JavaScript Call Stack Guide
    • How the JS Call Stack Handles Function Execution
    • JavaScript setTimeout Behavior: Complete Guide
    • How setInterval Works in JavaScript: Architecture
    • Clearing Timeouts and Intervals in JavaScript
    • The JavaScript Event Loop Explained in Detail
    • JS Microtasks vs Macrotasks: A Complete Guide
    • JavaScript Callbacks vs Promises: Full Tutorial
    • Avoiding Callback Hell in JavaScript: Complete Tutorial
    • JavaScript Promise Chaining: A Complete Guide
    • How to Handle Promise Rejections in JavaScript
    • How to Use Promise.all in JavaScript: Complete Tutorial
    • Using Promise.allSettled for Reliable JavaScript APIs
    • How to Use Promise.race in JavaScript: Complete Guide
    • JavaScript async/await: Complete Tutorial Guide
    • Converting Promises to async/await in JavaScript
    • JavaScript try/catch Tutorial: Advanced Error Handling
    • Handling Async Errors With try/catch in JavaScript
    • Creating Custom Errors in JavaScript: Complete Tutorial
    • Extending the JavaScript Error Class: Full Guide
    • The JavaScript Prototype Chain: Complete Guide
    • JavaScript __proto__ vs prototype: What Is the Difference?
    • How Prototypal Inheritance Works in JavaScript
    • Modifying the JavaScript Object Prototype: Guide
    • JS Constructor Functions: A Complete Tutorial
    • JavaScript Classes Explained: Complete Tutorial
    • JavaScript Class Inheritance: Complete Tutorial
    • Using the super Keyword in JavaScript Classes
    • JavaScript Static Methods: A Complete Tutorial
    • Encapsulation in JavaScript: Complete Tutorial
    • Creating Private Class Fields in Modern JS
    • Polymorphism in JavaScript: Complete Tutorial
    • The JavaScript this Keyword: Full Deep Dive
    • How Arrow Functions Change this in JavaScript
    • Losing this in JavaScript Callbacks Explained
    • JS bind, call, and apply Methods: Full Tutorial
    • When to Use JS bind vs call vs apply: Full Guide
    • JS let vs const: An Advanced Memory Deep Dive
    • Advanced Arrow Functions in JS: Complete Guide
    • Returning Objects from JS Arrow Functions Guide
    • Advanced Array and Object Destructuring Guide
    • Renaming Variables During JS Destructuring Guide
    • JS Spread vs Rest Operator Complete Tutorial
    • Copying Nested Objects With the JS Spread Operator
    • JavaScript ES6 Modules Import Export Guide
    • JavaScript Default Exports Complete Tutorial
    • JavaScript Named Exports a Complete Tutorial
    • Dynamic Imports in JavaScript Complete Guide
    • Advanced JS Optional Chaining Complete Guide
    • Advanced JS Nullish Coalescing Full Tutorial
    • Logical Assignment Operators in JS Complete Guide
    • Deploying JS Modules Using the GitHub Student Plan
    • JavaScript Tagged Template Literals Deep Dive
    • Building Custom JS String Parsers Full Tutorial
    • The JS Event Loop Architecture Complete Guide
    • Browser Web APIs in JavaScript Complete Guide
    • How to Use the JS Fetch API Complete Tutorial
    • Handling POST Requests With JS Fetch API Guide
    • Uploading Files via JS Fetch API Complete Guide
    • Building a Dynamic JS Portfolio at Parthh.in
    • How to Use Axios in JavaScript: Complete Guide
    • Axios Interceptors in JavaScript: Complete Guide
    • Advanced API Error Handling in JS: Full Guide
    • Debouncing in JavaScript: A Complete Tutorial
    • Building a Search Bar with JS Debouncing Guide
    • Throttling in JavaScript: A Complete Tutorial
    • Scroll Event Throttling in JavaScript: Full Guide
    • Rate Limiting in JavaScript: Complete Tutorial
    • Advanced JS Promise Patterns: Complete Tutorial
    • API Retry Patterns in JavaScript: Full Tutorial
    • Using AbortController in JS: Complete Tutorial
    • Canceling Fetch Requests in JavaScript Full Guide
    • JavaScript Web Streams API: A Complete Tutorial
    • JavaScript Async Generators: Complete Tutorial
    • JS LocalStorage API Guide: A Complete Tutorial
    • Storing Complex Objects in JS LocalStorage Guide
    • JS SessionStorage API Guide: Complete Tutorial
    • How to Manage Cookies in JS: Complete Tutorial
    • Parsing and Deleting Browser Cookies With JS
    • JS Geolocation API Guide: A Complete Tutorial
    • Tracking User Location With JavaScript Geolocation
    • JavaScript Clipboard API: A Complete Tutorial
    • Building a Copy to Clipboard Button in JavaScript
    • JavaScript History API Guide: Complete Tutorial
    • Creating an SPA Router With the JS History API
    • JS Intersection Observer API: Complete Tutorial
    • Implementing Infinite Scroll with JS Observers
    • JavaScript Mutation Observer: Complete Tutorial
    • Tracking DOM Changes with JS Mutation Observers
    • JavaScript Notifications API: Complete Tutorial
    • Requesting Desktop Notification Permissions in JS
    • The Web Storage API: Local vs Session Storage
    • Using the Web Audio API in JavaScript Full Guide
    • Fixing JavaScript Memory Leaks: Complete Guide
    • How to Find and Fix Memory Leaks in JavaScript
    • Identifying Detached DOM Elements in JavaScript
    • JavaScript Garbage Collection Complete Guide
    • How V8 Garbage Collector Works in JavaScript
    • Mark-and-Sweep Algorithm in JS: Full Tutorial
    • JavaScript Profiling: Advanced Performance Guide
    • Using Chrome DevTools for JS Performance Tuning
    • How to Measure JavaScript Execution Time Accurately
    • JS Code Splitting: Advanced Performance Guide
    • Implementing Route-Level Code Splitting in JS
    • Lazy Loading in JavaScript: Complete Tutorial
    • How to Lazy Load Images and Components in JS
    • JavaScript Tree Shaking: A Complete Tutorial
    • Removing Dead Code with JS Tree Shaking Guide
    • JavaScript Bundlers: An Advanced Architecture
    • Webpack vs Vite vs Rollup: JS Bundler Guide
    • Optimizing JavaScript for Core Web Vitals Guide
    • Minifying and Uglifying JavaScript Code for Production
    • JavaScript Module Pattern: Advanced Tutorial
    • Implementing the Revealing Module Pattern JS
    • JavaScript Singleton Pattern: Complete Guide
    • When to Use the Singleton Pattern in JS Apps
    • JavaScript Observer Pattern: Complete Guide
    • Building a Reactive UI with the JS Observer
    • The JavaScript Factory Pattern: Complete Guide
    • Creating Dynamic Objects with JS Factory Pattern
    • JavaScript Strategy Pattern: Complete Guide
    • The JavaScript Proxy Pattern: Complete Guide
    • JavaScript Decorator Pattern: Complete Guide
    • Using Decorators for Logging in JS Architecture
    • The JavaScript Pub/Sub Pattern: Complete Guide
    • Building an Event Bus with JS Pub/Sub Pattern
    • JavaScript MVC Architecture: Complete Guide
    • Building Vanilla JS Apps with MVC Architecture
    • Vanilla JS State Management for Advanced Apps
    • Building Enterprise UI Systems in Vanilla JS
    • JavaScript V8 Engine Internals: Complete Guide
    • How the Google V8 Engine Compiles JavaScript
    • JavaScript Parsing and Compilation: Full Guide
    • Abstract Syntax Trees (AST) in JavaScript Guide
    • V8 Hidden Classes in JavaScript: Full Tutorial
    • Optimizing JS Object Creation for V8 Engine
    • JavaScript Inline Caching: A Complete Tutorial
    • JavaScript Bytecode Explained: Complete Guide
    • Ignition Interpreter and JS Bytecode Tutorial
    • JavaScript JIT Compilation Advanced Tutorial
    • TurboFan Compiler and JS Optimization Guide
    • JavaScript Event Loop Internals Full Guide
    • Understanding libuv and JS Asynchronous I/O
    • Call Stack vs Task Queue vs Microtask Queue in JS
    • Advanced JavaScript Proxies Complete Guide
    • Data Binding with JS Proxies Complete Guide
    • Intercepting Object Calls with JS Proxy Traps
    • JavaScript Reflect API Advanced Architecture
    • Using Reflect and Proxy Together in JavaScript
    • JavaScript WeakMap and WeakSet Complete Guide
    • Preventing Memory Leaks with JS WeakMaps Guide
    • JavaScript Generators Deep Dive Full Guide
    • Handling Async Flows with JS Generator Functions
    • Advanced JavaScript Iterators Complete Guide
    • Creating JavaScript Custom Iterables Full Guide
    • JS Metaprogramming Advanced Architecture Guide
    • Writing Self-Modifying Code in JS Architecture
    • Creating Advanced UI Frameworks in JavaScript
    • JavaScript Macros and Abstract Code Generation
    • Advanced Web Workers for High Performance JS
    • OffscreenCanvas API in JS for UI Performance
Previous
How to Use Axios in JavaScript: Complete Guide
15 min · intermediate
Next
Advanced API Error Handling in JS: Full Guide
16 min · intermediate
Home/Tutorials/Programming Languages/JavaScript

Axios Interceptors in JavaScript: Complete Guide

A complete guide to Axios interceptors in JavaScript. Covers request interceptors for auth token injection and logging, response interceptors for error handling and token refresh, interceptor execution order, ejecting interceptors, and practical patterns including retry logic, loading indicators, error normalization, and request caching.

JavaScriptintermediate
RuneHub Team
RuneHub Team
March 3, 2026
15 min read
RuneHub Team
RuneHub Team
Mar 3, 2026
15 min read

Axios interceptors let you run code before a request is sent or after a response is received. They are middleware for HTTP calls. Common uses include injecting authentication tokens, logging requests, refreshing expired tokens, normalizing errors, and adding retry logic. This guide covers every interceptor pattern you will encounter in production applications.

How Interceptors Work

CodeCode
Request Flow:
  Your Code --> Request Interceptors --> Network --> Response Interceptors --> Your Code

Request Interceptors: modify config before sending
Response Interceptors: transform data or handle errors after receiving

Request Interceptors

A request interceptor receives the Axios config object and must return it (or a promise that resolves to it).

javascriptjavascript
import axios from "axios";
 
const api = axios.create({
  baseURL: "https://api.example.com/v2",
});
 
// Add auth token to every request
api.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem("accessToken");
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

The first function handles the fulfilled case (config is ready). The second handles the rejected case (something failed before sending).

Response Interceptors

A response interceptor has two handlers: one for successful responses (2xx) and one for errors (non-2xx or network failures).

javascriptjavascript
api.interceptors.response.use(
  (response) => {
    // Any 2xx status triggers this
    return response;
  },
  (error) => {
    // Any non-2xx status or network error triggers this
    if (error.response) {
      console.error(`HTTP ${error.response.status}: ${error.response.data.message}`);
    } else if (error.request) {
      console.error("Network error: no response received");
    }
    return Promise.reject(error);
  }
);

Interceptor Execution Order

PhaseOrderDescription
Request interceptorsLIFO (last added runs first)Added later = runs earlier
Response interceptorsFIFO (first added runs first)Added first = runs earliest
Error propagationChainedRejected promise skips fulfilled handlers
javascriptjavascript
// Request interceptors execute in reverse order
api.interceptors.request.use((config) => {
  console.log("Interceptor A"); // runs second
  return config;
});
 
api.interceptors.request.use((config) => {
  console.log("Interceptor B"); // runs first
  return config;
});
 
// Response interceptors execute in order added
api.interceptors.response.use((res) => {
  console.log("Interceptor C"); // runs first
  return res;
});
 
api.interceptors.response.use((res) => {
  console.log("Interceptor D"); // runs second
  return res;
});
 
// Output: B, A, C, D

Token Refresh Pattern

The most common production interceptor pattern. When the server returns 401, the interceptor refreshes the token and retries the original request.

javascriptjavascript
let isRefreshing = false;
let failedQueue = [];
 
function processQueue(error, token = null) {
  failedQueue.forEach(({ resolve, reject }) => {
    if (error) {
      reject(error);
    } else {
      resolve(token);
    }
  });
  failedQueue = [];
}
 
api.interceptors.response.use(
  (response) => response,
  async (error) => {
    const originalRequest = error.config;
 
    // Only handle 401 errors, skip if already retrying
    if (error.response?.status !== 401 || originalRequest._retry) {
      return Promise.reject(error);
    }
 
    if (isRefreshing) {
      // Queue this request until refresh completes
      return new Promise((resolve, reject) => {
        failedQueue.push({ resolve, reject });
      }).then((token) => {
        originalRequest.headers.Authorization = `Bearer ${token}`;
        return api(originalRequest);
      });
    }
 
    originalRequest._retry = true;
    isRefreshing = true;
 
    try {
      const refreshToken = localStorage.getItem("refreshToken");
      const { data } = await axios.post("https://api.example.com/auth/refresh", {
        refreshToken,
      });
 
      const newToken = data.accessToken;
      localStorage.setItem("accessToken", newToken);
      localStorage.setItem("refreshToken", data.refreshToken);
 
      api.defaults.headers.common.Authorization = `Bearer ${newToken}`;
      processQueue(null, newToken);
 
      originalRequest.headers.Authorization = `Bearer ${newToken}`;
      return api(originalRequest);
    } catch (refreshError) {
      processQueue(refreshError, null);
      localStorage.removeItem("accessToken");
      localStorage.removeItem("refreshToken");
      window.location.href = "/auth";
      return Promise.reject(refreshError);
    } finally {
      isRefreshing = false;
    }
  }
);

This pattern queues concurrent requests that fail with 401, refreshes the token once, then replays all queued requests with the new token. See how to use Axios in JavaScript complete guide for Axios fundamentals.

Retry Interceptor

javascriptjavascript
function createRetryInterceptor(instance, maxRetries = 3) {
  instance.interceptors.response.use(null, async (error) => {
    const config = error.config;
 
    // Only retry on network errors or 5xx
    const shouldRetry =
      !error.response || (error.response.status >= 500 && error.response.status < 600);
 
    if (!shouldRetry || (config._retryCount || 0) >= maxRetries) {
      return Promise.reject(error);
    }
 
    config._retryCount = (config._retryCount || 0) + 1;
 
    // Exponential backoff: 1s, 2s, 4s
    const delay = Math.pow(2, config._retryCount - 1) * 1000;
    await new Promise((resolve) => setTimeout(resolve, delay));
 
    console.log(`Retrying request (${config._retryCount}/${maxRetries}): ${config.url}`);
    return instance(config);
  });
}
 
createRetryInterceptor(api, 3);

Retry Configuration Table

Retry AttemptDelayCumulative WaitStatus Codes Retried
11 second1 second500, 502, 503, 504 + network errors
22 seconds3 seconds500, 502, 503, 504 + network errors
34 seconds7 seconds500, 502, 503, 504 + network errors

Never retry 4xx errors (except 429 Rate Limit). Client errors indicate a problem with the request itself, not a transient server issue.

Loading State Interceptor

javascriptjavascript
let activeRequests = 0;
 
function showLoader() {
  document.getElementById("global-loader").classList.add("visible");
}
 
function hideLoader() {
  document.getElementById("global-loader").classList.remove("visible");
}
 
api.interceptors.request.use((config) => {
  if (!config.silent) {
    activeRequests++;
    showLoader();
  }
  return config;
});
 
api.interceptors.response.use(
  (response) => {
    if (!response.config.silent) {
      activeRequests--;
      if (activeRequests === 0) hideLoader();
    }
    return response;
  },
  (error) => {
    if (!error.config?.silent) {
      activeRequests--;
      if (activeRequests === 0) hideLoader();
    }
    return Promise.reject(error);
  }
);
 
// Usage: suppress loader for background polling
api.get("/api/notifications", { silent: true });

The activeRequests counter ensures the loader stays visible until all pending requests complete. The silent flag lets specific requests skip the loader.

Error Normalization

javascriptjavascript
class AppError {
  constructor(message, code, details = null) {
    this.message = message;
    this.code = code;
    this.details = details;
    this.timestamp = new Date().toISOString();
  }
}
 
api.interceptors.response.use(
  (response) => response,
  (error) => {
    let normalized;
 
    if (error.response) {
      const { status, data } = error.response;
      const messages = {
        400: data.message || "Invalid request",
        401: "Please log in to continue",
        403: "You do not have permission for this action",
        404: "The requested resource was not found",
        409: "This resource already exists",
        422: "Please check your input and try again",
        429: "Too many requests. Please wait and try again",
        500: "Something went wrong on our end",
      };
 
      normalized = new AppError(
        messages[status] || `Server error (${status})`,
        status,
        data.errors || null
      );
    } else if (error.request) {
      normalized = new AppError(
        "Unable to reach the server. Check your connection.",
        0,
        null
      );
    } else {
      normalized = new AppError(error.message, -1, null);
    }
 
    return Promise.reject(normalized);
  }
);

Every error that reaches your components is now an AppError with a user-friendly message, a status code, and optional validation details. No need to parse error shapes in every component.

Request Logging

javascriptjavascript
api.interceptors.request.use((config) => {
  config._startTime = Date.now();
  console.log(`[API] ${config.method.toUpperCase()} ${config.url}`);
  return config;
});
 
api.interceptors.response.use(
  (response) => {
    const duration = Date.now() - response.config._startTime;
    console.log(
      `[API] ${response.config.method.toUpperCase()} ${response.config.url} - ${response.status} (${duration}ms)`
    );
    return response;
  },
  (error) => {
    if (error.config?._startTime) {
      const duration = Date.now() - error.config._startTime;
      const status = error.response?.status || "NETWORK_ERROR";
      console.log(
        `[API] ${error.config.method.toUpperCase()} ${error.config.url} - ${status} (${duration}ms)`
      );
    }
    return Promise.reject(error);
  }
);

Ejecting Interceptors

javascriptjavascript
// Store the interceptor ID
const authInterceptor = api.interceptors.request.use((config) => {
  config.headers.Authorization = `Bearer ${getToken()}`;
  return config;
});
 
// Remove it later
api.interceptors.request.eject(authInterceptor);

Ejecting is useful when a user logs out (remove auth interceptor) or when you need to temporarily disable retry logic for a specific flow.

Composing Multiple Interceptors

javascriptjavascript
function setupInterceptors(instance) {
  // 1. Auth token injection (request)
  instance.interceptors.request.use((config) => {
    const token = localStorage.getItem("accessToken");
    if (token) config.headers.Authorization = `Bearer ${token}`;
    return config;
  });
 
  // 2. Request timing (request)
  instance.interceptors.request.use((config) => {
    config._startTime = Date.now();
    return config;
  });
 
  // 3. Extract data (response) - unwrap response.data
  instance.interceptors.response.use(
    (response) => response,
    (error) => Promise.reject(error)
  );
 
  // 4. Token refresh (response)
  // ... token refresh interceptor from above
 
  // 5. Error normalization (response - runs last)
  // ... error normalization from above
}
 
const api = axios.create({ baseURL: "https://api.example.com" });
setupInterceptors(api);
 
export default api;

Remember: request interceptors run LIFO (timing runs before auth), response interceptors run FIFO (data extraction runs before error normalization).

Testing With Interceptors

javascriptjavascript
import axios from "axios";
 
function createTestClient() {
  const client = axios.create({ baseURL: "http://localhost:3000" });
 
  // Attach interceptors
  setupInterceptors(client);
 
  return client;
}
 
// In tests, mock the adapter
async function testRetryInterceptor() {
  const client = createTestClient();
  let callCount = 0;
 
  // Override adapter to simulate failure then success
  client.defaults.adapter = async (config) => {
    callCount++;
    if (callCount < 3) {
      const error = new Error("Server Error");
      error.response = { status: 500, data: {} };
      error.config = config;
      throw error;
    }
    return { data: { success: true }, status: 200, config };
  };
 
  const result = await client.get("/test");
  console.assert(callCount === 3, "Should retry twice before succeeding");
  console.assert(result.data.success === true, "Should return success");
}
Rune AI

Rune AI

Key Insights

  • Request interceptors run LIFO: The last interceptor added runs first, which affects the order of header modifications and logging
  • Token refresh with queue: When a 401 occurs, queue all concurrent requests, refresh once, then replay them all with the new token
  • Never retry client errors: Only retry network errors and 5xx responses; 4xx errors indicate the request itself is wrong
  • Error normalization centralizes parsing: Convert every error into a consistent AppError shape so components never parse raw Axios error objects
  • Eject interceptors for cleanup: Store the interceptor ID and call eject() when the interceptor is no longer needed, such as after logout
Powered by Rune AI

Frequently Asked Questions

Can I use interceptors with the global axios instance?

Yes, `axios.interceptors.request.use(...)` works on the global instance. However, creating a dedicated instance with `axios.create()` is better because it avoids polluting the global configuration shared by third-party libraries.

Do interceptors affect all HTTP methods?

Yes. Both request and response interceptors apply to GET, POST, PUT, DELETE, PATCH, and all other methods unless you add conditional logic inside the interceptor.

What happens if a request interceptor throws an error?

The request is never sent. The error propagates to the response interceptor error handler, then to the calling code's catch block.

How do I skip an interceptor for a specific request?

dd a custom flag to the config: `api.get("/url", { skipAuth: true })`. Then check for it in the interceptor: `if (config.skipAuth) return config;`.

Can interceptors modify the response data?

Yes. Return a modified response from the fulfilled handler: `return { ...response, data: transform(response.data) }`. This is commonly used to unwrap nested API response formats like `{ data: { users: [...] } }`.

Conclusion

Axios interceptors provide a centralized place to manage cross-cutting concerns in HTTP communication. Request interceptors handle auth tokens, logging, and request timestamps. Response interceptors handle token refresh, retry logic, error normalization, and loading states. The key architectural insight is composing small, focused interceptors that each handle one concern, stacked in a predictable execution order (LIFO for requests, FIFO for responses). For the Axios fundamentals these interceptors build on, see how to use Axios in JavaScript complete guide. For how the event loop processes these async HTTP calls under the hood, see the JS event loop architecture complete guide. For the native Fetch alternative, see how to use the JS Fetch API complete tutorial.

Tags

Intermediate JavaScriptInterceptorsHTTPAxiosJavaScript
Previous
How to Use Axios in JavaScript: Complete Guide
15 min read · intermediate
Next
Advanced API Error Handling in JS: Full Guide
16 min read · intermediate

More in this topic

OffscreenCanvas API in JS for UI Performance

Master the OffscreenCanvas API to offload rendering from the main thread. Covers worker-based 2D and WebGL rendering, animation loops inside workers, bitmap transfer, double buffering, chart rendering pipelines, image processing, and performance measurement strategies.

Advanced Web Workers for High Performance JS

Master Web Workers for truly parallel JavaScript execution. Covers dedicated and shared workers, structured cloning, transferable objects, SharedArrayBuffer with Atomics, worker pools, task scheduling, Comlink RPC patterns, module workers, and performance profiling strategies.

JavaScript Macros and Abstract Code Generation

Master JavaScript code generation techniques for compile-time and runtime metaprogramming. Covers AST manipulation, Babel plugin authorship, tagged template literals as macros, code generation pipelines, source-to-source transformation, compile-time evaluation, and safe eval alternatives.

On this page

    Share
    RuneHub
    Programming Education Platform

    Master programming through interactive tutorials, hands-on projects, and personalized learning paths designed for every skill level.

    Stay Updated

    Learning Tracks

    • Programming Languages
    • Web Development
    • Data Structures & Algorithms
    • Backend Development

    Practice

    • Interview Prep
    • Interactive Quizzes
    • Flashcards
    • Learning Roadmaps

    Resources

    • Tutorials
    • Tech Trends
    • Search
    • RuneAI

    Support

    • FAQ
    • About Us
    • Privacy Policy
    • Terms of Service
    • System Status
    © 2026 RuneAI. All rights reserved.