Day 19 – Protected Routes & Auth Basics in React
3 mins read

Day 19 – Protected Routes & Auth Basics in React

In real-world applications, not all pages should be accessible to everyone. For example:

  • A blog’s admin dashboard should be visible only to logged-in users.
  • An e-commerce checkout page must be available only after login.

This is where Protected Routes & Auth Basics come in. In React, we handle this by combining authentication state with React Router to control access.


What Are Protected Routes?

Protected Routes are simply normal React routes wrapped with authentication logic.

  • If the user is logged in → show the page.
  • If not logged in → redirect to login page.

This ensures secure routing and prevents unauthorized users from accessing sensitive parts of your app.


Step 1: Setup Authentication State

In a real project, authentication usually comes from API + JWT (JSON Web Token).
But for simplicity, let’s simulate login/logout using React’s useState hook.

import React, { useState } from "react";
import { BrowserRouter as Router, Routes, Route, Navigate } from "react-router-dom";

const Login = ({ setAuth }) => {
  return (
    <div>
      <h2>Login Page</h2>
      <button onClick={() => setAuth(true)}>Login</button>
    </div>
  );
};

const Dashboard = ({ setAuth }) => {
  return (
    <div>
      <h2>Dashboard (Protected)</h2>
      <button onClick={() => setAuth(false)}>Logout</button>
    </div>
  );
};

Step 2: Create ProtectedRoute Component

We now create a wrapper component that checks if the user is authenticated.

const ProtectedRoute = ({ isAuth, children }) => {
  if (!isAuth) {
    return <Navigate to="/login" replace />;
  }
  return children;
};

Here’s how it works:

  • If isAuth === false → user is redirected to /login.
  • If isAuth === true → user can access the protected component.

Step 3: Add Routes in App

Now let’s combine everything inside App.js.

function App() {
  const [isAuth, setAuth] = useState(false);

  return (
    <Router>
      <Routes>
        <Route path="/login" element={<Login setAuth={setAuth} />} />
        <Route
          path="/dashboard"
          element={
            <ProtectedRoute isAuth={isAuth}>
              <Dashboard setAuth={setAuth} />
            </ProtectedRoute>
          }
        />
        <Route path="/" element={<h2>Home Page (Public)</h2>} />
      </Routes>
    </Router>
  );
}

export default App;

How This Works

  1. Visit /dashboard without logging in → redirected to /login.
  2. Click Login button → sets isAuth to true.
  3. Now /dashboard is accessible.
  4. Click Logout button → sets isAuth to false, access removed.

This is the core idea of Protected Routes & Auth Basics.


Extending to Real Authentication

In production, instead of useState, you would:

  • Use JWT tokens stored in localStorage or httpOnly cookies.
  • Fetch login state from your backend API.
  • Persist user state with Context API or Redux.

Example login flow with real API:

  1. User enters email/password → send to backend.
  2. Backend returns a JWT token.
  3. Store token in localStorage or cookies.
  4. ProtectedRoute checks token before rendering the page.

👉 Read more about JWT Authentication


Conclusion

With this, you’ve learned Protected Routes & Auth Basics in React.
We covered:

  • What protected routes are.
  • How to use Navigate for redirection.
  • Creating a ProtectedRoute wrapper.
  • Simulating login/logout with useState.
  • Extending logic to real-world APIs with JWT.

This is the foundation of authentication in React apps. Next, we’ll learn Redux in React – Core Concepts for Day 20 🚀.

Leave a Reply

Your email address will not be published. Required fields are marked *