DEV Community

Cover image for Implement Protected Routes in React.js
Prathamesh More
Prathamesh More

Posted on

Implement Protected Routes in React.js

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

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

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

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

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;

Enter fullscreen mode Exit fullscreen mode

Output:
React app running

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/

Discussion (3)

Collapse
nawazmujawar profile image
Nawaz Mujawar

Cool....Its really helpful

Collapse
ymoran00 profile image
Yoav

This is cool - but it's not really protected, is it? All the user needs to do is open Chrome devTools and change the app's state to authorized. Isn't there a better way to stop unauthorized routing?

Collapse
edgaremmanuel profile image
DevByJESUS

you can juste build your own authentication and replace it with what he has done here