Route Guards in ReactJS

 Route guards are a way to control access to certain routes in your application. They are commonly used to protect routes that should only be accessible to authenticated users. In this blog post, we will explore how to implement route guards in ReactJS.



What are Route Guards?

In the context of a web application, a route guard is a piece of logic that runs before a route is loaded. It determines whether or not a user can access a certain route based on their authentication status or other conditions1.

Implementing Route Guards in ReactJS

ReactJS does not provide built-in support for route guards, but we can easily implement them using the features provided by the react-router-dom library1. Here’s a basic example of how to implement route guards in ReactJS:

import React from 'react';

import { BrowserRouter } from 'react-router-dom';

import { GuardProvider, GuardedRoute } from 'react-router-guards';

import { About, Home, Loading, Login, NotFound } from 'pages';

import { getIsLoggedIn } from 'utils';


const requireLogin = (to, from, next) => {

  if (to.meta.auth) {

    if (getIsLoggedIn()) {

      next();

    }

    next.redirect('/login');

  } else {

    next();

  }

};


function App() {

  return (

    <BrowserRouter>

      <GuardProvider guards={[requireLogin]} error={NotFound}>

        <GuardedRoute path="/" exact component={Home} />

        <GuardedRoute path="/about" exact component={About} meta={{ auth: true }} />

        <GuardedRoute path="/login" exact component={Login} />

      </GuardProvider>

    </BrowserRouter>

  );

}


export default App;

In the above example, the requireLogin function is our route guard. It checks if the route requires authentication by looking at the meta.auth property of the route. If the route requires authentication and the user is not logged in, it redirects the user to the login page.

Using React-Router v6 for Route Guards

If you’re using version 6 of react-router-dom, you can use the useRoutes hook to create protected routes. Here’s an example:

import { Navigate, Outlet } from 'react-router-dom';


const routes = (isLoggedIn) => [

  {

    path: '/app',

    element: isLoggedIn ? <DashboardLayout /> : <Navigate to="/login" />,

    children: [

      { path: '/dashboard', element: <Dashboard /> },

      { path: '/account', element: <Account /> },

      { path: '/', element: <Navigate to="/app/dashboard" /> },

      {

        path: 'member',

        element: <Outlet />,

        children: [

          { path: '/', element: <MemberGrid /> },

          { path: '/add', element: <AddMember /> },

        ],

      },

    ],

  },

  {

    path: '/',

    element: !isLoggedIn ? <MainLayout /> : <Navigate to="/app/dashboard" />,

    children: [

      { path: 'login', element: <Login /> },

      { path: '/', element: <Navigate to="/login" /> },

    ],

  },

];


export default routes;


In the above example, the routes function returns an array of route objects. Each route object has a path, an element, and optionally a children array of nested routes.

That’s it! We’ve covered the basics of route guards in ReactJS. Whether you’re redirecting to an external URL or navigating within your React app, these methods should cover most of your needs. Happy coding!

0 Comments