Hi, folks. I’ve been trying to implement protected routes in React Router, and I’m right on the edge of having it figured out, but I’ve gotten stuck on the last step and I was hoping someone else might see the way forward.
I’ve built a higher order component to reroute the user if they’re not authenticated and render the desired route if they are, but I can’t for the life of me figure out how to get that information for use in my component.
const ProtectedRoute = ({ component: Component, ...rest }) => {
return (
<Route
{...rest}
render={props => {
if (!AUTHENTICATED) {
return <Redirect to="/login" />;
}
return <Component {...props} />;
}}
/>
);
};
The if (!AUTHENTICATED)
part is where I’m stuck.
I’m using Passport, and have all the authentication stuff worked out on my Express server, so all I have to do is make a fetch request to see if the user is authenticated, but I can’t make that request in the return statement of the ProtectedRoute component. I tried adding a function before the return statement to fetch the user’s authentication status, but couldn’t figure that out either. If I use async at any point, the whole thing seems to fall apart, and I can’t get the info from the server without using async. It’s been hours, and my brain is falling out, so any input would be very very helpful.
Thanks for your time!