Using Axios Interceptors
When building React applications that interact with APIs, you often need to modify requests or handle responses in a consistent way across your app. Axios provides interceptors for this purpose, allowing you to intercept and transform requests or responses globally before they are handled by your components. One common scenario is attaching authentication tokens to every outgoing request so that your API knows who the user is. To set this up, you can use the axios.interceptors.request.use method to add a function that modifies each request before it is sent.
Suppose you store a user's authentication token in local storage after they log in. You want to ensure that every API request includes this token in its headers. Using an Axios request interceptor, you can automatically attach the token to all requests without repeating code in every component. Here is how you might set up such an interceptor in your React app:
import api from "./api";
api.interceptors.request.use(
(config) => {
const token = localStorage.getItem("authToken");
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
(error) => Promise.reject(error)
);
With this code, before any request is sent, Axios checks if an authToken exists in local storage. If it does, the token is added to the Authorization header. This ensures all outgoing requests include the necessary credentials, reducing the risk of missing authentication and improving security and maintainability.
Interceptors are not limited to handling authentication. Another frequent use case is global error logging. By adding a response interceptor using axios.interceptors.response.use, you can catch and process errors in one place, such as logging them or displaying a notification to the user. This helps you avoid duplicating error handling logic in every component that makes API calls. Interceptors are also useful for handling specific API response codes, such as redirecting users to a login page if a 401 Unauthorized error is received, or standardizing the shape of data returned from the API before it reaches your React components. By centralizing these concerns, Axios interceptors help you keep your codebase organized and reduce repetition.
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat
Can you show me how to set up a response interceptor for error handling?
What are some best practices for using Axios interceptors in React?
How do I remove or disable an interceptor if I no longer need it?
Awesome!
Completion rate improved to 10
Using Axios Interceptors
Swipe to show menu
When building React applications that interact with APIs, you often need to modify requests or handle responses in a consistent way across your app. Axios provides interceptors for this purpose, allowing you to intercept and transform requests or responses globally before they are handled by your components. One common scenario is attaching authentication tokens to every outgoing request so that your API knows who the user is. To set this up, you can use the axios.interceptors.request.use method to add a function that modifies each request before it is sent.
Suppose you store a user's authentication token in local storage after they log in. You want to ensure that every API request includes this token in its headers. Using an Axios request interceptor, you can automatically attach the token to all requests without repeating code in every component. Here is how you might set up such an interceptor in your React app:
import api from "./api";
api.interceptors.request.use(
(config) => {
const token = localStorage.getItem("authToken");
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
(error) => Promise.reject(error)
);
With this code, before any request is sent, Axios checks if an authToken exists in local storage. If it does, the token is added to the Authorization header. This ensures all outgoing requests include the necessary credentials, reducing the risk of missing authentication and improving security and maintainability.
Interceptors are not limited to handling authentication. Another frequent use case is global error logging. By adding a response interceptor using axios.interceptors.response.use, you can catch and process errors in one place, such as logging them or displaying a notification to the user. This helps you avoid duplicating error handling logic in every component that makes API calls. Interceptors are also useful for handling specific API response codes, such as redirecting users to a login page if a 401 Unauthorized error is received, or standardizing the shape of data returned from the API before it reaches your React components. By centralizing these concerns, Axios interceptors help you keep your codebase organized and reduce repetition.
Thanks for your feedback!