Skip to main content

Protected Routes

In a React application, a protected route is a route, which authenticated users can only access. Protected routes ensure that only authorized users can access certain application parts.

Steps to create protected routes in React using DhiWise

1. Go to Pages

Example banner

2. Select Protected routes from the left menu

Example banner

3. Select routes to protect & click Move to protected

Example banner

4. Define the local-storage key or use the existing & click Submit

Example banner

About the generated code of Protected routes using DhiWise

To create a protected route in React, you can use the <Route> component from the react-router-dom library and wrap it in a higher-order component (HOC) that checks if the user is authenticated before rendering the route.

Here's an example of how DhiWise generates a protected route in React:

import React from "react";
import { Navigate, useLocation } from "react-router-dom";

export const ProtectedRoute = ({ element: Element }) => {
const { pathname } = useLocation();
const token = localStorage.getItem("token");

if (!token && ["/dashboard"].includes(pathname)) {
return <Navigate to="/" />;
}
return <Element />;
};

In this example, the ProtectedRoute component is a HOC that wraps the <Element> component and checks if the user is authenticated using the local storage key name “token”. If the user is authenticated, it renders the Element passed as a prop to the ProtectedRoute component. If the user is not authenticated, it redirects them to the “/” (default) page.

To use the ProtectedRoute component, DhiWise passes it as an element prop from the <Route> component in Routes.js file:

<Route path="/dashboard" element={<ProtectedRoute element={Dashboard} />} />

This will ensure that authenticated users can only access the /profile route.



Got a question? Ask here.