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
- Nested Routes & Outlet Layouts
- Loaders & Actions (Data Router API)
- Protected Routes & Auth Guards
- Managing State in URL Search Params