Protected Routes in React

mohit thakur
1 min readSep 18, 2021

A simple and elegant solution to protect your routes based on authorization

Use Case

If your application has different roles and have different sections that need to be protected and accessed only when logged in with that role.

Implementation

  • Lets create a custom route component which will check for routes
import { Roles } from "models/roles";
import { Redirect, Route, useLocation } from "react-router-dom";
export const AuthorRoute = (props) => {const location = useLocation();return sessionStorage.getItem("role") == Roles.AUTHOR (<Route {...props} />) : (<Redirect to={{ pathname: "/", state: { from: location },}}/>);};

Lets look at the code above , few things to notice here

  • uselocation is a react hook to get the current location of the route
  • Session storage to get the saved role of the user , usually saved when user logs in.
  • redirect — if the role is not as expected redirect back to ‘/’ that is home page

How to use our custom route , simply go to your app routes and convert

<Route exact path="/profile" component={Profile} />

Replace with our custom Route

<AuthorRoute exact path="/profile" component={Profile} />

That’s it , now your route is available only for Role = Author

--

--