How to re-check for each URL route for authentication? Private Routing in React JS.
When I was building my application Grow Media, I was thinking about how private routing is done, while going to each component through their specified URL and having the authorized cookie in the browser it re-directs me to the Login page.
ehh, but whyyy? 🤔
It is because we are storing the authorized user ID in the Redux store and after a refresh or a direct link to other specified routes, it doesn't persist the authorized user ID.
So I created logic in App.tsx, because it renders at each URL request, as a parent component by React which then renders the component for specified routes.
1. Storing user ID in Redux.
const [callLazy,{data}]=useLazyQuery<verifyjwtFunc>(FROM_COOKIE);
useEffect(()=>{
callLazy();
if(data){
dispatchJwt(logIn(data?.verifyjwtFunc))
}
},[data,callLazy,dispatchJwt])
useEffect will call callLazy ' a function name ', this will send a request to the server with the cookie, which in response gives the user ID as confirmed authorization.
after it got the user ID in the data, it dispatches the data to the redux store.
Now, we can access the user ID through COOKIE from REDUX.
2. Private Route
Now check if the redux store variable has a user ID or not. If it does then navigate to the child component which we routed for, if it doesn't then navigate to the login route.
const PrivateRoute = ({children, path }: {children: any, path: string}) => {
const selector = useSelector(userLoginInfo);
return selector ? (
children
):(
<Navigate to={'/login'} replace />
)
}
- Now check for the user ID
- using the Navigate for routing programmatically
3. Private Route the components
Covering the main component as a child component in the Private routing component as :
return (
<Router>
<Routes>
<Route path = "/explore" element={<><PrivateRoute>< Explore /></PrivateRoute></>}/>
<Route path = "/home" element={<><PrivateRoute>< Home /></PrivateRoute></>}/>
</Routes>
</Router>
)
- Here the private route is returning the child component as < Explore /> and < Home />
- Now we can check through this method for checking through cookies to provide the user ID after authorization.
Now you have made a perfect private routing system for each route or targetting a specified URL in the browser. 🤩
How to send cookies to clients while login, in through GraphQL?
You can check the article here.