React – Protected Routes

Table of Contents
Overview
Below is a quick how to protect certain routes from users that are not authenticated. An exported function labeled “ProtectedRoute” will check if the user is authenticated otherwise it will redirect to another component that handles authentication. This is just a solution I came across on stackoverflow and is similar to Angular’s AuthGuard. This is not a complete application, just short example of how to prevent users from accessing certain routes.
Prerequisites
Install the react router.
npm install react-router-dom
Authentication
To keep this simple, set a “true” or “false” value in a session variable to allow the protected routes to be available.
Protected Routes Function Component
This solution was taken from a post on Stackoverflow by Drew Reese. This is by far the best solution I have run across and thought I would share. This function will go to the current route being requested if there is an “admin” variable with the value of true in the session storage. If the “admin” has no value or is false then application is redirected to a route labeled authorize in this example.
import { Route, Redirect, useLocation } from 'react-router-dom';
function ProtectedRoute(props) {
const location = useLocation();
const isAuthenticated = Boolean(sessionStorage.getItem("admin"));
return isAuthenticated ? (
<Route {...props} />
) : (
<Redirect
to={{
pathname: "/authorize",
state: { from: location }
}}
/>
);
}
export default ProtectedRoute;
The Router
The router uses the ProtectedRoute component to determine if the route is accessible.
import { BrowserRouter as Router, Switch, Route, useLocation, Redirect } from 'react-router-dom';
import ProtectedRoute from './ProtectedRoute';
import AdminAllProducts from '../Components/AdminAllProducts';
import AdminEditProduct from '../Components/AdminEditProduct';
export default function MainRouter(props) {
return (
<>
<Switch>
<Route exact path="/" component={Home} />
<Route exact path="/login" component={Login} />
<ProtectedRoute path="/admin-products" component={AdminAllProducts} />
<ProtectedRoute path="/admin-edit-product/:id"
component {AdminEditProduct} />
</Switch>
</>
);
}
You must be logged in to post a comment.