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

Handling 401: Redirect to Login

Learn to redirect users to login when receiving 401, preserving the intended destination URL for post-login navigation.

Handling 401: Redirect to Login

What you'll learn: How to automatically redirect users to the login page when your application receives a 401 status code, while remembering where they wanted to go so you can send them back after successful authentication.

The Problem

When your API returns a 401 Unauthorized response (which you've learned to detect), you need to gracefully guide the user to log in again. But here's the catch: the user was trying to do something specific—view their profile, submit a form, or access a protected page. After they log in, they shouldn't have to hunt for that page again.

Preserving the Intended Destination

Think of it like a restaurant host: "I'm sorry, this is the VIP section. Let me take you to the front desk to verify your membership—and I'll remember you wanted table 7 by the window."

When redirecting to login, capture the current URL or route and store it temporarily (in sessionStorage, a URL parameter, or app state). After successful login, read that saved location and navigate the user back to their original destination.

// In your 401 response interceptor
if (response.status === 401) {
  // Save where they were trying to go
  const intendedPath = window.location.pathname;
  sessionStorage.setItem('redirectAfterLogin', intendedPath);
  
  // Redirect to login
  window.location.href = '/login';
}

Then, in your post-login logic:

const redirectPath = sessionStorage.getItem('redirectAfterLogin') || '/dashboard';
sessionStorage.removeItem('redirectAfterLogin');
window.location.href = redirectPath;

Key Takeaway: When handling 401 responses, always redirect users to login and preserve their intended destination URL, creating a seamless experience that returns them to their original task after authentication.