A 401 Unauthorized error means:
- Token is missing
- Token is expired
- Token is invalid
- User is not logged in
To handle it correctly, you must catch 401 globally, refresh tokens if needed, and redirect the user to login if refresh fails.
✅ 1. Handle 401 Using Axios Interceptors (Recommended)
This is the best way because you don’t have to write try/catch everywhere.
🔹 Create an Axios instance
import axios from "axios";
const api = axios.create({
baseURL: "https://api.example.com",
withCredentials: true, // if using cookies
});
🔹 Add Response Interceptor
api.interceptors.response.use(
(response) => response,
async (error) => {
if (error.response?.status === 401) {
try {
// try to refresh token
await api.post("/auth/refresh");
// retry original request
return api(error.config);
} catch (refreshError) {
// refresh failed → redirect to login
window.location.href = "/login";
}
}
return Promise.reject(error);
}
);
✔ Handles token expiry
✔ Automatically retries failed request
✔ Redirects user if refresh token invalid
✅ 2. Handling 401 in Fetch API
Fetch has no interceptors, so you wrap it:
const fetchWithAuth = async (url, options = {}) => {
const response = await fetch(url, options);
if (response.status === 401) {
// try refresh
const refresh = await fetch("/auth/refresh", { method: "POST" });
if (refresh.ok) {
return fetch(url, options); // retry
} else {
window.location.href = "/login";
}
}
return response;
};
✅ 3. Redirect User on 401 using React Router
Inside protected routes:
import { Navigate } from "react-router-dom";
const ProtectedRoute = ({ isAuth, children }) => {
if (!isAuth) return <Navigate to="/login" replace />;
return children;
};
If isAuth becomes false because of 401 → redirect automatically.
✅ 4. Logout User Automatically on 401
Inside a global Redux/Context handler:
if (error.response?.status === 401) {
dispatch(logout());
}
🧠 Why Is This Important?
Proper 401 handling ensures:
- App never gets stuck
- Users aren’t left in inconsistent state
- Expired token is refreshed seamlessly
- User gets logged out safely when needed
🎯 Short Interview Answer
We handle 401 errors in React by using Axios interceptors to catch unauthorized responses globally.
When a 401 occurs, we try refreshing the token; if refresh succeeds, we retry the request, and if it fails, we redirect the user to the login page.
For routing, we also protect routes using React Router and redirect unauthenticated users.