DEV Community

Hamza Ali
Hamza Ali

Posted on

Protected Routes In React

What is protected Routing

Protected routes are routes that can only be accessed when a certain condition is met. Commonly those conditions are

  • If the user is authenticated or not
  • If the user session is expired or not.

Why do we need protected Routing

We need protected routing to protect certain page from the user that don’t have the access to view that page.

For Example

we have a route /home/profile and on this page a user can preform some actions that can change the data. If this page is accessible to all then the data on this page is no longer secure. To address this issues protected routes come into play.

Lets get our hands dirty

Lets dive into a coding example to better understand what protected routing is.

We are going to build a new react project with npx

Run the below code in the terminal and it will create a new react project.

npx create-react-app protected-route-example
Enter fullscreen mode Exit fullscreen mode

learn more about how to setup a new react project
https://reactjs.org/docs/create-a-new-react-app.html

Navigate to the project that we just created by running the command in the terminal or you can also navigate to the project using the GUI

cd protected-route-example

Get rid of the boilerplate code from App.js that is generated by the npx create-react-app

After refactoring the App.js should look like this

function App() {
  return (
    <div>
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

We are now ready to setup the routes for our project

Install react-router-dom

npm install react-router-dom
Enter fullscreen mode Exit fullscreen mode

want to read more about react-router-dom https://reactrouter.com/docs/en/v6

After install the package lets setup a container/navbar that will contain all the visual links to go to our routes

create a file called navbar.js
Add the following code in navbar.js

import React from 'react';
import { Link } from 'react-router-dom';

export default function () {
    return (
        <div style={{display: 'flex', flexDirection:'column',justifyContent: 'center'}}>
            <Link to="/home" >Home</Link>
            <Link to="/dashboard" >Dashboard</Link>
            <Link to="/contact-us" >Contact us</Link>
        </div>
    )
}
Enter fullscreen mode Exit fullscreen mode

want to read more about Link https://reactrouter.com/docs/en/v6/components/link

Now lets define our routes and also render navbar in app.js file.

import { BrowserRouter, Route, Routes } from "react-router-dom";
import Navbar from './navbar'
import Home from './home'
import ContactUs from './contactus'
import Dashboard from './dashboard'

function App() {
  return (
    <BrowserRouter>
      <Navbar/>
      <Routes>
        <Route
          path="/home"
          element={<Home/>}
        />
        <Route
          path="/contact-us"
          element={<ContactUs/>}
        />
        <Route
          path="/dashboard"
          element={<Dashboard/>}
        />

      </Routes>
    </BrowserRouter>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

create home.js, contactus.js and dashboard.js

home.js

export default function Home(){
    return(
        <h1>Home</h1>
    )
}
Enter fullscreen mode Exit fullscreen mode

contactus.js

export default function ContactUs(){
    return(
        <h1>Contact Us</h1>
    )
}
Enter fullscreen mode Exit fullscreen mode

dashboard.js

export default function Dashboard(){
    return(
        <h1>Dashboard</h1>
    )
}
Enter fullscreen mode Exit fullscreen mode

Setup Protected Route

Now lets setup a route that is protect. We are going to use react's useState hook to set if the user is logged in or not.
Learn more about react hooks here https://reactjs.org/docs/hooks-intro.html

Setup fake authentication

we are going to setup a fake authentication process that is going to tell us if the user is logged in or not.
***you can update it according to your usecse

Update the app.js file

import { BrowserRouter, Route, Routes } from "react-router-dom";
import Navbar from './navbar'
import Home from './home'
import ContactUs from './contactus'
import Dashboard from './dashboard'
import { useState } from "react";
function App() {
  const [isUserLoggedIn, setIsUserLoggedIn] = useState(false)
  return (
    <BrowserRouter>
      <Navbar/>
      {
        isUserLoggedIn?
        <button onClick={()=>setIsUserLoggedIn(false)}>Log out</button>:
        <button onClick={()=>setIsUserLoggedIn(true)}>Log In</button>
      }
      <Routes>
        <Route
          path="/home"
          element={<Home/>}
        />
        <Route
          path="/contact-us"
          element={<ContactUs/>}
        />
        <Route
          path="/dashboard"
          element={<Dashboard/>}
        />

      </Routes>
    </BrowserRouter>
  );
}

export default App;

Enter fullscreen mode Exit fullscreen mode

Now lets create a protected route component that is going to determine weather the user has access to view the protected page or not.

create a file ProtectedRoute.js

ProtectedRoute.js

import { Navigate } from "react-router-dom";
export default function ProtectedRoute({isUserLoggedIn,children}) {
    if(!isUserLoggedIn) return <Navigate to="/"/>
    return children
}
Enter fullscreen mode Exit fullscreen mode

Now use the protectedRoute component to those Routes that you want to protect

Update the route that you want to protect

<Route
          path="/dashboard"
          element={
          <ProtectedRoute isUserLoggedIn={isUserLoggedIn}>
              <Dashboard/>
          </ProtectedRoute>
          }
        />
Enter fullscreen mode Exit fullscreen mode

update the app.js

import { BrowserRouter, Route, Routes } from "react-router-dom";
import Navbar from './navbar'
import Home from './home'
import ContactUs from './contactus'
import Dashboard from './dashboard'
import { useState } from "react";
import ProtectedRoute from "./protectedRoute";

function App() {
  const [isUserLoggedIn, setIsUserLoggedIn] = useState(false)
  return (
    <BrowserRouter>
      <Navbar/>
      {
        isUserLoggedIn?
        <button onClick={()=>setIsUserLoggedIn(false)}>Log out</button>:
        <button onClick={()=>setIsUserLoggedIn(true)}>Log In</button>
      }
      <Routes>
        <Route
          path="/home"
          element={<Home/>}
        />
        <Route
          path="/contact-us"
          element={<ContactUs/>}
        />
        <Route
          path="/dashboard"
          element={
          <ProtectedRoute isUserLoggedIn={isUserLoggedIn}>
              <Dashboard/>
          </ProtectedRoute>
          }
        />

      </Routes>
    </BrowserRouter>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Now the dashboard route is protected and is only accessible to the user who are logged in.

Conclusion
Did you guys find the method that I have listed above useful. If you have any suggestion leave them in the comments.
That it for this blog. Thank you for reading.

That's all from me! Bye!

Top comments (0)