How to Create Protected Routes with React Router?

Routes that only allow authorized users access are known as protected routes. This indicates that visitors must first fulfill certain requirements in order to access that particular route.

The dashboard page, for instance, might only be accessible to people who are registered according to your application.

React Router’s Protected Routes, also known as Private Routes, demand that a user has permission to access the route.

A user cannot view a page if they are not permitted to do so. The most prevalent illustration is authentication in a React application, where a user can only access the protected pages if they are permitted.

However, authorization goes further than authentication. A user may, for instance, have responsibilities and permissions that grant access to particular portions of the programmer.

Schedule an interview with React developers

We can restrict which routes users can access based on whether they are logged in using protected routes.

You might, for instance, have login, price, and landing pages that are public and that you want everyone to be able to access. Only logged-in users should be allowed to access protected routes, such as a dashboard or settings page.

React Router was designed with composability in mind, so even while it doesn’t come with any functionality for this out of the box, adding it is pretty simple.

If we take a look at the output of the routing programme we created in the last session, we can see that it has three different parts: login, home, and editprofile.

We direct users to the home component after entering the correct credentials. But there’s an issue with our application.

Users without the LogIn Credentials can still access the home or modify profile components.

Protected Router Example

import { Routes, Route, BrowserRouter } from "react-router-dom";
import { useState } from "react";

function App() {
  const [isLoggedIn, setisLoggedIn] = useState(null);
  const logIn = () => {
    setisLoggedIn(true);
  };
  const logOut = () => {
    setisLoggedIn(false);
  };
  return (
    <BrowserRouter>
      <Navbar />
      {isLoggedIn ? (
        <button onClick={logOut}>Logout</button>
      ) : (
        <button onClick={logIn}>Login</button>
      )}
      <Routes>
      </Routes>
    </BrowserRouter>
  );
}
export default App;

You are keeping tabs on the user’s login status while using state. The buttons for logging in and logging out are both there.
Whether or not a user is logged in determines how these buttons are displayed in turn.

The login button is visible if the user is currently logged out. When clicked, it will launch the login process, update the isLoggedIn state to true, and switch the button’s display from login to logout.

Unique component

By developing a unique component that will manage incoming requests, we will achieve protection. In React component libraries, we have the standard Route component.
This will be used for the login page, our only public route. Additionally, we would like a special component that can handle protected routes. Give it the name ProtectedRoute.

The component will have a very straightforward function. Render the passed component if the user has been verified and granted access. If it is not done, redirect them to the login page.

Example

<BrowserRouter>
         <Switch>
            <Route path="/login" component={Login} />
	      <ProtectedRoute exact={true} path="/" component={Dashboard} />
              <ProtectedRoute path="/settings" component={Settings} />
              <ProtectedRoute component={Dashboard} />
          </Switch>
</BrowserRouter>

Also Read: What is the component lifecycle in React?

React Component

The Home component can then be wrapped in this new protective route component. This guarding method no longer needs to be known to the Home component itself:

Example

<Routes>
        <Route index element={<Landing />} />
        <Route path="landing" element={<Landing />} />
        <Route
          path="home"
          element={
            <ProtectedRoute user={user}>
              <Home />
            </ProtectedRoute>
          }
        />
        ...
</Routes>

Example

<BrowserRouter>
  <Switch>
    {authLogin ? (
      <>
        <Route path="/dashboard" component={Dashboard} exact />
        <Route exact path="/About" component={About} />
      </>
    ) : (
      <Route path="/" component={Login} exact />
    )}

    <Route component={PageNotFound} />
  </Switch>
</BrowserRouter>

Conclusion

Using high-order components, you must create protected routes that are very useful in the development phase. This tutorial has helped you to understand private routes with examples in React routers and how to use them as guards for routes that need authorization dependent on the authentication status of a user or roles and permissions. If you want more ideas about React development, you can go through our blogs!

If you want to develop your next application with React framework, you can hire dedicated ReactJS developer ready to assist you in every manner.

Frequently Asked Questions?

1. Is it possible to disable Route Guard?

CanDeactivate is a TypeScript interface that requires it to be integrated by the component to make the route guard. Hence, the router uses this guard to decide if it can deactivate a route. It can combine it in any Angular component by using a canDeactvate method of the interface.

2. Is it better to get route package protection?

There is no need for package protection, but it is a good idea as it benefits both consumers and merchants. However, for merchants, package protection is a crucial tool to improve the post-purchase experience and protects the customer.

3. How many types of route guards are there?

There are four types of route guards which are listed below
1. CanActivate: Controls if a route is activated
2. CanActiveChild: It controls the rote of the child if it is activated
3. CanLoad: If the route is loaded, then it is controlled
4. CanDeactivate: Leaves the route


Talk To Our Experts

Request a Quote