Back to blogs
Blog
Writing in public
Longer posts — published here first, then cross-posted to Dev.to with a canonical URL back to this site.
Blog
Longer posts — published here first, then cross-posted to Dev.to with a canonical URL back to this site.
Back to blogs
Back to blogs
Postauthentication, react, reactrouter, javascript
After we authenticate we might want to guard certain routes and redirect to the login page if not...
Date published

Why You Might Still Pick Next.js Over TanStack Start From a TanStack Start...

A complete theme management system for React applications with SSR support! ✨ 🌟...

slides used in the presentation building the generic component In this example we'll use...
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
1import { Navigate } from 'react-router-dom';23export const ProtectedRoute = ({ user,children }) => {4 if (!user) {5 return <Navigate to="/login" replace />;6 }7 return children;8 };9
and wrap the childern with the component
1 <Routes>2 <Route3 path="/"4 element={5 <ProtectedRoute user={user}>6 <Home user={user} />7 </ProtectedRoute>8 }9 />10 </Routes>
but with the react-router v6+ routes can be nested inside layouts which unlocks new patterns
1import { useEffect } from 'react';2import { useNavigate } from 'react-router-dom';3import { PBUser } from '../../utils/types/types';45export const useAuthGuard = (user:PBUser,test_mode:boolean) => {6 const navigate = useNavigate();78 useEffect(() => {9 if (!user?.email && !test_mode) {10 navigate("/auth");11 }12 }, [user?.email]);13};
and use the hook in the main layout or layout for whichever route you want to guard
1import { Outlet} from 'react-router-dom';2import { Toolbar } from '../../components/toolbar/Toolbar';3import { PBUser } from '../../utils/types/types';4import { useAuthGuard } from './../../shared/hooks/useAuthGuard';56interface RootLayoutProps {7 user: PBUser;8 test_mode: boolean;9}1011export const RootLayout = ({user,test_mode}: RootLayoutProps) => {1213 useAuthGuard(user,test_mode)1415 return (16 <div className="w-full h-full dark:bg-slate-900">17 <div18 className="h-14 w-full bg-slate-700 dark:bg-slate-80019 bg-opacity-30 dark:bg-opacity-90 max-h-[50px] p-120 sticky top-0 z-40"21 >22 <Toolbar user={user} />23 </div>24 <main className=" w-full h-[90%] fixed top-12 overflow-y-scroll">25 <Outlet />26 </main>27 </div>28 );29};30