Handling Failed Refresh Attempts
What you'll learn: How to gracefully handle scenarios where refresh tokens fail, ensuring users are redirected to login rather than stuck in a broken authentication state.
When Refresh Tokens Fail
Even with refresh tokens in place, they can fail for several reasons: they've expired, been revoked, invalidated on the server, or tampered with. When your silent refresh attempt returns an error (typically a 401 or 403 status), you need a clear recovery strategy.
The Core Pattern
When a refresh token request fails, you should:
- Clear all authentication state – Remove both access and refresh tokens from storage (cookies, memory, wherever you keep them)
- Redirect to login – Send the user back to the login page
- Preserve context – Optionally save the current URL so users can return after re-authenticating
Here's a conceptual flow:
async function refreshAccessToken() {
try {
const response = await fetch('/api/auth/refresh', {
method: 'POST',
credentials: 'include' // sends httpOnly cookie
});
if (!response.ok) {
throw new Error('Refresh failed');
}
return await response.json();
} catch (error) {
// Refresh failed - clear auth state
clearAuthTokens();
// Save current location for post-login redirect
sessionStorage.setItem('redirectAfterLogin', window.location.pathname);
// Redirect to login
window.location.href = '/login';
}
}
Why This Matters
Without proper error handling, users might see infinite retry loops, partially authenticated states, or cryptic errors. By clearing state and redirecting, you provide a clean, expected experience: "Your session expired, please log in again."
Key Takeaway: Always catch failed refresh attempts, clear all auth tokens, and redirect users to login—treat expired refresh tokens as the end of a valid session, not a recoverable error.