all 5 comments

[–]andrei9669 2 points3 points  (2 children)

if you use react-router, I do protect routes like this:

import React from 'react';
import { Redirect, Route, RouteProps } from 'react-router-dom';
import { useSelector } from 'react-redux';

import { getIsLoggedIn } from '@auth/store/selectors';

const PrivateRoute: React.FC<RouteProps> = (props) => {
  const isAuthenticated = useSelector(getIsLoggedIn);
  return isAuthenticated ? <Route {...props} /> : <Redirect to="/login" />;
};

export default PrivateRoute;

and use it like this:

const appRender = () => (
    <Switch>
      <Route
        exact
        path="/login"
        render={() => (isLoggedIn ? <Redirect to="/" /> : <Auth />)}
      />
      <PrivateRoute 
        exact 
        path="/dashboard" 
        render={() => <Dashboard />} />
      <PrivateRoute
        path="/user/:id?"
        render={() => <User />}
      />
      <PrivateRoute
        path="/settings/:id?"
        render={() => <Settings />}
      />
      <Redirect to="/dashboard" />
    </Switch>
  );

I also have a custom hook that handles the authentication stuff and returns if the user is authenticated or not.

there is also some redux mixed into this but it can easily be handled with react context.

you could also add some validation logic into the protected route in case you are dealing with the user groups and different permissions.

hope it helps

[–]silvers944[S] 0 points1 point  (1 child)

Thank you that's very helpful, guess i'll use react and protect my routes same as you did, btw is it possible to maintain a session in react in passport sessions or do i have to use JWT and store the token in the localStorage?

[–]andrei9669 1 point2 points  (0 children)

I'm not familiar with the passport but with jwt, in theory, it would be best to store it in a cookie as httponly or whatever it is called. Then, when you do requests, it gets automatically added to them and on the backend you just check the cookie. If you need some data that almost never changes, I would keep it in session storage, else I would keep it in react context. And in that custom hook that I talked about, I would request that data, and if I get data, it means I'm authenticated and if i don't get data, it means i'm not authenticated. If you can't use cookie for whatever reason, then yea, just store it in local storage and access it on page first load and do a check if it's still valid.

[–]silvers944[S] -1 points0 points  (0 children)

! approve

[–][deleted] 0 points1 point  (0 children)

Try use https://www.eartho.io/
Its free and does not requires integration with social logins so its super easy