Education
Last updated onSep 2, 2024
Last updated onSep 2, 2024
In the context of React web application, protected routes are those routes that only grant access permission to authorized users. For example, while making a login request for your social media account you need to provide an id and password to access a specific route.
While building a web application you need to protect specific routes from users who don’t have authentication to access that route. The protected routes alias private routes help you to implement exactly that. It lets you choose the routes which users can visit based on whether they are logged in or not.
In this article, we will learn how to create protected routes in the React web application all from scratch.
So let's get started with creating a React app.
Before creating a protected route we must have a React application already created and the components for which we are implementing the protected routes.
1 // create a React application 2 3 npx create-react-app protect-routes-react 4
Navigate to the folder which you have just created and start your application.
1 cd protect-routes-react 2 npm start 3
Next, you need to open your application folder. Your app.js should look something like this.
1 // Empty React application 2 3 function App() { 4 return
Install the react-router-dom version 6. It is a standard library for routing in React that enables developers to navigate among views of various components in React app, change browser URLs, and keep the UI in synchronization with the URL.
1 npm install react-router-dom@6
However before creating the protected routes, you should find out whether the user is authenticated. So let's create a way to log in users with the fake useAuth Hook and determine the user’s authentication status. This helps you to understand how to implement the useAuth Hook.
1 import * as React from "react"; 2 3 const authContext = React.createContext(); 4 5 function useAuth() { 6 const [authed, setAuthed] = React.useState(false); 7 8 return { 9 authed, 10 login() { 11 return new Promise((res) => { 12 setAuthed(true); 13 res(); 14 }); 15 }, 16 logout() { 17 return new Promise((res) => { 18 setAuthed(false); 19 res(); 20 }); 21 }, 22 }; 23 } 24 25 export function AuthProvider({ children }) { 26 const auth = useAuth(); 27 28 return
Use the useAuth hook whenever you want to know whether the user is authenticated, login to a user account, or log out from the user account. The hook exposes the values from the library and enables any component to get the current authentication state and rerenders on the state changes.
In this application, we will create the following three components:
Let’s render the above routes through the following application
1 2 3 4 5 6 import * as React from "react"; 7 import { Link, Routes, Route } from "react-router-dom"; 8 9 const Home = () => <h1>Home (Public)</h1>; 10 const About = () => <h1>About (Public)</h1>; 11 const Dashboard = () => <h1>Dashboard (Private)</h1>; 12 13 14 15 const Login = () => <h1>TODO</h1>; 16 17 function Nav() { 18 return ( 19 <nav> 20 <ul> 21 <li> 22 <Link to="/">Home</Link> 23 </li> 24 <li> 25 <Link to="/about">About</Link> 26 </li> 27 </ul> 28 </nav> 29 ); 30 } 31 32 export default function App() { 33 return ( 34 <div> 35 <Nav> 36 <Routes> 37 <Route path="/" 38 element={<Home />} /> 39 <Route path="/about" 40 element={<About />} /> 41 <Route path="/dashboard" 42 element={<Dashboard />} /> 43 <Route path="/login" 44 element={<Login />} /> 45 </Routes> 46 </div> 47 ); 48 } 49
At this point we are only mapping the app’s location to the few components. But how will you authenticate a user to Log in? Here, we need to build a Login component.
Login Component:
The Login component here renders a header and a button. On the Login button click login and the user will be navigated to the dashboard upon successful login.
1 import { useNavigate } from "react-router-dom"; 2 import useAuth from "./useAuth"; 3 4 const Login = () => { 5 const navigate = useNavigate(); 6 const { login } = useAuth(); 7 8 const handleLogin = () => { 9 login().then(() => { 10 navigate("/dashboard"); 11 }); 12 }; 13 14 return ( 15 <div> 16 <h1>Login</h1> 17 <button onClick={handleLogin}>Log in</button> 18 </div> 19 ); 20 }; 21 22 23 24
Log Out Component:
Now, using the same useAuth hook creates the method to Logout.
1 import { useNavigate } from "react-router-dom"; 2 import useAuth from "./useAuth"; 3 4 function Nav() { 5 const { authed, logout } = useAuth(); 6 const navigate = useNavigate(); 7 8 const handleLogout = () => { 9 logout(); 10 navigate("/"); 11 }; 12 13 return ( 14 <nav> 15 <ul> 16 <li> 17 <Link to="/">Home</Link> 18 </li> 19 <li> 20 <Link to="/about">about</Link> 21 </li> 22 </ul> 23 {authed && <button onClick={handleLogout}>Logout</button>} 24 </nav> 25 ); 26 } 27 28
Next, we need to add protected routes to the dashboard, so only the authenticated users can access it.
1 <Routes> 2 <Route path="/" element={<Home />} /> 3 <Route path="/about" element={<Pricing />} /> 4 <Route 5 path="/dashboard" 6 element={ 7 <RequireAuth> 8 <Dashboard /> 9 </RequireAuth> 10 } 11 /> 12 <Route path="/login" element={<Login />} /> 13 </Routes> 14
;
In the above code you can add more protected routes inside the RequireAuth components similar to the dashboard. The RequireAuth renders the child element only if they are authenticated otherwise, it will be redirected back to the login page.
Here, the RequireAuth function will look something like this:
1 function RequireAuth({ children }) { 2 const { authed } = useAuth(); 3 4 return authed === true ? children :
So, this is just one way to add protected routes to your React application. You can build a custom hook to add authentication and add multiple protected routes to your React application.
DhiWise React web application builder goes way further to simplify application development. The web builder lets you easily set navigation in and out using a visual programming language in a few simple steps.
The social media authentication functionality in the app builder allows you to set up authentication using social media accounts so users do not have to set up and use an id and password. And they can easily sign up or log in using their social media accounts.
These are just a few capabilities of DhiWise web builder. It offers everything from design to code generation to UI customization to deployment.
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.