Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 71

Implementing Protected Routes

Recommended resources

Hello! Welcome to the next lesson in our journey through client-side routing with React Router.

In our last lesson, we explored how to create nested UI layouts using the <Outlet> component. This allowed us to build consistent layouts, like a dashboard with a persistent sidebar, where only the main content area changes during navigation.

Today, we'll take that concept and make it secure. This lesson directly addresses the learning outcome: Implement protected routes to restrict access based on authentication status. We will build a mechanism that acts as a gatekeeper for our dashboard, ensuring that only logged-in users can access its content. This is a fundamental skill for building almost any real-world web application.

The Logic of a Protected Route

At its core, a protected route is a component that wraps our sensitive routes and makes a decision before rendering them. The logic is straightforward:

  1. Is the user authenticated (i.e., logged in)?
  2. If yes, render the requested page.
  3. If no, redirect the user to a public page, like the login screen.

We can visualize this decision-making process with a simple flowchart.

Protected Route Access Flowchart
This flowchart shows the logic for route access. It checks if a user is logged in. If not, they are redirected. If they are, it then checks if their role matches what's required for the route. For now, we'll focus on the first check: "Logged In?".

To implement this, we'll need three key pieces from React and React Router:

  • React Context: To manage and provide the user's authentication status across the application.
  • A Custom Wrapper Component: We'll call it ProtectedRoute. This component will contain our gatekeeper logic.
  • The <Navigate> Component: To perform the redirection when a user is not authenticated.

Step 1: Managing Authentication State

Before we can protect a route, our application needs to know whether a user is logged in. In Module 6, you learned about useContext for managing global state. This is the perfect tool for the job.

We'll create an AuthProvider that holds the authentication state (isAuthenticated) and provides functions to log in and out. We'll also create a custom useAuth hook to easily consume this context in other components.

The following video provides a clear walkthrough of setting up a simple AuthProvider using createContext, which will serve as the foundation for our protected route.

Custom Protected Route Component in React

Watch this segment from Cosden Solutions to see how to create a basic authentication context provider. This will manage whether a user is considered signed in or not.

Watch from 02:29 to 03:58. Pay attention to how createContext is used, how the AuthProvider component is structured with a simple isSignedIn state, and how the custom useAuth hook is created to simplify access to the context.

Here's a quick example of what that AuthContext might look like in our TypeScript project. You can place this in a file like src/contexts/AuthContext.tsx.

import React, { createContext, useContext, useState, ReactNode } from 'react';

// Define the shape of the context data
interface AuthContextType {
  isAuthenticated: boolean;
  login: () => void;
  logout: () => void;
}

// Create the context with a default undefined value
const AuthContext = createContext<AuthContextType | undefined>(undefined);

// Define the provider component
export const AuthProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
  // We'll use a simple boolean state for this example
  const [isAuthenticated, setIsAuthenticated] = useState(false);

  // In a real app, these functions would handle tokens, API calls, etc.
  const login = () => setIsAuthenticated(true);
  const logout = () => setIsAuthenticated(false);

  const value = { isAuthenticated, login, logout };

  return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
};

// Create the custom hook for consuming the context
export const useAuth = () => {
  const context = useContext(AuthContext);
  if (context === undefined) {
    throw new Error('useAuth must be used within an AuthProvider');
  }
  return context;
};

Finally, you would wrap your entire application (or at least the parts that need authentication) with this provider, typically in main.tsx.

// main.tsx
// ... imports
import { AuthProvider } from './contexts/AuthContext';

ReactDOM.createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <AuthProvider>
      <RouterProvider router={router} />
    </AuthProvider>
  </React.StrictMode>,
);

Step 2: Building the ProtectedRoute Component

Now for the main event. We'll create a component that uses the <Outlet> pattern from our previous lesson. This component will check the authentication status and either render its nested child routes or redirect the user.

// src/components/ProtectedRoute.tsx

import { Navigate, Outlet } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext';

const ProtectedRoute = () => {
  const { isAuthenticated } = useAuth();

  // If authenticated, render the child routes.
  // If not, redirect to the /login page.
  return isAuthenticated ? <Outlet /> : <Navigate to="/login" replace />;
};

export default ProtectedRoute;

Let's break down the key line: isAuthenticated ? <Outlet /> : <Navigate to="/login" replace />.

  • isAuthenticated: We get this from our useAuth hook.
  • <Outlet />: If isAuthenticated is true, we render the <Outlet>, which acts as the placeholder for our nested protected routes (e.g., the dashboard pages).
  • <Navigate to="/login" replace />: If isAuthenticated is false, we use the <Navigate> component to declaratively redirect the user. The replace prop is crucial here. It replaces the current entry in the browser's history stack instead of pushing a new one. This prevents the user from clicking the "back" button and ending up on the protected page they were just redirected from.

Integrating into the Router

With our ProtectedRoute component ready, we can use it in our router configuration to protect the dashboard layout we created in the last lesson.

// In your router configuration file (e.g., main.tsx)

const router = createBrowserRouter([
  {
    path: '/login',
    element: <LoginPage />, // A public login page
  },
  // ... other public routes
  {
    // This is our protected route group
    element: <ProtectedRoute />, 
    children: [
      {
        path: '/dashboard',
        element: <DashboardLayout />,
        children: [
          { index: true, element: <DashboardIndex /> },
          { path: 'profile', element: <UserProfile /> },
          { path: 'settings', element: <UserSettings /> },
        ],
      },
      // You could add other top-level protected routes here
      // { path: '/admin', element: <AdminPanel /> }
    ],
  },
]);

Now, any attempt to access /dashboard or its children will first be processed by ProtectedRoute. If the user isn't logged in, they'll be immediately sent to /login.


Step 3: Improving UX by Remembering the Original Destination

There's a common user experience problem with our current setup. Imagine a user tries to access /dashboard/profile. They are correctly redirected to /login. After they successfully log in, where do they go? Right now, they'd have to manually navigate back to /dashboard/profile. We can do better.

We can make our application "remember" where the user was trying to go and send them there automatically after they log in.

This involves a three-part change:

  1. In ProtectedRoute.tsx: Use the useLocation hook to get the user's current location and pass it along to the login page via the state prop on <Navigate>.
  2. In LoginPage.tsx: Use useLocation to check if this state exists.
  3. In LoginPage.tsx: After a successful login, use useNavigate to redirect the user back to the location stored in state.

The following video demonstrates this entire flow perfectly.

React Protected Routes | Role-Based Authorization | React Router v6

This video from Dave Gray clearly explains how to preserve the user's intended location during a redirect. This is a crucial UX improvement for any application with authentication.

First, watch from 10:04 to 13:15 to see how the RequireAuth (our ProtectedRoute) component is built using useLocation and how the location is passed in the state prop. Then, watch from 15:53 to 20:14 to see how the Login component uses this state to navigate the user back to their original destination after a successful login.

Here's how our ProtectedRoute.tsx and LoginPage.tsx would look with these changes:

ProtectedRoute.tsx (Updated)

import { Navigate, Outlet, useLocation } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext';

const ProtectedRoute = () => {
  const { isAuthenticated } = useAuth();
  const location = useLocation();

  return isAuthenticated 
    ? <Outlet /> 
    : <Navigate to="/login" state={{ from: location }} replace />;
};

export default ProtectedRoute;

LoginPage.tsx (Conceptual)

import { useLocation, useNavigate } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext';

const LoginPage = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const { login } = useAuth();

  // Get the 'from' location, or default to the dashboard
  const from = location.state?.from?.pathname || "/dashboard";

  const handleLogin = () => {
    // Perform actual login logic...
    login();
    // Redirect user back to where they came from
    navigate(from, { replace: true });
  };

  return (
    <div>
      <h1>Login Page</h1>
      <button onClick={handleLogin}>Log In</button>
    </div>
  );
};

export default LoginPage;

Advanced Topic: Role-Based Authorization

We've successfully handled authentication (is the user logged in?). The next level is authorization (is this logged-in user allowed to see this page?).

For example, you might have:

  • Regular users who can see their profile.
  • Editors who can see a post-editing page.
  • Admins who can see a user management panel.

We can extend our ProtectedRoute to handle this by passing it a list of allowedRoles.

React Protected Routes | Role-Based Authorization | React Router v6

Now let's extend our component to handle different user roles. This segment from the same Dave Gray video provides a fantastic, step-by-step guide on adding role-based authorization logic.

Watch from 20:14 to 28:15. This part covers modifying the protected route component to accept an allowedRoles prop and checking it against the user's roles. It also shows how to handle three distinct outcomes: authorized, unauthorized (but logged in), and unauthenticated.

The logic inside our ProtectedRoute would now look like this, assuming our useAuth hook also provides the current user's roles:

// Updated AuthContext to include user roles
interface AuthContextType {
  user: { roles: string[] } | null; // e.g., { roles: ['user', 'editor'] }
  // ... login/logout
}

// ProtectedRoute with role checking
const ProtectedRoute = ({ allowedRoles }: { allowedRoles: string[] }) => {
  const { user } = useAuth(); // Assuming useAuth now returns the user object
  const location = useLocation();

  if (!user) {
    // User is not logged in
    return <Navigate to="/login" state={{ from: location }} replace />;
  }

  const hasRequiredRole = user.roles.some(role => allowedRoles.includes(role));

  if (hasRequiredRole) {
    // User is logged in and has the required role
    return <Outlet />;
  } else {
    // User is logged in but does not have the required role
    return <Navigate to="/unauthorized" state={{ from: location }} replace />;
  }
};

And in your router, you'd use it by creating separate protected route groups for each role requirement:

const router = createBrowserRouter([
  // ... public routes
  {
    // Routes for any logged-in user
    element: <ProtectedRoute allowedRoles={['user', 'editor', 'admin']} />,
    children: [ { path: '/dashboard', element: <DashboardLayout /> } ]
  },
  {
    // Routes only for editors and admins
    element: <ProtectedRoute allowedRoles={['editor', 'admin']} />,
    children: [ { path: '/editor', element: <EditorPage /> } ]
  },
  {
    // Routes only for admins
    element: <ProtectedRoute allowedRoles={['admin']} />,
    children: [ { path: '/admin-panel', element: <AdminPanel /> } ]
  }
]);
Test your understanding!

You have a ProtectedRoute that accepts an allowedRoles prop. You need to create a new route at /analytics that should only be accessible to users with the 'admin' role. How would you add this to your createBrowserRouter configuration?

Show answer

You would create a new route definition that uses the ProtectedRoute component as its element, passing ['admin'] to the allowedRoles prop. The AnalyticsPage would be a child of this route.

const router = createBrowserRouter([
  // ... other routes
  {
    element: <ProtectedRoute allowedRoles={['admin']} />,
    children: [
      {
        path: '/analytics',
        element: <AnalyticsPage />,
      },
    ],
  },
]);

Conclusion

You have now mastered one of the most critical aspects of building secure React applications. By combining React Context, custom components, and React Router's Outlet and Navigate features, you can create robust protection for any part of your app.

Key Takeaways:

  • Protected routes act as gatekeepers, checking conditions like authentication before rendering content.
  • An AuthProvider using React Context is an effective way to manage and share authentication state.
  • A custom ProtectedRoute component can encapsulate the checking logic, typically using <Outlet> to render children or <Navigate> to redirect.
  • The replace prop on <Navigate> is essential for correct browser history management.
  • Passing the original location via state allows you to redirect users back to their intended page after login, creating a seamless user experience.
  • This pattern can be easily extended from simple authentication to more complex role-based authorization.

Preview of the Next Lesson:
We've covered what to do when a user tries to access a valid route they aren't allowed to see. But what about when they try to access a route that doesn't exist at all? In our final lesson of this module, we will learn how to handle 404 (Not Found) pages using a catch-all route, providing a graceful user experience for invalid URLs.