Implementing Protected Route and Authentication in React-JS
Tags: react, routing, beginners, redux
Published: 2021-03-13 23:49:11

---
title: Implementing Protected Route and Authentication in React-JS
published: true
description: This is a basic how to guide on implementing authentication and protected routes in ReactJS.
tags: react, routing, beginner, redux
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0p49gt9l9s5wgnpjr0m2.PNG
---

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](https://dev.to/olumidesamuel_/structuring-redux-in-a-react-web-app-1i21)_

#### 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7kl8gq6fe0j6w4fv6aok.PNG)


#### Signin Component
In `./src/view/Authentication/Signin.js`, let's create the Signin component,
![Signin Component](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cf3pl9lp2vasrlht58yh.PNG)

OnInputChange, update the userData state with the current value;
```javascript
 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.

```javascript
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2ont2wav5uqolxals4e0.PNG)

...

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.

```javascript
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1qoz1fwt4klm4ehtmka6.PNG)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vhe5sywmeudfxhxzera5.PNG)


#### Test run the Application
When the application is launched, it'll redirect to the Sign-in page,
![signin](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2p39adcd4vxw7d8u9f3m.PNG)

_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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lb96o2kxoac764jznjlu.PNG)

...
Here is a link to the code on [github](https://github.com/LuminousIT/auth-protected-route). 
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)](https://dev.to/olumidesamuel_/implementing-autologout-feature-in-web-applications-react-js-28k5)