Protected Routes In React Js

Protected Routes In React Js

·

4 min read

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 user that doesn’t have the access to view that page.

For Example

we have a route /home/profile and on this page, a user can perform 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 issue protected routes come into play.

Let's get our hands dirty

Let's 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

learn more about how to set up a new react project 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;

We are now ready to set up the routes for our project

Install react-router-dom

npm install react-router-dom

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

After installing the package let's 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>
    )
}

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

Now let's define our routes and also render the 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;

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

home.js

export default function Home(){
    return(
        <h1>Home</h1>
    )
}

contactus.js

export default function ContactUs(){
    return(
        <h1>Contact Us</h1>
    )
}

dashboard.js

export default function Dashboard(){
    return(
        <h1>Dashboard</h1>
    )
}

Setup Protected Route

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

Setup fake authentication

we are going to set up 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 use case

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;

Now let's create a protected route component that is going to determine whether 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
}

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

Update the route that you want to protect

<Route
          path="/dashboard"
          element={
          <ProtectedRoute isUserLoggedIn={isUserLoggedIn}>
              <Dashboard/>
          </ProtectedRoute>
          }
        />

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;

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 suggestions leave them in the comments. That's it for this blog. Thank you for reading.

That's all from me! Bye!