Handle Protected Routes in React app with the react-router-dom v6

Mohammad Esmaeilzadeh
2 min readMay 21, 2022

You will definitely need that to protect some pages in your web application, for example: I can mention to admin pages (Dashboard etc.) which they are not accessible before Login.

React Protected Routes with react-router-dom v6

react-router-dom v6 has a great component which it makes you able to wrap all protected routes then, you can check something for the security (Login or Access Token etc.) before render those wrapped components (Protected Pages) in DOM 👌

▶ What is <Outlet /> Component?

You can use the Outlet component to render all child Routes into parent:

function Dashboard() {
return (
<div>
<h1>Dashboard</h1>
<Outlet />
</div>
);
}

function App() {
return (
<Routes>
<Route path="/" element={<Dashboard />}>
<Route
path="messages"
element={<DashboardMessages />}
/>
<Route path="tasks" element={<DashboardTasks />} />
</Route>
</Routes>
);
}

Great 👌 now that we are familiar with the <Outlet /> component, we can create a re-usable component to wrap all protected routes:

import { Outlet, Navigate } from 'react-router-dom';const ProtectedRoute = () => {
if (/* Check Login or Access Token here */) {
return <Outlet />;
} else {
return <Navigate to="/login" />;
}
}
export default ProtectedRoute;

In fact, the above component (ProtectedRoute) is a simple function which checks that, user is logged in and has access token or not?!

If user has access it renders the Outlet component which represents the wrapped component or protected page otherwise, it will redirect client to login page (http://127.0.0.1/login) by Navigate component.

Now we should add our Routes into app component:

<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/login" element={<Login />} />
<Route element={<ProtectedRoute />}>
<Route path="/dashboard" element={<Dashboard />} />
</Route>
<Route path="*" element={<NotFound />} />
</Routes>
</BrowserRouter>

According to the above codes, we wrapped Dashboard by a Route which uses <ProtectedRoute /> as it’s element…

So for this case, if user open: (http://127.0.0.1/dashboard) our component first checks for login and access token and Outlet mentions to dashboard page as a protected route 👍

Good Luck.

--

--