DEV Community

loading...
Cover image for Implement Protected Routes in React.js

Implement Protected Routes in React.js

pprathameshmore profile image Prathamesh More ・2 min read

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

pic
Editor guide
Collapse
nawazmujawar profile image
Nawaz Mujawar

Cool....Its really helpful