0
0
Vueframework~15 mins

Axios interceptors in Vue - Deep Dive

Choose your learning style9 modes available
Overview - Axios interceptors
What is it?
Axios interceptors are functions that run before a request is sent or after a response is received when using Axios, a tool to make web requests. They let you change or check the request or response automatically without changing each call. This helps manage things like adding login tokens or handling errors in one place. Interceptors work behind the scenes to make your code cleaner and easier to maintain.
Why it matters
Without interceptors, you would have to repeat the same code to add headers or handle errors every time you make a web request. This repetition wastes time and can cause mistakes. Interceptors solve this by letting you write that code once and apply it everywhere automatically. This makes your app more reliable and easier to update, especially when dealing with many requests.
Where it fits
Before learning interceptors, you should understand how to make basic Axios requests in Vue and how promises work in JavaScript. After mastering interceptors, you can learn about advanced error handling, token refresh strategies, and global state management for authentication in Vue apps.
Mental Model
Core Idea
Axios interceptors are like automatic checkpoints that modify or check every request or response before it continues.
Think of it like...
Imagine a security guard at a building entrance who checks every visitor’s ID and sometimes adds a visitor badge before letting them in. Similarly, interceptors check and modify requests or responses automatically.
┌───────────────┐       ┌───────────────┐       ┌───────────────┐
│  Your Code    │──────▶│ Request       │──────▶│ Server        │
│ (makes call)  │       │ Interceptor   │       │ (response)    │
└───────────────┘       └───────────────┘       └───────────────┘
                              │                        ▲
                              ▼                        │
                       ┌───────────────┐       ┌───────────────┐
                       │ Response      │◀──────│ Server        │
                       │ Interceptor   │       │ (sends data)  │
                       └───────────────┘       └───────────────┘
Build-Up - 7 Steps
1
FoundationWhat is Axios and basic requests
🤔
Concept: Learn what Axios is and how to make simple web requests.
Axios is a tool to send and receive data from servers using JavaScript. You can ask for data with axios.get('url') or send data with axios.post('url', data). These calls return promises that resolve when the server replies.
Result
You can fetch or send data to a server and get the response in your Vue app.
Understanding basic Axios requests is essential because interceptors work by modifying these requests and responses.
2
FoundationPromises and asynchronous flow
🤔
Concept: Understand how promises handle asynchronous requests and responses.
When you make a request with Axios, it returns a promise. This promise waits for the server to respond. You use .then() to handle success and .catch() for errors. This lets your app keep running while waiting for data.
Result
You can write code that reacts to server responses or errors without freezing the app.
Knowing promises helps you understand how interceptors can modify requests or responses before your code handles them.
3
IntermediateAdding request interceptors
🤔Before reading on: do you think request interceptors can modify the request headers or body? Commit to your answer.
Concept: Request interceptors let you change or add information to every request before it is sent.
You add a request interceptor with axios.interceptors.request.use(function(config) { /* modify config */ return config; }). For example, you can add an authorization token to headers so every request includes it automatically.
Result
Every request sent by Axios now includes the added headers or changes without repeating code.
Understanding request interceptors helps you centralize common request modifications, reducing errors and repetition.
4
IntermediateUsing response interceptors
🤔Before reading on: do you think response interceptors can catch errors globally or only after your code handles them? Commit to your answer.
Concept: Response interceptors let you handle or change data from the server before your code sees it.
You add a response interceptor with axios.interceptors.response.use(function(response) { return response; }, function(error) { /* handle error */ return Promise.reject(error); }). This can catch errors like expired tokens and trigger login or refresh automatically.
Result
Your app can handle server errors or modify responses in one place, improving consistency.
Knowing response interceptors allows you to manage errors and data transformations globally, simplifying your app logic.
5
IntermediateEjecting interceptors to avoid leaks
🤔Before reading on: do you think interceptors stay forever once added, or can they be removed? Commit to your answer.
Concept: Interceptors can be removed to prevent unwanted repeated effects or memory leaks.
When you add an interceptor, it returns an ID. You can remove it later with axios.interceptors.request.eject(id) or axios.interceptors.response.eject(id). This is useful in apps with dynamic behavior or tests.
Result
You avoid bugs caused by interceptors running multiple times or after they are no longer needed.
Knowing how to remove interceptors prevents subtle bugs and resource waste in complex apps.
6
AdvancedChaining multiple interceptors
🤔Before reading on: do you think multiple interceptors run in the order added or in reverse? Commit to your answer.
Concept: You can add many interceptors that run one after another, allowing layered processing.
Interceptors run in the order they were added for requests, and in reverse order for responses. This lets you separate concerns, like logging, authentication, and error handling, each in its own interceptor.
Result
Your app can handle complex request/response flows cleanly and modularly.
Understanding interceptor order helps you design predictable and maintainable request pipelines.
7
ExpertInterceptor pitfalls and async traps
🤔Before reading on: do you think async code inside interceptors pauses the request or runs after? Commit to your answer.
Concept: Interceptors can use async code, but misuse can cause delays or unhandled errors.
If you use async functions in interceptors, Axios waits for them to finish before continuing. Mistakes like not returning promises or throwing inside interceptors can break requests silently. Proper error handling and returning promises is critical.
Result
Your app avoids hanging requests or hidden bugs caused by interceptor misuse.
Knowing how async works inside interceptors prevents hard-to-debug issues in production apps.
Under the Hood
Axios interceptors work by wrapping the request and response processes with functions that run before sending or after receiving data. Internally, Axios maintains arrays of interceptor functions. When a request is made, Axios runs each request interceptor in sequence, modifying the config object. After the server responds, Axios runs response interceptors in reverse order, allowing modification or error handling. This chaining uses JavaScript promises to handle asynchronous flow smoothly.
Why designed this way?
Interceptors were designed to separate concerns and avoid repeating code for common tasks like authentication or logging. Using promise chains allows asynchronous operations inside interceptors without blocking the main thread. The design balances flexibility and simplicity, letting developers add or remove interceptors dynamically. Alternatives like modifying each request manually were error-prone and hard to maintain, so interceptors provide a clean, centralized solution.
┌─────────────────────────────┐
│       Axios Request          │
│  (config object created)     │
└─────────────┬───────────────┘
              │
              ▼
┌─────────────────────────────┐
│  Request Interceptors Array  │
│  (run in order added)        │
└─────────────┬───────────────┘
              │
              ▼
┌─────────────────────────────┐
│       HTTP Request Sent      │
│       (to server)            │
└─────────────┬───────────────┘
              │
              ▼
┌─────────────────────────────┐
│      HTTP Response Received  │
│       (from server)          │
└─────────────┬───────────────┘
              │
              ▼
┌─────────────────────────────┐
│ Response Interceptors Array  │
│ (run in reverse order added) │
└─────────────┬───────────────┘
              │
              ▼
┌─────────────────────────────┐
│    Promise resolves with     │
│    final response or error   │
└─────────────────────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Do request interceptors run after the request is sent? Commit to yes or no.
Common Belief:Request interceptors run after the request is sent to the server.
Tap to reveal reality
Reality:Request interceptors run before the request is sent, allowing modification of the request config.
Why it matters:Believing this causes confusion about when to modify headers or data, leading to bugs where changes don't apply.
Quick: Do response interceptors catch errors only after your .catch() handlers? Commit to yes or no.
Common Belief:Response interceptors cannot catch errors before your code’s .catch() handlers.
Tap to reveal reality
Reality:Response interceptors run before your .catch() handlers, so they can handle or transform errors globally.
Why it matters:Misunderstanding this leads to duplicated error handling and inconsistent app behavior.
Quick: Can you add async code inside interceptors without returning a promise? Commit to yes or no.
Common Belief:You can add async code inside interceptors without returning promises, and it will work fine.
Tap to reveal reality
Reality:If you don’t return a promise or the async function’s result, Axios won’t wait, causing unexpected behavior or silent failures.
Why it matters:This causes requests to proceed before async tasks finish, leading to bugs like missing tokens or unhandled errors.
Quick: Do multiple interceptors run in the order they were added for both requests and responses? Commit to yes or no.
Common Belief:Multiple interceptors run in the order they were added for both requests and responses.
Tap to reveal reality
Reality:Request interceptors run in the order added, but response interceptors run in reverse order.
Why it matters:Ignoring this causes confusion about the flow of data and can break layered logic like logging or error handling.
Expert Zone
1
Interceptors can be used to implement token refresh logic by catching 401 errors and retrying requests transparently.
2
Ejecting interceptors is crucial in single-page apps to avoid stacking interceptors on route changes or component mounts.
3
Interceptors can modify config or response objects deeply, but careless mutations can cause side effects that are hard to debug.
When NOT to use
Avoid using interceptors for request-specific logic that only applies once or rarely; instead, modify those requests directly. For complex state management or retry logic, consider dedicated libraries or Vue plugins that handle authentication flows more robustly.
Production Patterns
In production Vue apps, interceptors commonly add authentication tokens, log request/response data for monitoring, handle global error messages, and refresh expired tokens automatically. They are often combined with Vuex or Pinia for state management and used with centralized API service modules.
Connections
Middleware in Express.js
Similar pattern of intercepting and modifying requests and responses in a chain.
Understanding Axios interceptors helps grasp how middleware works in backend frameworks, showing a shared design for handling requests step-by-step.
Aspect-Oriented Programming (AOP)
Interceptors implement cross-cutting concerns like logging or security, which is the core idea of AOP.
Knowing interceptors reveals how programming can separate concerns cleanly, improving modularity and maintainability.
Airport security checkpoints
Both involve sequential checks and modifications before allowing passage.
Recognizing this connection helps understand the importance of order and thoroughness in processing flows.
Common Pitfalls
#1Adding an interceptor inside a component without removing it causes multiple interceptors stacking.
Wrong approach:axios.interceptors.request.use(config => { config.headers['Auth'] = 'token'; return config; }); // called on every component mount
Correct approach:const interceptorId = axios.interceptors.request.use(config => { config.headers['Auth'] = 'token'; return config; }); // later when component unmounts axios.interceptors.request.eject(interceptorId);
Root cause:Misunderstanding that interceptors persist globally and must be removed to avoid duplicates.
#2Not returning the config or response object inside interceptors breaks the request chain.
Wrong approach:axios.interceptors.request.use(config => { config.headers['Auth'] = 'token'; }); // missing return
Correct approach:axios.interceptors.request.use(config => { config.headers['Auth'] = 'token'; return config; });
Root cause:Forgetting that interceptors must return the modified object to continue the chain.
#3Throwing errors inside interceptors without catching causes unhandled promise rejections.
Wrong approach:axios.interceptors.response.use(response => response, error => { throw error; });
Correct approach:axios.interceptors.response.use(response => response, error => { return Promise.reject(error); });
Root cause:Confusing throwing with rejecting promises in async flows.
Key Takeaways
Axios interceptors let you automatically modify or handle every request and response in one place.
Request interceptors run before sending data, and response interceptors run after receiving data, each in specific order.
Properly returning values and handling async code inside interceptors is critical to avoid bugs.
Removing interceptors when no longer needed prevents bugs and memory leaks in dynamic apps.
Interceptors enable clean, centralized management of common tasks like authentication and error handling.