Detecting 403 Responses
You'll learn how to programmatically detect 403 Forbidden responses and handle them differently from authentication failures.
Why Detection Matters
In the previous lesson, you learned how to redirect users to login when a 401 occurs. But what about 403? A 403 means the user is authenticated—the server knows who they are—but they don't have permission to access that resource. Detecting this distinction is crucial for showing the right error message.
How to Detect 403 Responses
When making HTTP requests, check the response status code:
fetch('/api/admin/users', {
headers: {
'Authorization': `Bearer ${token}`
}
})
.then(response => {
if (response.status === 403) {
// User is authenticated but not authorized
console.log('Access denied: insufficient permissions');
return;
}
if (response.status === 401) {
// Authentication issue - handled separately
window.location.href = '/login';
return;
}
return response.json();
})
.catch(error => {
console.error('Request failed:', error);
});
The Key Distinction
Think of it like a secured building: a 401 is "we don't know who you are, show your ID badge," while a 403 is "we know you're Bob from Marketing, but this is the executive floor—access denied." Both prevent access, but for very different reasons requiring different user feedback.
When you detect a 403, you typically show an error message like "You don't have permission to view this page" rather than redirecting to login (the user is already logged in!).
Key Takeaway: Always check for response.status === 403 separately from 401 errors to distinguish authorization failures from authentication failures and provide appropriate user feedback instead of unnecessary login redirects.