skip to Main Content

Currently, I’m looking for the best way to block or redirect users from accessing the login page if they are already logged in.

I’m working on a project using React with TypeScript.

What would be the best approach to implement this? Should I use Context API for managing authentication state, or would Redux be a better choice? Are there any other strategies or best practices I should consider for blocking the login page for authenticated users?

I made a custom hook that redirects me even if I’m logged in, it displays the page and then takes me back, is there any way to make it not render the page?

2

Answers


  1. If you have a large application, I recommend saving the authentication state in Redux. You can store user information or tokens in browser cookies to persist them across browser refreshes.

    You can then create a custom hook to manage redirection logic for both pages that require authentication and those that do not. Here’s a quick mockup for the custom hook:

    export const useRedirectIfAuthenticated = ({ shouldBeAuthenticated }) => {
      const isAuthenticated = useSelector((state) => state.auth.isAuthenticated); // This line gets the data from redux store so you can change it to useContext if you decide not to use redux or any other solution just to get the authentication state 
      const history = useHistory();
    
      useEffect(() => {
        if (isAuthenticated && !shouldBeAuthenticated) {
          history.replace('/'); // Replace to avoid back navigation to the login page
        } else if (shouldBeAuthenticated && !isAuthenticated) {
          history.replace('/login');
        }
      }, [isAuthenticated, history]);
    
      return isAuthenticated;
    };
    
    Login or Signup to reply.
  2. You could consider making a HOC( Higher Order Component ) like PrivateRoute.jsx

    // PrivateRoute.js
    import { useContext } from 'react';
    import { Redirect, Route } from 'react-router-dom';
    import { AuthContext } from './AuthContext';
    
    const PrivateRoute = ({ component: Component, ...rest }) => {
      const { isAuthenticated } = useContext(AuthContext);
    
      return (
        <Route
          {...rest}
          render={(props) =>
            isAuthenticated ? (
              <Component {...props} />
            ) : (
              <Redirect to={{ pathname: '/login', state: { from: props.location } }} />
            )
          }
        />
      );
    };
    
    export default PrivateRoute;

    and wrap your components around these where you want this functionality. The code will look something like this with context api.

    // AuthContext.js
    import { createContext, useState } from 'react';
    
    const AuthContext = createContext();
    
    const AuthProvider = ({ children }) => {
      const [isAuthenticated, setIsAuthenticated] = useState(false);
    
      const login = () => {
        setIsAuthenticated(true);
      };
    
      const logout = () => {
        setIsAuthenticated(false);
      };
    
      return (
        <AuthContext.Provider value={{ isAuthenticated, login, logout }}>
          {children}
        </AuthContext.Provider>
      );
    };
    
    export { AuthProvider, AuthContext };
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search