Securing single-page apps with the Keycloak JavaScript adapter

Adding Keycloak login to a browser app with keycloak-js means a public client using authorization code with PKCE, a deliberate token refresh pattern and a silent check-sso design that holds up when browsers block third-party cookies.

On this page

How keycloak-js secures a single-page app with PKCE

keycloak-js runs the authorization code flow with PKCE in the browser as a public client, so the single-page app never holds a client secret and Keycloak issues tokens only after the browser proves possession of a code verifier it created. This page covers that browser-only design. It does not cover a backend-for-frontend, where a server holds the tokens and the browser holds only a session cookie. The adapter handles the redirect to the realm's authorization endpoint, the code exchange on return, the in-memory storage of access and refresh tokens, and the refresh calls that keep the session alive. The app still has to decide which routes require sign-in, what to do when a token cannot be refreshed, and how it calls its APIs.

Several pieces sit outside the adapter and must be set in the Keycloak client. The client must be configured as a public client with standard flow enabled and PKCE set to the S256 method. Valid redirect URIs and web origins must match the exact app URLs, including any wildcard you accept, because a loose pattern widens where codes can be returned. Keycloak's server administration guide describes these client settings. Confirm them against the Keycloak version you run, since client policy and default behavior can differ between releases.

Because tokens live only in memory, a page reload loses them unless the app re-runs the sign-in check, and a browser that blocks third-party cookies can break the silent check described below. Plan for these cases early: decide where the app shows a sign-in button, how long access tokens live in your realm, and how the app behaves when a refresh fails. Test sign-in, refresh and logout in each browser your users run, because cookie and storage rules differ and no single test run covers them all.

What a keycloak-js login project needs before work starts

A keycloak-js login project depends on a Keycloak realm, a browser app and a client configuration that all agree on the same public origins. Settle these items before any code is written, because most failed sign-ins trace back to a mismatch between them.

Keycloak realm over TLS

Confirm you have a running realm reachable over TLS at a public frontend URL that the browser can open directly. The production guide calls for TLS on all communication and a reverse proxy with path restrictions. Ask who owns the hostname, certificate renewal and the proxy rules, because the SPA cannot start a login until the realm answers at that address. Check that the realm's frontend URL matches the hostname your users will type.

Production guide

Admin and public hostname separation

Keep the admin console and Administration REST API on a different hostname or context path from the public frontend URLs. The SPA only needs the public login endpoints, so the proxy should not expose administrative paths to browsers that reach the app. Confirm which hostname the team will use for administration and that the reverse proxy blocks the admin paths on the public name before go-live.

Single-page app build and hosting

Decide how the SPA is built, where its static files are served and which origin they load from. The keycloak-js library runs in the browser, so the app's origin must be the one registered in Keycloak. Agree on the build pipeline, the environment-specific values for the realm URL and client ID, and whether the app and the realm share a site, since that choice affects cookie behavior later.

Public client, redirect URIs and web origins

Create a public client for the SPA with standard flow enabled and PKCE set to S256, so no client secret ships in the browser bundle. Register exact redirect URIs for each environment and list the matching web origins for CORS. Wildcards widen the set of places tokens can be returned, so ask the security team to approve each entry individually.

Realm admin console access

Name the people who will hold realm admin rights to create clients, change redirect URIs and rotate settings. Give them named accounts with multi-factor sign-in rather than a shared admin login, and keep a second administrator who can recover access. Changes to client settings take effect for every user of the app, so agree on a review step before anyone edits a production client.

Keycloak version and release line

Confirm the Keycloak version your team will run against the current release line before writing against its API. The supplied current release is 26.8.1, published October 13, 2026. Check the version your environment actually runs, since keycloak-js and server behavior should be tested against the same release. Plan a retest when you move to a later minor release.

Keycloak site

Configuring the Keycloak client and the keycloak-js init sequence

This sequence produces a public OpenID Connect client in Keycloak and a browser app that initializes keycloak-js, completes the login redirect, and keeps its access token fresh before each API call.

  1. Create a public OpenID Connect client

    A Keycloak administrator creates a new client in the target realm with the OpenID Connect protocol and a client ID the front end will use. Turn on client authentication off so the client is public, enable the standard flow (authorization code), and require PKCE with the S256 code challenge method. Public clients hold no secret, so the browser never carries one. The step is done when the client appears in the realm's client list with standard flow enabled and PKCE set, and you can see those settings on the client's details page.

  2. Set redirect URIs and web origins

    Add the exact application URLs Keycloak may return users to after login and logout, and list the origins allowed to make cross-origin requests to the token endpoint. Use specific paths rather than wildcards where your Keycloak version and policy allow it, and avoid broad patterns that match other applications on the same host. Confirm these values with your security team, because an overly broad redirect URI is a common route for token theft. The step is done when a test login from the listed origin completes and a request from an unlisted origin is refused by the browser.

  3. Install and configure keycloak-js

    In the front-end project, install the keycloak-js package and create a single Keycloak instance that points at the server URL, realm name and client ID. Keep these values in build-time or runtime configuration rather than in source code, so the same build can move between development and production realms. Confirm the package version against the Keycloak release your server runs, since the front-end library and server should be upgraded together. The step is done when the instance is created in the app without errors and the configuration values resolve in the running build.

  4. Initialize with login-required or check-sso

    Call the init method once at application startup and choose the onLoad mode deliberately. The login-required option sends anonymous users to the Keycloak login page immediately, which suits apps where every page needs a signed-in user. The check-sso option only checks for an existing Keycloak session and stays anonymous otherwise, which suits public pages. Set pkceMethod to S256 in the init options so the authorization code flow uses PKCE. The step is done when init resolves with the expected authenticated value for a signed-out browser and a signed-in browser.

  5. Handle the redirect callback

    After Keycloak redirects back with an authorization code, keycloak-js exchanges it for tokens during init and removes the code parameters from the address bar. Confirm your app waits for the init promise before rendering protected routes, so the page does not flash or call APIs with no token. If you use a silent check iframe, host the silent check page at a same-origin path and register it as a valid redirect URI. The step is done when a login returns the user to the intended page with the code parameters gone from the URL and the tokens present on the instance.

  6. Call updateToken before API requests

    Before each call to a protected API, call updateToken with a minimum validity window in seconds and wait for it to resolve. If the access token is close to expiry, keycloak-js uses the refresh token to obtain a new one. Attach the current accessToken as a bearer header only after this call succeeds, and route a failed refresh to a fresh login. Ask your team to confirm the minimum validity value against the access token lifespan set in the realm, since a window longer than the lifespan forces a refresh on every call. The step is done when requests after the window pass a fresh token to the API.

  7. Verify claims and expiry in a test session

    Open the app in a clean test browser profile, sign in, and inspect the decoded access token claims. Check the issuer, the audience or authorized party your APIs expect, the subject, the realm roles or client roles your app reads, and the expiry time against the realm settings. Then wait for the token to near expiry, trigger an API call, and confirm the token changed while the user stayed signed in. The step is done when the claims match the design and a refreshed token appears without a login prompt.

How the authorization code flow with PKCE runs in the browser

The authorization code flow with PKCE is the sign-in path keycloak-js uses for a browser app, and it works because the browser never needs a client secret. When the app calls keycloak.init with the login-required setting, the adapter generates a random code_verifier and a derived code_challenge, stores the verifier in session storage, and redirects the browser to the realm's authorization endpoint with the challenge attached. The user authenticates at Keycloak, which redirects back to the app with a one-time authorization code. The adapter then posts that code together with the original verifier to the token endpoint. Keycloak recomputes the challenge from the verifier and issues tokens only if they match. An intercepted code is useless without the verifier, which lives only in the browser that started the flow. That is why PKCE replaces the client secret for a public client, the client type you configure for a browser app because any secret shipped in JavaScript is visible to anyone who loads the page.

Tokens are held in the adapter's memory, and the adapter keeps only the ID token, access token and refresh token it needs for the session. Nothing in this design is stored in a cookie that the server reads, so the tokens are reachable by any script running in the page. A cross-site scripting flaw, or a compromised third-party script, can read them and use them until they expire. The practical controls are a strict Content Security Policy, a minimal set of third-party scripts, short access token lifespans in the realm, and refresh token settings that match how long a user should stay signed in. Confirm these values in your own realm, since the defaults may not match your policy.

The trade-off is against the backend-for-frontend design covered in the sibling topic on keycloak for SPAs. A backend-for-frontend keeps tokens on the server and gives the browser only a session cookie, which shrinks what an XSS payload can steal, at the cost of running a server component, managing session state and changing logout behavior. Choose the public PKCE client when the app is static or has no server to host the session, and the team can enforce strict script controls. Choose the backend-for-frontend when the application handles sensitive data and your security review will not accept tokens in page memory.

Request flow between the browser app, keycloak-js and Keycloak

The flow starts when the user opens the single-page app, which loads keycloak-js and calls init with login-required or check-sso. The adapter redirects the browser to the Keycloak authorization endpoint with a PKCE code challenge, and after sign-in the app exchanges the returned code at the token endpoint for tokens. Silent check-sso runs in a hidden iframe against the same endpoint, and updateToken refreshes access tokens before they expire. Check that the redirect URIs, web origins and PKCE settings match on the client, and that the API validates the token it receives.

Sign-in, silent session check and token refresh between the browser app and Keycloak.

How updateToken and check-sso keep sessions alive

updateToken(minValidity) checks the access token and refreshes it only when it will expire within the number of seconds you pass. Your app calls it immediately before sending a request to a protected API, so the token attached to that request is still valid when it reaches the resource server. Nothing refreshes in the background on a timer unless your code schedules it, which keeps the behavior easy to reason about during testing.

  • Trigger: the call itself. Choose a minValidity value that covers the time a request may take to reach the API, plus a margin for clock skew between the browser and Keycloak.
  • Failure path: if the refresh promise rejects, the refresh token is no longer usable. Send the user to a sign-in flow (for example, keycloak.login()) and retry the request after sign-in, rather than retrying the refresh in a loop.
  • Lifespan settings: the access token lifespan controls how often a refresh is needed, and the SSO session and refresh token settings in the realm decide whether a refresh still succeeds. Read these values from your realm configuration, not from memory.
  • Concurrency: several parallel API calls can each trigger updateToken. Route them through one shared promise so only one refresh request goes to Keycloak.
  • Token storage: the adapter keeps tokens in memory by default. Confirm where your build stores them before you rely on them surviving a page reload.

Before release, test a request that starts just before expiry and confirm the API receives a token with enough remaining life.

What changes when browsers block third-party cookies

Silent check-sso depends on a browser session that may not be sent. The keycloak-js adapter runs silent checks in a hidden iframe that loads the Keycloak login endpoint and reads the existing session. When the single-page app and Keycloak sit on different sites, that iframe is a third-party context. Browsers that block third-party cookies can withhold the Keycloak session cookie inside the iframe, so the check reports no session even though the user signed in a moment earlier. The app then either shows a signed-out state or falls back to a redirect, depending on how the team wrote the init call. Confirm this behavior in the exact keycloak-js version you ship, because browser cookie policy has changed repeatedly and each vendor applies it differently.

The main mitigation options differ in cost and in what they change. Serving the app and Keycloak under one site, for example by putting both behind a shared parent domain and reverse proxy, makes the iframe first-party and keeps silent checks working, but it constrains DNS, certificate and cookie domain design. A visible redirect fallback, where the app sends the user through a normal authorization request when the silent check fails, works in every browser but adds a page load and can interrupt users who simply reopened a tab. A backend-for-frontend keeps tokens on a server the app controls and avoids browser iframes for session state, at the cost of building and operating that server component. The related Keycloak for SPAs: public client with PKCE or backend for frontend choice should be made with these options in view.

Test the decision on the browsers and privacy settings your users actually run, not only the latest desktop Chrome build. Build a short matrix that covers each major browser your users use, managed enterprise settings that block third-party cookies, private browsing, and a session that starts before a browser restart. For each case, record whether silent check-sso returns an authenticated state, whether token refresh still works after the access token expires, and what the user sees. Ask your security and IT teams which browser versions and policies are standard in your workforce, and treat any failing case as a design input rather than a support ticket.

Mapping token claims and roles to app authorization

This table compares each token claim or role the SPA receives with what the browser may use it for and what the API must enforce. Read it as a split of duties: the SPA uses claims to shape the interface, while the API makes the access decisions from a token it validates itself.

Claim or roleWhat the SPA reads it forWhat the API enforcesKeycloak setting that supplies it
Subject (sub)Keying local state and cache entries to the signed-in userIdentifying the caller and scoping records to the ownerBuilt-in user identifier in the ID token and access token
Preferred usernameShowing the account name in the header or menuNot used for authorization, since display names can changeStandard profile claim mapped through the default client scopes
EmailDisplaying contact details and account pagesNot used as an identifier for access decisionsStandard email claim, released only through the scopes the client requests
Realm rolesHiding menu items and routes the user cannot open (illustrative: an admin menu)Checking the role before every protected operationRealm role mapper on the client scope that the access token includes
Client rolesShowing features scoped to this applicationChecking the client role on the resource server sideClient role mapper, configured per client scope and token type
Audience (aud)Not read for display, but the app should confirm it can use the token at allRejecting tokens not issued for this API before reading any claimAudience mapper in the client scope that adds the API client to the access token
Issuer (iss) and signatureNothing directly; the library checks them during loginValidating against the realm keys and expected issuer on every requestRealm URL and key set published by the Keycloak realm

Hardening a browser-based Keycloak login

A keycloak-js login runs in a browser that the application does not control, so the security of the sign-in depends on how the Keycloak client, the page and the network are configured. The cards below cover the Keycloak client settings, the browser-side controls and the transport and logout decisions that connect to the adapter code on this page.

Redirect URI and web origin allowlists

Keycloak returns authorization codes only to redirect URIs registered on the client, so wildcards and broad patterns widen who can receive them. Register the exact callback URLs for each environment and set web origins to the exact scheme, host and port that load the app, because these origins control which browser pages may call Keycloak from JavaScript. Check that development and staging hosts are not left in the production client.

Keycloak docs

PKCE enforcement on the public client

A browser app is a public client that cannot keep a client secret, so the authorization code flow must use PKCE to bind the code to the browser that started the login. Keycloak lets you require PKCE on the client rather than trusting the adapter to send it. Confirm that the client is set to require the S256 challenge method and that a token request without a verifier fails in a test.

Short access token lifespans with refresh

Access tokens held in the browser are readable by any script that runs there, so limiting their lifespan limits the damage of a leak. Keep the access token lifespan short in the realm settings and let keycloak-js call updateToken before expiry to renew it. Test what happens when the refresh token expires or the session ends, because the app must send the user back to login rather than fail silently.

Keeping tokens out of local storage

Tokens written to localStorage or sessionStorage can be read by any injected script, which makes cross-site scripting a token theft path. keycloak-js keeps tokens in memory by default, so the team should avoid code that copies them into browser storage for convenience. Review third-party scripts and any custom wrapper code for this pattern, and treat a hardened design that keeps tokens on a server as a separate decision covered in the SPA pattern comparison.

Strict Content Security Policy against XSS

A strict Content Security Policy limits which scripts the page may run, which reduces the chance that an injected script can read in-memory tokens or call Keycloak as the user. Avoid inline scripts and eval, list only the script and connect sources the app needs, and include the Keycloak host in the connect sources. Test the policy in report-only mode first, since the login redirect and silent check-sso iframe depend on specific frame and connect rules.

TLS and admin console separation

Every hop between the browser, the app and Keycloak should use TLS, because tokens and authorization codes travel in redirects and responses. Keycloak's production guide also calls for a reverse proxy with path restrictions and for exposing the admin console and Administration REST API on a different hostname or context path from public frontend URLs. Confirm that the public Keycloak hostname does not serve the admin console and that the frontend URL setting matches the hostname users see.

Production guide

Logout that ends the session everywhere

Logging out of the app alone leaves the Keycloak session active, so a silent check-sso on the next visit can sign the user back in. Call keycloak.logout with a registered post-logout redirect URI so the Keycloak session ends, and clear in-memory token state in the app. Decide whether other applications on the same session also need to end, because a single browser logout does not reach them without the logout mechanisms covered in the single logout topic.

Common keycloak-js failures and how to fix them

This table pairs each common keycloak-js failure with its usual cause and the fix to try first. Read it by matching the symptom your users or browser console show, then checking the client settings, browser behavior and token timing listed in the fix. Most failures trace back to the Keycloak client configuration or to browser policies that the app cannot control.

FailureLikely causeFix
Redirect URI mismatchThe page URL after login does not match a Valid redirect URI on the Keycloak client, often because of a trailing slash, a different port, or a missing environment-specific host.Register the exact origin and path for each environment in the client's Valid redirect URIs. Pass redirectUri explicitly in init or login so the value matches a registered entry.
CORS or web origin errorsThe browser blocks token or userinfo requests because the app origin is not listed in Web origins on the client, so Keycloak does not send the matching Access-Control-Allow-Origin header.Add the app origin to Web origins, without a path. Use the plus sign setting only if you intend to derive origins from redirect URIs. Confirm the exact origin in the browser network tab.
Redirect loop from check-ssoThe app calls login when check-sso returns no session, and the silent check redirects back to the app, so each load starts the flow again. Often caused by an invalid silent check-sso redirect URI or a page that is not loaded at the expected path.Use a dedicated silent-check-sso.html page on the app origin, pass silentCheckSsoRedirectUri to init, and call init with onLoad set to check-sso only when you need that behavior. Keep the login call behind an explicit user action or a guarded condition.
Silent check-sso timeout under blocked third-party cookiesThe iframe that runs the silent check cannot read Keycloak's session cookies because the browser blocks third-party cookies. The check never completes and keycloak-js reports a timeout or an unauthenticated state.Set a longer checkLoginIframeInterval only if needed, but first confirm the browser behavior. Plan for a fallback that sends the user through a normal login redirect, and test on the browsers your users run, including those with strict tracking protection.
updateToken failures after session expiryThe refresh token or SSO session has expired or been revoked, so the refresh request returns an error. Calling updateToken without handling the rejected promise leaves the app in a stale state.Wrap updateToken in a catch block and call login or clear local state when it rejects. Confirm the SSO Session Idle and Max values in the realm so that session lifetimes match what users expect.
Clock skew affecting token validityThe browser or the server clock differs enough from Keycloak that tokens look expired or not yet valid. The app may refresh too often or reject fresh tokens.Synchronize clocks with NTP on user machines where possible and on the Keycloak and app hosts. Keep the minValidity argument to updateToken reasonable, and check the iat, nbf and exp claims when you investigate.

Questions teams ask before building keycloak-js login

What drives the cost of adding keycloak-js login to our apps?

The cost follows the written scope, and the main drivers are the number of single-page apps, the number of realms, custom claims, the browsers and devices you must support, and the cookie strategy you choose. Each app needs its own public client, redirect URIs, web origins and logout settings, so more apps means more configuration, testing and review. Custom claims add mapper work and token checks on both the frontend and the APIs that consume them. Browser coverage matters because third-party cookie behavior differs across browsers and versions. DeployOpen does not publish a price list, so ask a quote to itemize each of these drivers, separate one-time build work from any recurring retainer for upgrades and testing, and state what is excluded.

How long does a keycloak-js implementation take?

Duration depends on the scope and on your environment, not on the library alone. A single app with one realm, a standard login flow and existing test accounts is a much smaller job than several apps spread across realms with custom claims, step-up requirements and a mix of browsers. Delays usually come from waiting on hostnames, certificates, realm admin access and sign-off on token lifetimes, not from writing the JavaScript. Ask the quote to show the schedule by milestone, the assumptions behind it, and which tasks depend on your team's responses.

What does our team need to provide before the work starts?

The work needs a few things from your side before it can move quickly:

  • Realm admin access, or an admin who can create clients, roles, mappers and client scopes in the target realm
  • Final public hostnames for each single-page app and for the Keycloak server, including the redirect and web origin URLs you will allow
  • Test accounts in each realm covering the roles, groups and organizations the apps depend on
  • A named owner for token lifetimes, logout behavior and the browser support list

Confirm these items in writing as part of the scope, since missing hostnames or accounts are a common cause of rework.

Can our internal team build keycloak-js login without outside help?

Yes, a team with frontend and identity experience can build it alone, and the Keycloak documentation covers the client settings and the adapter's login, token refresh and silent check-sso behavior. The hard parts are less about code and more about judgment: choosing between a public browser client and a backend for frontend, setting safe token lifetimes, handling refresh failures, and testing what happens when third-party cookies are blocked. Ask whether your team has someone who has done this before and whether they can own the work after go-live. An outside partner can make sense when the timeline is short, several apps must follow one pattern, or you want an independent review of the configuration.

How do third-party cookie restrictions change the keycloak-js design?

When a browser blocks third-party cookies, a silent check-sso iframe on a different origin may no longer see the Keycloak session, so the app can fail to restore a login silently. The fix usually involves serving the Keycloak server and the app under hostnames that share a site, reviewing how the silent check-sso page is hosted, and testing the full sign-in and refresh path in each browser you support. Ask the quote to state which browsers and versions are in the test matrix and how fallback behavior, such as a redirect to login, will look to users.

Which security checks should the keycloak-js rollout include?

A sound rollout uses the authorization code flow with PKCE on a public client, keeps redirect URIs and web origins as narrow as possible, and sets access token lifespans short enough that a stolen token has limited value. Teams should also confirm that tokens are refreshed with updateToken, that failed refreshes send users to sign in again, and that logout reaches every app in the session. Ask the quote to list which checks run before go-live and whether the review covers the Keycloak client settings as well as the browser code. Independent auditors, not DeployOpen, decide whether any control satisfies a specific compliance framework.

What keeps working after go-live, and what recurs?

Once the apps are live, you carry recurring work for Keycloak upgrades, browser changes, new apps and regular review of client settings. Keycloak ships minor releases several times a year, so client configuration and frontend library versions should be retested on a schedule. Ask whether the engagement includes handover documentation, a runbook for common failures and a retainer for upgrades and continuous testing, and what each of those costs on a recurring basis.

How DeployOpen scopes and delivers SPA login with Keycloak

DeployOpen plans, builds, tests and hands over browser sign-in for your single-page apps against a Keycloak realm running in infrastructure you control. Each engagement starts with a written scope that names the apps, realms, clients and browsers involved, so your security and platform teams can review the design before any build starts.

How we scope

  • Inventory each single-page app, its routes, API calls and whether it needs silent sign-in or only a login redirect.
  • Agree the realm, public client settings, redirect URIs, web origins and token lifetimes in writing before work starts.
  • Define which browsers, third-party cookie settings and identity providers the written scope must cover.

How we build

  • Configure the public client for authorization code flow with PKCE and wire keycloak-js into the app's startup and token refresh logic.
  • Implement updateToken handling, check-sso silent sign-in with a silent check SSO redirect page, and logout that clears local state.
  • Test sign-in, refresh, expiry and logout across the browsers in scope, including setups where third-party cookies are blocked.

How we hand over

  • Deliver the realm and client configuration, the application changes and a written record of each setting and why it was chosen.
  • Document the token lifetime, refresh and logout behavior so developers and platform engineers can maintain it after handover.
  • Walk through the test results and the known limits, such as browser cookie behavior, with the team that will run the app.

How we support

  • Engagements are fixed-scope, with scope, deliverables and timelines agreed in writing before work starts.
  • Ongoing support, upgrades and continuous testing are available as a retainer, including retesting after Keycloak or browser changes.
  • Ask for a quote based on the written scope, which sets out the components, the one-time work and any recurring support.

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.