Member-only story
🔁 Fixing Keycloak Auto-Redirect on Refresh: How to Persist Authentication in SPAs
If you’re using Keycloak with a frontend built on JavaScript or React, you may have hit this common snag: refreshing the page sends users back to the Keycloak login screen. Why does this happen — and how do we fix it?
Let’s dive into a clean solution with examples and best practices.
🔍 Understanding the Issue
When using keycloak-js
, the tokens (accessToken
, refreshToken
, and idToken
) are stored in memory by default. That means when your app reloads, those tokens vanish.
Result? Keycloak sees you as unauthenticated and kicks off a new login flow.
✅ Solution: Persist Tokens Across Reloads
You can fix this by saving tokens in localStorage
or sessionStorage
after login, and restoring them on page load.
1. Store Tokens After Login
keycloak.init({ onLoad: 'login-required' }).then((authenticated) => {
if (authenticated) {
localStorage.setItem('kc_token', keycloak.token);
localStorage.setItem('kc_refreshToken', keycloak.refreshToken);
localStorage.setItem('kc_idToken', keycloak.idToken);
}
});