codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
⚛️

React.js

27 / 61 topics
24Introduction to React Router25Basic Routing with React Router26Nested Routes in React Router27Protected Routes in React Router
Tutorials/React.js/Protected Routes
⚛️React.js

Protected Routes

Updated 2026-05-15
10 min read

Protected Routes

Introduction

In modern web applications, it's common to have certain pages or routes that should only be accessible to authenticated users. Implementing protected routes is a crucial aspect of securing your application and ensuring that sensitive information remains private.

This tutorial will guide you through the process of implementing protected routes in a React application using React Router for navigation and routing.

Concept

To implement protected routes, we need to create a higher-order component (HOC) or a custom hook that checks if a user is authenticated before rendering a specific route. If the user is not authenticated, they should be redirected to a login page or shown an error message.

Steps to Implement Protected Routes:

  1. Set Up Authentication State: Typically, this involves storing authentication status in React Context or using a state management library like Redux.
  2. Create a Protected Route Component: This component will check the authentication status and render the appropriate content.
  3. Use the Protected Route in Your Application: Integrate the protected route into your routing configuration.

Examples

Step 1: Set Up Authentication State

First, let's set up a simple authentication state using React Context. This example assumes you have a basic understanding of how to use context in React.

// src/context/AuthContext.js
import React, { createContext, useState } from 'react';

const AuthContext = createContext();

export const AuthProvider = ({ children }) => {
  const [isAuthenticated, setIsAuthenticated] = useState(false);

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

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

  return (
    <AuthContext.Provider value={{ isAuthenticated, login, logout }}>
      {children}
    </AuthContext.Provider>
  );
};

export default AuthContext;

Step 2: Create a Protected Route Component

Next, we'll create a ProtectedRoute component that checks the authentication status and renders the appropriate content.

// src/components/ProtectedRoute.js
import React from 'react';
import { Navigate } from 'react-router-dom';
import AuthContext from '../context/AuthContext';

const ProtectedRoute = ({ children }) => {
  const { isAuthenticated } = React.useContext(AuthContext);

  if (!isAuthenticated) {
    return <Navigate to="/login" replace />;
  }

  return children;
};

export default ProtectedRoute;

Step 3: Use the Protected Route in Your Application

Now, let's integrate the ProtectedRoute into your routing configuration.

// src/App.js
import React from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import AuthProvider from './context/AuthContext';
import Login from './pages/Login';
import Dashboard from './pages/Dashboard';
import ProtectedRoute from './components/ProtectedRoute';

const App = () => {
  return (
    &lt;AuthProvider&gt;
      &lt;Router&gt;
        &lt;Routes&gt;
          <Route path="/login" element={<Login />} />
          <Route
            path="/dashboard"
            element={
              &lt;ProtectedRoute&gt;
                <Dashboard />
              </ProtectedRoute>
            }
          />
          <Route path="*" element={<Navigate to="/login" replace />} />
        </Routes>
      </Router>
    </AuthProvider>
  );
};

export default App;

Explanation

  • AuthContext: Manages the authentication state and provides login and logout functions.
  • ProtectedRoute: Checks if the user is authenticated. If not, it redirects to the login page using React Router's &lt;Navigate&gt; component.
  • App Component: Sets up the routing configuration, using ProtectedRoute to protect the /dashboard route.

Practical Example

Let's create a simple login and dashboard page to demonstrate how this works.

// src/pages/Login.js
import React from 'react';
import AuthContext from '../context/AuthContext';

const Login = () => {
  const { login } = React.useContext(AuthContext);

  return (
    <div>
      &lt;h2&gt;Login</h2>
      <button onClick={login}>Login</button>
    </div>
  );
};

export default Login;
// src/pages/Dashboard.js
import React from 'react';

const Dashboard = () => {
  return (
    <div>
      &lt;h2&gt;Dashboard</h2>
      <p>Welcome to your protected dashboard!</p>
    </div>
  );
};

export default Dashboard;

Testing the Protected Routes

  1. Start your application and navigate to /dashboard.
  2. Since you are not authenticated, you should be redirected to the login page.
  3. Click the "Login" button on the login page to authenticate.
  4. Now, when you navigate to /dashboard, you should see the protected dashboard content.

What's Next?

In this tutorial, we covered how to implement protected routes in a React application using React Router and context for authentication state management. In the next section, we will explore handling forms in React, which is another essential aspect of building interactive web applications.

Feel free to experiment with different authentication mechanisms and routing configurations to suit your application's needs.


PreviousNested Routes in React RouterNext Introduction to Redux

Recommended Gear

Nested Routes in React RouterIntroduction to Redux