VOOZH about

URL: https://dev.to/olumidesamuel_/implementing-protected-route-and-authentication-in-react-js-3cl4

⇱ Implementing Protected Route and Authentication in React-JS - DEV Community


NOTE:

An updated rewrite of this article on protected routes can be found here. A lot has changed in the React ecosystem since this was first written in 2021. React Router moved from v5 to v7, class components have faded out, and the patterns we use for authentication state have matured. Please check the link to read how to do the same in modern React 2026.

Almost every web application require some form of authentication to prevent unauthorized users from having access to the inner workings of the applications.

For this tutorial, I'll be showing how to set up an authentication route and protect other routes from been accessed by unauthorized users.

First things first,

Install all dependencies

  • npm i react-router react-router-dom
  • Add link to bootstrap CDN in ./public/index.html header

React-router will handle our routing, i.e switching from one page to another within the web application.

Note: We'll be building ontop of the last project from Structuring redux in a web app

Home Component

First, in ./src/view/Home let's create an Home component which will serve as our homepage. Note: onComponentDidMount, some demo data are fetched from https://jsonplaceholder.typicode.com/users to populate the landing page.
👁 Homepage

Signin Component

In ./src/view/Authentication/Signin.js, let's create the Signin component,
👁 Signin Component

OnInputChange, update the userData state with the current value;

 const handleInputChange = (e) => {
 setUserData((prevState) => {
 return {
 ...prevState,
 [e.target.name]: e.target.value,
 };
 });
 };

OnSubmit, if username and password supplied by user matches admin and 123456 respectively,

  • save isAuthenticated as true in localStorage,
  • else display appropriate error message. The data saved in localStorage will be used later to confirm Authentication status.
const handleSubmit = (e) => {
 e.preventDefault();

 //if username or password field is empty, return error message
 if (userData.username === "" || userData.password === "") {
 setErrorMessage((prevState) => ({
 value: "Empty username/password field",
 }));

 } else if (
 userData.username.toLowerCase() === "admin" &&
 userData.password === "123456"
 ) {
 //Signin Success
 localStorage.setItem("isAuthenticated", "true");
 window.location.pathname = "/";
 } else {
 //If credentials entered is invalid
 setErrorMessage((prevState) => ({ value: "Invalid username/password" }));
 return;
 }
 };

App.js Component

In ./src/App.js, add the created component to the BrowserRouter from react-router-dom,

👁 App.js

...

At this point, if the project is launched, we'll be redirected to the landing page because the path="/" points to the Home component. However, it'll be great to protect the route such that only authenticated users can have access to that route and every other user redirected to the Signin Page. This leads us to the concept of Protected Route in React-JS.

Protected Route

Protected Routes are routes that can only be accessed if a condition is met(usually, if user is properly authenticated). It returns a Route that either renders a component or redirects a user to another route based on a set condition.

In ./src/components/ProtectedRoute.js,

  • create a functional component that accepts component and other route details as props, and then
  • check a condition to confirm if user is authenticated or not. (In our case, we'll be getting isAutheticated from localStorage)
  • if the value is true, render the component, else, Redirect route to /signin page.
import React from "react";
import { Redirect, Route } from "react-router-dom";

function ProtectedRoute({ component: Component, ...restOfProps }) {
 const isAuthenticated = localStorage.getItem("isAuthenticated");
 console.log("this", isAuthenticated);

 return (
 <Route
 {...restOfProps}
 render={(props) =>
 isAuthenticated ? <Component {...props} /> : <Redirect to="/signin" />
 }
 />
 );
}

export default ProtectedRoute;

In ./src/App.js, import the ProtectedRoute and pass the Home component into it,
👁 Protected route

Let's add logout button to the Homepage, onClick the logout button, clear the isAuthenticated value in localStorage, and then redirect the route to Sign-in page.

👁 Alt Text

Test run the Application

When the application is launched, it'll redirect to the Sign-in page,
👁 signin

To test if the protected route work as it should, edit the route to visit the homepage as http://localhost:3001/ , you'll notice the app will be redirected back to the Signin page at http://localhost:3001/signin page.

Landing Page
After a successful login with the set credentials: Username: admin, Password: 123456,

👁 landing page

...
Here is a link to the code on github.
I hope this is helpful to someone. Like, share and bookmark. :)
...

If you would be interested in implementing an automatic logout feature after some seconds of user inactivity, read this next article I wrote - Implementing AutoLogout Feature in Web Applications (React)