Course contentsShow
← React
Lesson 1867 of 2,39643. RoutingFree lesson

Basic Auth Check Pattern

Implementing a simple wrapper component that checks auth state and redirects unauthenticated users to login.

Basic Auth Check Pattern

You'll learn how to create a reusable wrapper component that automatically redirects unauthenticated users to a login page.

What Problem Does This Solve?

After learning what protected routes are, you need a practical way to implement them. The Basic Auth Check Pattern uses a simple wrapper component that sits between your route and the actual content. It checks whether a user is authenticated and either renders the protected content or redirects them to login.

Think of it like a bouncer at a club: before letting anyone into the VIP section, they check credentials. If you don't have the right pass, you're redirected to the entrance.

The Core Pattern

The pattern involves creating a component (often called ProtectedRoute or RequireAuth) that:

  1. Checks the current authentication state
  2. If authenticated → renders the requested content
  3. If not authenticated → uses Navigate to redirect to login
function ProtectedRoute({ children }) {
  const isAuthenticated = useAuth(); // Your auth hook

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

  return children;
}

You wrap protected content with this component:

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

The beauty of this pattern is its simplicity and reusability. Every route that needs protection uses the same wrapper, ensuring consistent auth checks across your application without repeating logic.

Key Takeaway: The Basic Auth Check Pattern uses a wrapper component that checks authentication state and conditionally renders content or redirects to login, providing a clean, reusable solution for protecting routes.