Handling HTTP 403 Errors Globally in Axios
Handling HTTP 403 Forbidden errors globally in Axios ensures that permission-denied responses are intercepted consistently across an entire application. By utilizing Axios response interceptors, developers can catch 403 status codes in a centralized location to trigger automatic redirects, show notifications, or log out unauthorized users without writing repetitive error-handling logic for every individual API request.
Using Axios Response Interceptors
The standard method for catching errors globally in Axios is attaching a response interceptor to your Axios instance. Interceptors act as middleware, allowing you to inspect every incoming HTTP response and handle errors before they reach calling functions.
Here is a complete implementation:
import axios from 'axios';
// Create a custom Axios instance
const apiClient = axios.create({
baseURL: 'https://api.example.com',
timeout: 10000,
});
// Attach a global response interceptor
apiClient.interceptors.response.use(
(response) => {
// Return successful responses directly
return response;
},
(error) => {
if (error.response && error.response.status === 403) {
// Execute global 403 logic here
handleForbiddenError(error);
}
// Always reject the promise so local catch blocks can still execute if needed
return Promise.reject(error);
}
);
function handleForbiddenError(error) {
console.error('Access forbidden:', error.response.data);
// Common action 1: Show a global alert or toast notification
// showNotification('You do not have permission to perform this action.');
// Common action 2: Redirect to a dedicated "Access Denied" page
// window.location.href = '/access-denied';
}
export default apiClient;Recommended Actions for HTTP 403 Errors
Unlike an HTTP 401 Unauthorized status, which signifies missing or invalid authentication credentials, an HTTP 403 Forbidden status indicates that the server understands who the user is, but refuses to authorize the specific action or resource access.
When managing 403 errors globally, implement the following best practices:
- Redirect to an Access Denied Route: Prevent users from seeing broken UI components by navigating them to a dedicated page that informs them of their insufficient permissions.
- Display Global Toast Notifications: For non-page-blocking requests (such as clicking an action button), display a notification explaining that the user lacks the necessary roles or privileges.
- Propagate the Error: Always return
Promise.reject(error)at the end of the interceptor error callback. This ensures downstream asynchronous calls receive the error state, enabling local loading spinners and button states to reset properly. - Use Scoped Axios Instances: Attach interceptors to
an exported
axios.create()instance rather than the default globalaxiosobject. This avoids unexpected side effects if third-party libraries also use the base Axios package.