2

The user is in home page and if he goes to any protected route(cart page, profile page) without authentication he will be Redirecting to login page and after login they must not return to home page, they must go to the current location they were trying to go to when they were redirected, but it returns to the homepage.

 <Routes>
        <Route path='/' element={<HomeScreen />} />
        <Route path='/signin' element={<SignInScreen />} />
        <Route path='/signup' element={<SignUpScreen />} />
        <Route path='/products/:id' element={<ProductScreen />} />
        <Route element={<PrivateRoute />}>
          <Route path='/cart' element={<CartScreen />} />
          <Route path='/wishlist' element={<WishlistScreen />} />
          <Route path='/profile' element={<ProfileScreen />} />
        </Route>
      </Routes>
const PrivateRoute = () => {
    if (!auth.authenticated) {
      return <Navigate to='/signin' replace={true} />;
    }
    return <Outlet />;
  };
 const Submit = async (e) => {
    e.preventDefault();
    let data = { email, password };

    if (!email || !password) {
      setMessage('Please Enter All Fields');
    } else {
      setLoading(true);
      return await axios
        .post('/signin', data)
        .then((res) => {
          if (res.data.message === 'Invalid Credentials') {
            setMessage('Invalid Credentials');
            setLoading(false);
          }
          if (res.data.message === 'Logged In') {
            setLoading(false);
            navigate('/', { replace: true });
          }
        })
        .catch((err) => {
          console.log(err);
          setLoading(false);
        });
    }
  };
Haree Prasad
  • 103
  • 1
  • 2
  • 8

1 Answers1

0

In the private route you should grab the current location to send in route state to the log in page, and upon successful authentication, redirect them back to the location they were originally attempting to access.

import { ...., useLocation } from 'react-router-dom';

const PrivateRoute = () => {
  const location = useLocation();
  
  ...

  if (!auth.authenticated) {
    return <Navigate to='/signin' replace state={{ from: location }} />;
  }
  return <Outlet />;
};

In the SignIn component, access the from value from the location object.

import { ...., useLocation } from 'react-router-dom';

...

const SignIn = () => {
  const { state: { from = "/" } = {} } = useLocation();

  ...

  const submit = (e) => {
    e.preventDefault();
    const data = { email, password };

    if (!email || !password) {
      setMessage('Please Enter All Fields');
    } else {
      setLoading(true);
      return axios
        .post('/signin', data)
        .then((res) => {
          if (res.data.message === 'Invalid Credentials') {
            setMessage('Invalid Credentials');
          }
          if (res.data.message === 'Logged In') {
            navigate(from, { replace: true }); // <-- redirect to from value
          }
        })
        .catch(console.log)
        .finally(() => {
          setLoading(false);
        });
    }
  };

  ...
Drew Reese
  • 165,259
  • 14
  • 153
  • 181