reactjsnode.jsexpressmern

Redirect User to Booking Page After Login in React Router v6


Description: I’m building a room booking system in React with React Router v6. When a user clicks on a booking link (/book/:roomId), if they are not authenticated, they should be redirected to the sign-in page. After successful login, they should be taken back to the booking page instead of the home/dashboard.

Right now, my issue is:

The user is redirected to the sign-in page correctly when clicking a booking link. After signing in, they are not redirected back to the booking page but instead land on the profile or dashboard. How can I correctly store the intended booking page before login and navigate the user back to it after authentication?

What I Tried In my Rooms.tsx file, I handle direct booking attempts like this:

import React, { useEffect } from 

'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext';

const Rooms: React.FC = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const { isAuthenticated } = useAuth();

  useEffect(() => {
    const match = location.pathname.match(/^\/book\/([a-f0-9]{24})$/i);
    if (match) {
      const roomId = match[1];

      if (!isAuthenticated) {
        sessionStorage.setItem('redirectAfterLogin', `/book/${roomId}`);
        navigate('/signin', { state: { from: `/book/${roomId}` }, replace: true });
      } else {
        navigate(`/book/${roomId}`);
      }
    }
  }, [location, navigate, isAuthenticated]);

  return <div>Room List Here</div>;
};

export default Rooms;

In my SignIn.tsx file, I try to check for a stored redirect path after login:

    import React, { useEffect } from 

    'react';
    import { useNavigate } from 'react-router-dom';
    import { useAuth } from '../contexts/AuthContext';
    
    const SignIn = () => {
      const navigate = useNavigate();
      const { isAuthenticated } = useAuth();
    
      useEffect(() => {
        if (isAuthenticated) {
          const redirectPath = sessionStorage.getItem('redirectAfterLogin');
          if (redirectPath) {
            sessionStorage.removeItem('redirectAfterLogin');
            navigate(redirectPath, { replace: true });
          }
        }
      }, [isAuthenticated, navigate]);
    
      return <div>Sign In Form Here</div>;
    };
    
    export default SignIn;

Current Issue Even though redirectAfterLogin is stored in sessionStorage, after login, the user is still taken to the default page instead of the intended /book/:roomId page.

Question: How can I correctly store the intended URL and ensure the user is navigated back to /book/:roomId after logging in?


Solution

  • when isAuthenticated changes after login. The redirect logic inside useEffect in SignIn.tsx may be running before authentication is fully updated. Instead of running the redirection inside useEffect , move it inside your authentication function .