Authentication Patterns
JWT handling, protected routes, session management, and OAuth integration.
Overview
Authentication is critical for securing React applications and protecting user data.
Key Concepts
- JWT Tokens — Stateless authentication with JSON Web Tokens
- Protected Routes — Guard routes requiring authentication
- Refresh Tokens — Maintain sessions without re-login
- OAuth — Third-party authentication with Google, GitHub, etc.
- Auth Context — Share authentication state across app
Code Examples
function ProtectedRoute({ children }) {
const { user, loading } = useAuth();
if (loading) return <LoadingSpinner />;
if (!user) return <Navigate to="/login" replace />;
return children;
}
function AuthProvider({ children }) {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
const token = localStorage.getItem('token');
if (token) {
verifyToken(token)
.then(setUser)
.catch(() => localStorage.removeItem('token'))
.finally(() => setLoading(false));
} else {
setLoading(false);
}
}, []);
const login = async (email, password) => {
const { token, user } = await api.login(email, password);
localStorage.setItem('token', token);
setUser(user);
};
const logout = () => {
localStorage.removeItem('token');
setUser(null);
};
return (
<AuthContext.Provider value={{ user, loading, login, logout }}>
{children}
</AuthContext.Provider>
);
}
Practice
Implement OAuth login with Google and handle token refresh automatically.