0PricingLogin
React Academy · Lesson

Protected Routes & Auth Guards

Redirect unauthenticated users to login using wrapper components or loader-based guards.

Why Protect Routes?

Some pages (dashboard, profile, admin) should only be accessible to authenticated users. React Router provides two approaches: wrapper components and loader-based guards.

Auth State Shape

First, establish an auth context that components can read to know if the user is logged in.

const AuthContext = React.createContext(null);

function AuthProvider({ children }) {
  const [user, setUser] = useState(null);
  const login = async (creds) => { const u = await apiLogin(creds); setUser(u); };
  const logout = () => setUser(null);
  return (
    <AuthContext.Provider value={{ user, login, logout }}>
      {children}
    </AuthContext.Provider>
  );
}

export const useAuth = () => useContext(AuthContext);

All lessons in this course

  1. Nested Routes & Outlet Layouts
  2. Loaders & Actions (Data Router API)
  3. Protected Routes & Auth Guards
  4. Managing State in URL Search Params
← Back to React Academy