Implement Protected Routes in React.js
Tags: react, routes, node
Published: 2020-08-16 17:06:07

---
title: Implement Protected Routes in React.js
published: true
description: Implement protected routes in React.js
tags: react, routes, reactjs, nodejs
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/09xhsf0kj8zrzat220fa.jpg
---

We are going to start our project as always using `npx create-react-app protected-routes`.

Install react-router-dom for routing functionality:

`npm i react-router-dom`

Now, we will remove the boilerplate code from `App.js` and create basic routes in our `App.js` file as following.

![app.js](https://dev-to-uploads.s3.amazonaws.com/i/xkwg1wvoaehf1jvz9va8.png)

As you can see above in code, we created `/` and `/secret`, public, and secret routes respectively.

But `/secret` route still accessible to anyone i.e unauthorized user, Now we have to protect this route.

Now we will create a state hook to hold login status and function to change state in memory.

Basically we will do this in `App.js` to keep all things simple.

![Hold state](https://dev-to-uploads.s3.amazonaws.com/i/5vq8casf5lisbdzpujjg.png)

Next, create a generalized component that will accept props as authentication status, the path of the component to be rendered, log out function reference, and actual component to render.

![Protected Route](https://dev-to-uploads.s3.amazonaws.com/i/e7dupy14m1nwf4fs2edy.png)

In the above code, we destructing props, which are important for our functionality and return `<Route />` component as per authentication status. If the user is not logged in we will redirect to the homepage.

Now create `Secret.js` for secret component i.e page and import with `withRouter(Component)`

![Secret.js](https://dev-to-uploads.s3.amazonaws.com/i/d7wfjhjaso52l2nz6zw8.png)

Updated `App.js` at the end.

Here, we created a state and some useful functions for authentication.

```

import React, { useState } from "react";
import {
  BrowserRouter as Router,
  Route,
  Switch,
  Redirect,
  Link,
} from "react-router-dom";

import ProtectedRoute from "./ProtectedRoute";
import Secret from "./Secret";

function App() {
  const [isAuthenticated, setIsAuthenticated] = useState(false);

  const login = () => {
    setIsAuthenticated(true);
  };

  const logout = () => {
    setIsAuthenticated(false);
  };

  return (
    <div className="App">
      <Router>
        <Switch>
          <Route path="/" exact>
            {isAuthenticated ? (
              <Redirect to="/secret" />
            ) : (
              <div>
                <h1>Homepage</h1>
                <Link to="/secret">Go to secret</Link>
                <br></br>
                <button onClick={login}>Log in</button>
              </div>
            )}
          </Route>
          <ProtectedRoute
            isAuthenticated={isAuthenticated}
            path="/secret"
            logout={logout}
            component={Secret}
          />
          <Route path="*">
            <div>404 Not found </div>
          </Route>
        </Switch>
      </Router>
    </div>
  );
}

export default App;

```

Output: 
![React app running](https://dev-to-uploads.s3.amazonaws.com/i/q0sdisawwsmv2swf3r7y.gif)


Source code: https://github.com/pprathameshmore/protected-routes-react

Stay safe!

Looking for an entry-level job as a Backend Developer or Full Stack Web Developer in India and Europe.

http://pprathameshmore.github.io/