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.


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)


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,
} from "react-router-dom";

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

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

  const login = () => {

  const logout = () => {

  return (
    <div className="App">
          <Route path="/" exact>
            {isAuthenticated ? (
              <Redirect to="/secret" />
            ) : (
                <Link to="/secret">Go to secret</Link>
                <button onClick={login}>Log in</button>
          <Route path="*">
            <div>404 Not found </div>

export default App;

Enter fullscreen mode Exit fullscreen mode

React app running

Source code:

Stay safe!

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

Top comments (3)

nawazmujawar profile image
Nawaz Mujawar

Cool....Its really helpful

ymoran00 profile image

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?

edgaremmanuel profile image

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