How to Create a Protected Route with react-router-dom?

A protected route in a React application is a route that only authorized users can access. This is useful for securing parts of an application that should not be available to everyone. We will see how we can create a protected route with react-router-dom.

Prerequisites:

Steps to Setup ReactJS Application and Installing Required Modules

Step 1: Create a ReactJS application using the following command

npx create-react-app my-app

Step 2: Navigate to the Project directory

cd my-app

Step 3: Install the necessary packages/libraries in your project using the following commands

npm install react-router-dom

Project Structure:

Project Structure

The updated dependencies in package.json file will look like:

"dependencies": { 
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.22.3",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}

Approach to Create a Protected Route

  • Create an isAuthenticated state in the App component to track whether the user is logged in.
  • Inside the ProtectedRoute component in the App, add Route elements for its child components we want to keep protected.
  • Create a ProtectedRoute component that checks if the user is authenticated.
  • When a user is authenticated we will render the child routes using <Outlet /.> otherwise redirect the user to the login page using <Navigate to/>.
  • Create LoginPage where we will perform a simple hardcoded check for credentials.
  • If the credentials are correct, we call the login function and navigate the user to the Dashboard page using useNavigate.

Example: In this example, we have created a protected dashboard route which will be accessible only if the user is authenticated.

JavaScript
// App.js
import React, { useState, useEffect } from 'react';
import { Route, Routes } from 'react-router-dom';

import { BrowserRouter } from 'react-router-dom'
import Dashboard from './components/Dashboard';
import ProtectedRoute from './components/ProtectedRoute';
import LoginPage from './components/LoginPage';
const App = () => {
    const [isAuthenticated, setIsAuthenticated] = 
                                useState(false);

    const login = () => {
        setIsAuthenticated(true);
    };

    const logout = () => {
        setIsAuthenticated(false);
    };

    return (
        <BrowserRouter>
            <Routes>
                <Route element={<ProtectedRoute isAuthenticated
                                        ={isAuthenticated} />} >
                    <Route path="dashboard" 
                           element={<Dashboard logout
                                     ={logout} />} />

                </Route>

                <Route path="/" 
                       element={<LoginPage login
                                 ={login} />} />

            </Routes>
        </BrowserRouter>
    );
};

export default App;
JavaScript
// ProtectedRoute.js
import React from 'react'
import { Navigate, Outlet } from 'react-router-dom'

const ProtectedRoute = (props) => {
    // let auth={'token': false}
    return (
        props.isAuthenticated ? 
        <Outlet /> : <Navigate to="/" />
    )
}

export default ProtectedRoute;
JavaScript
// LoginPage.js
import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';

const LoginPage = ({ login }) => {
    const [userId, setUserId] = useState('');
    const [pass, setPass] = useState('');
    const navigate = useNavigate();

    const handleLogin = () => {
        if (userId === 'user' && pass === 'pass') {
            login(userId, pass);
            navigate('/dashboard');
        }
    };

    return (
        <div>
            <h2>Login Page</h2>
            <div>
                <input
                    type="text"
                    placeholder="User ID"
                    value={userId}
                    onChange={(e) => 
                        setUserId(e.target.value)}
                />
            </div>
            <div>
                <input
                    type="text"
                    placeholder="Password"
                    value={pass}
                    onChange={(e) => 
                        setPass(e.target.value)}
                />
            </div>
            <button onClick={handleLogin}>Login</button>
        </div>
    );
};

export default LoginPage;
JavaScript
// Dashboard.js
import React from 'react';
import { useNavigate } from 'react-router-dom';

const Dashboard = ({ logout }) => {
    const navigate = useNavigate();

    const handleLogout = () => {
        logout();
        navigate('/');
    };

    return (
        <div>
            <h2>Hello user welcome to Dashboard</h2>
            <h3>This page is protected</h3><br />
            <button onClick={handleLogout}>
                Logout
            </button>
        </div>
    );
};

export default Dashboard;

Step to Run Application: Run the application using the following command from the root directory of the project

npm start

Output:

Output



Contact Us