DEV Community

Dennis kinuthia
Dennis kinuthia

Posted on

 

Auth Guarding in react

After we authenticate we might want to guard certain routes and redirect to the login page if not authenticated

the most common way to do it is

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

export const ProtectedRoute = ({ user,children }) => {
  if (!user) {
   return <Navigate to="/login" replace />;
    }
  return children;
  };

Enter fullscreen mode Exit fullscreen mode

and wrap the childern with the component

          <Routes>
            <Route
              path="/"
              element={
                <ProtectedRoute user={user}>
                  <Home user={user} />
                </ProtectedRoute>
              }
            />
            </Routes>
Enter fullscreen mode Exit fullscreen mode

but with the react-router v6+ routes can be nested inside layouts which unlocks new patterns

import { useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { PBUser } from '../../utils/types/types';

export const useAuthGuard = (user:PBUser,test_mode:boolean) => {
    const navigate = useNavigate();

    useEffect(() => {
        if (!user?.email && !test_mode) {
            navigate("/auth");
        }
    }, [user?.email]);
};
Enter fullscreen mode Exit fullscreen mode

and use the hook in the main layout or layout for whichever route you want to guard

import { Outlet} from 'react-router-dom';
import { Toolbar } from '../../components/toolbar/Toolbar';
import { PBUser } from '../../utils/types/types';
import { useAuthGuard } from './../../shared/hooks/useAuthGuard';

interface RootLayoutProps {
  user: PBUser;
  test_mode: boolean;
}

export const RootLayout = ({user,test_mode}: RootLayoutProps) => {

  useAuthGuard(user,test_mode)

  return (
    <div className="w-full h-full dark:bg-slate-900">
      <div
        className="h-14 w-full  bg-slate-700 dark:bg-slate-800
          bg-opacity-30 dark:bg-opacity-90 max-h-[50px] p-1
         sticky top-0 z-40"
      >
        <Toolbar user={user} />
      </div>
      <main className=" w-full h-[90%] fixed top-12 overflow-y-scroll">
        <Outlet />
      </main>
    </div>
  );
};

Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Top Posts from the React Ecosystem

1. Changes In The Official React Documentation

The former React Docs Beta has been officially released as the updated React documentation at react.dev after years of hard work and refinement. Check out the brand new React Docs: What’s New in the Updated React Docs

2. CRA's Time is Over

React developer team has removed create-react-app (CRA) from official documentation rendering it no longer the default setup method for new projects. The bulky setup, slow, and outdated nature of CRA led to its removal: create-react-app is officially dead

3. How to Fetch Dev.to Articles for Your Portfolio

Integrate the articles of your Dev.to profile into your personal portfolio with either React, Vue, or Next.js by following these simple steps. It outlines how to include frontend to pull the information and correctly utilizes the Dev.to API: How to Fetch Your Dev.to Articles for Your Portfolio with React