Course contentsShow
← Web Development
Lesson 1659 of 2,98230. Web Authorization PatternsFree lesson

Detecting 401 Responses

Learn to intercept 401 responses in fetch requests and global error handlers to trigger authentication flows.

Detecting 401 Responses

You'll learn how to catch 401 Unauthorized responses in your frontend code so you can automatically redirect users to login or refresh their tokens.

When your API returns a 401 Unauthorized status (indicating expired or missing authentication), your frontend needs to detect it and respond appropriately—typically by refreshing tokens or redirecting to a login page. Rather than handling this in every single fetch call, you want a centralized detection system.

Core Detection Strategies

In Individual Fetch Requests: You can check the response status after every API call:

const response = await fetch('/api/profile', {
  headers: { Authorization: `Bearer ${token}` }
});

if (response.status === 401) {
  // Token expired or invalid
  redirectToLogin();
}

In Global Fetch Wrappers: Create a wrapper function that all API calls use:

async function apiFetch(url, options) {
  const response = await fetch(url, options);
  
  if (response.status === 401) {
    // Centralized 401 handling
    await refreshToken(); // or redirectToLogin()
  }
  
  return response;
}

In Axios Interceptors: For apps using Axios, response interceptors provide elegant global handling:

axios.interceptors.response.use(
  response => response,
  error => {
    if (error.response?.status === 401) {
      // Handle 401 globally
      triggerAuthenticationFlow();
    }
    return Promise.reject(error);
  }
);

Think of 401 detection like a smoke detector in your house—you install it in a central location to catch problems anywhere, rather than checking for smoke in every single room manually.

Key Takeaway: Detecting 401 responses globally through fetch wrappers or interceptors allows you to centralize authentication logic and automatically trigger token refresh or login flows without repeating code throughout your application.