'React - How to implement isLogin() function?
I am working on implementing authentication in React. I have followed the guide https://medium.com/@thanhbinh.tran93/private-route-public-route-and-restricted-route-with-react-router-d50b27c15f5e to implement Private and Public routes. Everything works fine.
To summarise my routes look like this:
<PublicRoute restricted={true} component={Login} exact path="/login">
<PrivateRoute component={Dashboard} path="/dashboard" exact />
My private and public routes check if user is logged in through isLogin() function. I have implemented it in a following way:
export const isLogin = () => {
if(getToken('myToken') == true) {
return true;
}
return false;
getToken() is basically a function which retrieves token from local storage and returns true or false. Now my question is how do I verify if myToken is a valid token from API and then return true or false accordingly?
Solution 1:[1]
For that you have two option 1). if you have refresh token API than call it when route is change or may be page get refresh if the token is expire than remove token from local storage and redirect user to login page. 2). Another one is you have to set expire time of token in local storage if time expire than logout the user also if you call the any API than validate token in backend if the token will expire the API gives 401 means unauthorized than you can logout the user.
Solution 2:[2]
if you are using react-router new version (v6) than use ohterwise use ,... and in path if you have dynamic route list than use like otherwise call all the component inside here is
const isLogin = localStorage.getItem('login');
function RequireAuth({children}) {
return isLogin ? children : <Navigate to="/sign-in" replace/>;
}
<Routes>
<Route path={'*'} element={<RequireAuth><RouteList/></RequireAuth>}/>
</Routes>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Vishal Gajera |
Solution 2 |