Keycloak for SPAs: when a public PKCE client is enough and when to add a backend
A public PKCE client is enough for a single-page app that holds no sensitive server-side data and calls APIs that can validate tokens on their own. A backend for frontend (BFF) is the better fit when the browser must never hold access or refresh tokens, or when the app needs server-side sessions, data stored under the user's identity, or policy enforcement before requests leave the server. Keycloak supports the OpenID Connect authorization code flow with PKCE for public clients, so both patterns use the same realm and the same login flow. The difference lies in where the tokens are kept and which client settings you configure.
With a public client, the SPA runs the authorization code flow with PKCE, receives tokens in the browser, and sends the access token to each API. In the Keycloak client settings, you set the client authentication to off, enable standard flow, and list exact redirect URIs and web origins for each environment. Tokens in browser storage are readable by any script that runs in the page, so this pattern depends on strict content security policy, short access token lifespans, and APIs that check audience and signature. A BFF instead registers a confidential client, keeps tokens in server-side storage, and gives the browser an httpOnly session cookie. Plan the cookie scope, the session timeout and the CSRF defense before you choose it.
Confirm three things with your security team before you pick a pattern: whether your APIs can validate tokens locally or need introspection, whether your logout requirements can be met with front-channel or back-channel logout, and whether the browser is allowed to hold refresh tokens at all. The Keycloak server administration guide documents the client settings for both options, and the answers to these questions determine the client configuration you will build. Confirm the lifespans and session limits for your own realm, since these are set by your organization, not by the pattern.
Public client with PKCE vs backend for frontend compared
This table compares a public browser client using PKCE with a backend for frontend that holds tokens on the server, across the areas that change Keycloak client settings and your infrastructure. Read each row as a question to answer for your own app, then use the Keycloak column to see what you configure and the operations column to see what you run.
| Area | Public client with PKCE | Backend for frontend (confidential client) |
|---|---|---|
| Where tokens live | Access and refresh tokens are held in browser memory or storage and sent by the SPA to APIs | Tokens stay on the BFF server; the browser holds only an HTTP-only session cookie |
| Keycloak client type | Public client with standard flow enabled and PKCE set to S256 | Confidential client with a client secret or signed client authentication and standard flow enabled |
| Client secret use | None; the code verifier replaces a secret, so the browser code cannot be trusted with one | Secret or signed JWT stored in the BFF configuration or secret store, never in the frontend bundle |
| Session handling | Token refresh runs in the browser; session lifetime depends on Keycloak realm and client token settings | BFF manages the session and refresh server-side; you set session idle and max lifetimes in your BFF and Keycloak |
| Cookies and CORS | Needs allowed web origins and redirect URIs in Keycloak; third-party cookie limits can affect silent checks | Browser talks to the same site as the BFF, so CORS is mostly avoided; cookie attributes such as Secure, SameSite and path must be set |
| Logout behavior | Front-channel logout and local token clearing; tokens already issued remain valid until expiry unless short lifetimes are set | BFF ends its own session and can trigger Keycloak logout; back-channel logout endpoints must be registered and reachable from Keycloak |
| Fit for regulated data | Workable for lower-sensitivity data, but tokens in the browser widen the exposure to XSS and token theft | Generally preferred where audit teams expect tokens kept off the browser; you still need a review of the BFF's own controls |
| What you operate | The SPA hosting, CDN and origin configuration; no extra server component | A BFF service with its own scaling, session store, patching, logging and secret rotation in your infrastructure |
Configuring the Keycloak client for each pattern
This sequence sets up the Keycloak client, redirect rules, token lifespans and login checks for either a public browser client using PKCE or a confidential backend for frontend client, so each design can be verified before application code is written.
Choose the client type for your architecture
Decide before touching the admin console whether the browser app will hold tokens itself (public client with PKCE) or whether a backend service will hold them and the browser will only receive a session cookie (backend for frontend). The platform team and the application owner should agree on this in writing, because the client type, redirect URIs and logout behavior all follow from it. Confirm that your SPA framework and hosting model support the chosen pattern. The step is done when both teams sign off on one client type per application and environment.
Create the realm client with the right authentication setting
In the admin console, open the target realm and create a new OpenID Connect client. For a public SPA, leave client authentication off so Keycloak treats the client as public and issues no client secret. For a BFF, turn client authentication on so the backend can authenticate with a secret or another supported client authentication method. Record the client ID and where the secret or credential will be stored. The check is that the client's settings page shows the authentication choice you agreed on, and that the credentials tab matches it.
Enable the authorization code flow with PKCE
Keep standard flow enabled and disable implicit and direct access grant flows, since neither is needed for a browser sign-in with the authorization code flow. For a public client, set the PKCE code challenge method to S256 in the client's advanced settings so Keycloak requires a code verifier at the token endpoint. For a BFF, PKCE remains a sound addition for the backend's code exchange, and the team should confirm that their chosen library sends it. The check is that a login attempt with the SPA or BFF library completes and that a request without a code challenge is rejected.
Define exact redirect URIs and web origins
Enter each redirect URI as a full, exact address, including the callback path your library uses, and avoid wildcards that match unrelated paths or hosts. For a public SPA, add the allowed web origins for the single-page app's domain so that browser token requests from that origin are permitted. For a BFF, the redirect URI points to the backend's callback route, and the browser origin is not the token-receiving endpoint. Separate development, staging and production hostnames into their own entries. The check is that a login from an unlisted URI or origin fails with an error rather than redirecting.
Set token and session lifespans for the pattern
Review access token lifespan, refresh token behavior and SSO session idle and maximum values in the realm and client settings. A public SPA holds access and refresh tokens in the browser, so keep access token lifespans short and confirm the refresh token rules your security team has approved. A BFF keeps tokens on the server, so the session lifetime is governed by the backend's own session store and cookie settings as well as Keycloak's session values. Write the chosen values in your configuration record and confirm them with your security owner. The check is that a token issued at login shows the expected expiry in its claims.
Confirm discovery metadata and endpoints
Open the realm's OpenID Connect discovery document, which Keycloak publishes under the realm's well-known configuration path, and confirm the issuer, authorization, token and end session endpoints match the public hostname your users will reach. Check that the advertised code challenge methods include S256. If the issuer contains an internal hostname, fix the frontend URL and reverse proxy settings before continuing, since browsers and the backend will reject mismatched issuers. The check is a clean metadata response from the hostname that clients will use.
Test the login end to end
Run a full sign-in with a test user from the application, through the Keycloak login page, back to the callback, and into an authenticated view. For a public SPA, inspect the token request and confirm it includes a code verifier and no client secret. For a BFF, confirm the browser receives a session cookie and never receives an access or refresh token in the response body or local storage. Repeat the test with a user who has no access to confirm the denial path. The check is a repeatable test record for each environment that matches the pattern you chose.
Test logout and document the configuration
Sign out from the application and confirm the session ends in Keycloak, then check that the post-logout redirect URIs you configured are the only accepted targets. Store the client settings, redirect URIs, lifespans and any secret rotation procedure in your configuration repository, and assign an owner for rotating the BFF client credential. Logout behavior across multiple applications has its own trade-offs, so confirm the single logout design separately. The check is a written configuration record and a logout test that ends the Keycloak session.
How the browser, BFF and Keycloak exchange tokens
The diagram sets two login paths side by side. In the public client path, the single-page app runs the authorization code flow with PKCE and receives tokens in the browser, so the browser is inside the token trust boundary. In the BFF path, the browser holds only a session cookie, and the backend holds the tokens and calls Keycloak as a confidential client. Check where each token lives, which component can reach Keycloak's token endpoint, and what ends the session on logout.
Public SPA token handling compared with a BFF that keeps tokens on the server.
Security trade-offs in token storage and XSS exposure
The choice between a public PKCE client and a backend for frontend comes down to where tokens sit and what an attacker can reach if the browser is compromised. The cards below cover token placement, cross-site scripting, cookie attributes, CSRF, redirect strictness and transport security, which together decide how much a browser-side flaw can expose.
Token placement in each pattern
With a public client, the access token and refresh token are returned to the browser and kept in JavaScript memory or browser storage. With a backend for frontend, Keycloak issues tokens to a confidential client on the server, and the browser holds only a session cookie. Map which tokens exist, where each one is stored and which component can read it before choosing a pattern. Keep in mind that a refresh token in browser storage can outlive a page session.
Keycloak docsXSS reach to browser-held tokens
Cross-site scripting that runs in the SPA's origin can read any token the page can read, and can send authenticated requests on the user's behalf while the session lasts. A BFF limits this exposure because the token never reaches page script, but script can still call the BFF's own endpoints from the logged-in session. Test both patterns with a stored and a reflected payload to confirm what an attacker could do.
HttpOnly, Secure and SameSite cookies
A BFF session cookie should carry the HttpOnly attribute so page script cannot read it, Secure so it travels only over TLS, and SameSite set to limit cross-site sends. Confirm the values your framework sets by default and whether the cookie scope is limited to the BFF host. Cookie lifetime should match the session policy you set in Keycloak, not a long default.
CSRF protection for the BFF
Once the browser holds a session cookie, the browser attaches it automatically to cross-site requests, so state-changing BFF routes need a separate defense. Common choices are anti-CSRF tokens tied to the session, checks on the Origin or Referer header, and SameSite settings applied to the session cookie. Verify that every POST, PUT and DELETE route on the BFF enforces at least one of these checks.
Strict redirect URIs and web origins
Keycloak compares redirect URIs for the client against the registered list, and the web origins setting controls which origins may make cross-origin requests. Use exact redirect URIs without wildcards for production clients, and limit web origins to the SPA's origin. For a public client, a loose redirect pattern lets an attacker receive authorization codes. Review these settings for each environment, since development hostnames often leak into production.
Production guideTLS on all communication
Keycloak's production guide calls for TLS on all communication, including the browser to the SPA or BFF, the BFF to Keycloak, and Keycloak to its backend services. Without TLS, tokens, codes and session cookies can be read on the network, and the Secure cookie attribute will not work. Confirm certificate handling on the reverse proxy, the trust store used by the BFF, and the HTTPS issuer URL in each client's configuration.
How session and logout differ between a SPA and a BFF
With a public client, the single-page app runs the authorization code flow with PKCE, receives tokens in the browser and renews them itself. Session state lives in the browser and in Keycloak's own SSO session, so the app's sense of being signed in depends on tokens it can read. Silent renewal typically uses a refresh token, or a hidden iframe check when refresh tokens are not issued to the client, and both depend on what the browser allows.
- Silent renewal: The app refreshes access tokens before they expire, using the refresh token or the check-sso iframe approach, and each path has different browser dependencies.
- Refresh token rotation: Confirm in the client settings whether refresh tokens are rotated on use and how long reuse of an old token is tolerated, since a stolen token that is still valid is the main risk.
- Token lifetimes: Keep access token lifespans short in the realm settings, because back-channel logout reaches only applications that register for it, and a browser token cannot be revoked by Keycloak alone.
- Logout clears browser state: RP-initiated logout redirects to Keycloak's end-session endpoint, and the app must delete tokens from memory and storage, otherwise the page still appears signed in.
- Idle behavior: Idle time is governed by the SSO session settings in the realm, so a closed tab does not end the session on its own.
Confirm the redirect URIs, web origins and post-logout redirect URIs on the client, and test sign-out from a fresh browser profile to confirm no tokens remain.
With a backend for frontend (BFF), a server component is the confidential OIDC client. It completes the code flow, holds the access and refresh tokens, and gives the browser only an HTTP-only session cookie. Session lifetime and idle timeout are then enforced by your server and its session store, and Keycloak's SSO session becomes a second, separate clock that the BFF must respect when it refreshes tokens.
- Server-side session lifetime: Set an absolute maximum and an idle timeout in the BFF session store, and decide whether each refresh extends the idle timer.
- Refresh behavior: The BFF refreshes tokens on the server, so a failed refresh should end the local session and send the user to sign-in rather than leave a stale cookie.
- RP-initiated logout through the backend: The browser calls a logout endpoint on the BFF, which destroys the local session and redirects to Keycloak's end-session endpoint with the ID token hint and a registered post-logout redirect URI.
- Back-channel logout registration: Register the BFF's back-channel logout URL on the confidential client so Keycloak can end its session when the user signs out elsewhere, and verify the logout token signature.
- Session store protection: Sessions and tokens sit in the store you operate, so encryption, access control and eviction on that store become part of the logout design.
Confirm with your application team how the BFF handles a refresh failure and a logout initiated in another application, and test both paths.
Logout is where the two patterns diverge most. A public client can end its own state, but it cannot reliably end sessions in other applications unless those applications receive a signal. Keycloak supports front-channel and back-channel logout for applications that register for them, and an application that does not register will keep a valid session until its token or local session expires. Short access token lifespans bound that window, but they do not end sessions that the application keeps locally.
- Local versus global sign-out: Decide whether sign-out ends only this app or the Keycloak SSO session shared with other apps, and label the choice in the user interface.
- Back-channel reach: Only applications that register a back-channel logout URL receive the signal, so inventory which apps are registered before promising a global sign-out.
- Token lifespan: Keep access token lifespans short enough that an application without logout support loses access within an interval your risk owner accepts.
- Frontend-only logout gap: A public client that clears storage without calling the end-session endpoint leaves the Keycloak session alive, so the next sign-in may happen silently.
- Testing: Sign out in one application and attempt access in each other registered application to observe what actually ends.
Ask your security team to set the accepted maximum window for lingering access and confirm it matches the token lifespans configured in Keycloak.
Operating the backend and client settings after go-live
Once a SPA is live, the two patterns put different work on your team. A backend for frontend keeps session state on your servers, while a public client with PKCE moves more risk into client settings that must be reviewed whenever the app changes. The cards below cover the load, monitoring and change controls that connect these choices after go-live.
Session store scaling for a BFF
A backend for frontend holds user sessions and tokens on your servers, so every replica must see the same session data. Decide whether sessions live in a shared store that all replicas read, or whether you rely on sticky routing at the load balancer. Sticky routing fails during replica restarts and scale-in events, so test what users experience when a pod is replaced. Ask your team who owns the session store, its backups and its capacity planning.
Monitoring Keycloak with Prometheus
Keycloak exposes Prometheus-format metrics at /metrics on its management interface when started with --metrics-enabled=true. Enable the optional HTTP request and cache histograms when you need latency and cache behavior during login spikes. Scrape the endpoint only from your monitoring network, since the management interface should not be reachable from public frontend hostnames. Alert on login failure rates and token endpoint latency so a broken SPA redirect or a token refresh storm shows up quickly.
Metrics guideReviewing redirect URIs during changes
Every release that adds a route, a preview environment or a new hostname can change the redirect URIs and web origins your public client accepts. Keep these values as a reviewed list in your configuration, not as wildcards that widen over time. Treat each change as a security change, with a second reviewer and a test that confirms unknown redirect URIs are rejected. Ask your team to name who may edit client settings in the production realm.
Auditing client policies and scopes
Client policies and default client scopes determine which PKCE rules, token lifetimes and mappers apply to your SPA client. Review them after each Keycloak upgrade, since minor releases can change defaults and the project makes breaking changes opt-in only in minor releases. Export client configuration as code where possible so differences between environments are visible in a diff. Record who approved each change so auditors can trace it.
Rotating the BFF client secret
A confidential BFF client authenticates to Keycloak with a client secret, which must be rotated on a schedule and after any suspected exposure. Plan rotation so the new secret is deployed to every BFF replica before the old one is revoked, or sign-in will fail during the overlap. Store the secret in your secrets manager, not in source control or container images. Ask your team how a rotation is tested in staging before it reaches production.
Planning Keycloak upgrade impact
Upgrades can change how an SPA or BFF behaves, so each upgrade needs a test plan that covers sign-in, token refresh and logout in a non-production realm. Read the upgrade notes for the target release before scheduling work, paying attention to changes in logout token validation and login failure storage. Keep a rollback path for the database schema and the client configuration. Ask your provider to confirm the test scope and the rollback steps in writing.
Upgrading guideQuestions teams ask before choosing a SPA pattern
What drives the cost and effort of a public client with PKCE compared with a backend for frontend?
The public client with PKCE is the smaller build: the browser app runs the authorization code flow with PKCE, holds tokens in memory, and calls APIs directly, so the main work is client registration, redirect URI rules, token refresh, and logout handling in the browser. A backend for frontend adds a server component that runs the confidential client, stores tokens, manages the session cookie, and proxies API calls, so it adds services to build, deploy, patch, and monitor. Effort rises with the number of APIs behind the BFF, the session store design, and the number of environments. Ask any partner to split the quote into the Keycloak client configuration, the application changes, and the ongoing support for the extra server component.
How long does a SPA integration with Keycloak take?
Duration depends on scope rather than on the pattern name alone. The main drivers are how many SPAs and APIs share the realm, whether the team already runs a backend service that can host a BFF, how many environments need matching client settings, and whether logout and token refresh must work across several applications. This page does not give a duration because no researched figure supports one. Ask for a timeline tied to a written scope, with named milestones for the Keycloak client setup, the application changes, testing in each environment, and the production cutover.
What does the work need from our own team?
Plan to supply realm access or an admin account for the Keycloak instance that will hold the client, the public hostnames for the SPA and any BFF, and the redirect and post-logout URIs for each environment. Your CI system and secrets store must hold any client secret used by a BFF, and your platform team must confirm the reverse proxy routes for the frontend and API paths. Keycloak's production guidance expects TLS on all traffic and separate hostnames for the admin console, so confirm those choices before the build starts. Name one owner for realm changes so client settings do not drift between environments.
Can an internal team set this up without outside help?
Yes, if the team already runs Keycloak in production and has engineers who know OAuth 2.0 and OpenID Connect well. The public client route can often be built from the Keycloak server administration guide and the SPA library the team already uses. The BFF route needs more skills: session handling, cookie security settings, a server framework, and a process for rotating the client secret. A useful check is whether the team can explain how logout reaches the browser session and the BFF session, and whether someone can run the setup in a test realm before touching production. DeployOpen can take on the full build or review an internal design, depending on the written scope.
When is a backend for frontend required for regulated data?
A BFF is not mandated by Keycloak itself. The decision follows your own risk assessment and the rules your auditors apply to the data the SPA handles. Teams with strict requirements often choose a BFF so that access and refresh tokens never reach browser JavaScript, which reduces the exposure to cross-site scripting. Ask your compliance team which control objectives cover token handling, session lifetime, and logout, then map each one to a client setting or server behavior. Keep in mind that a BFF moves the risk to the server and session store, so those components also need hardening, logging, and patching.
What client settings change between a public client and a BFF in Keycloak?
A public client is set with client authentication turned off, standard flow enabled, PKCE required with the S256 challenge method, and exact redirect URIs for each environment. A BFF uses a confidential client with client authentication on and a client secret or another supported client authentication method, so the server can exchange the code and keep the secret. Both need precise web origins, valid post-logout redirect URIs, and token lifetimes chosen for the session model. Confirm each setting against the current Keycloak server administration guide for your version, because client policy defaults can differ between releases.
What goes wrong most often with either pattern?
The most common faults are loose redirect URIs, missing PKCE enforcement on the public client, tokens stored in local storage without a clear reason, and logout that clears the app session but leaves the Keycloak session active. With a BFF, teams often leave the session cookie without the Secure and SameSite settings they need, or they expose the Keycloak admin hostname next to public frontend URLs. Test each environment with a second browser session to confirm that logout ends access. Build a short test list covering login, refresh after the access token expires, logout, and access after the Keycloak session ends.
Limits to confirm in your environment before you commit
A public client with PKCE and a backend for frontend depend on different Keycloak settings, libraries and infrastructure. Each card names one thing to verify in your own environment rather than assume, so the design you choose holds up in the release, browser and network you actually run.
Keycloak version and release notes
Confirm which Keycloak version you run and read its release notes for changes to client policies, logout handling and default settings. The 26.8 upgrade notes, for example, make backchannel logout token signature validation mandatory for external providers and change how login failures are stored. A client configuration that worked on an earlier minor release can behave differently after an upgrade, so check the notes before you pin a version and again before each upgrade.
Keycloak docsClient library and its Keycloak support
Identify the library your SPA or BFF uses, such as keycloak-js or a standard OpenID Connect client, and confirm it implements authorization code flow with PKCE and the token refresh behavior your design needs. Check that its configuration options match the Keycloak client settings documented for your chosen pattern. Libraries that were built around the deprecated adapters need a separate review before you rely on them.
Server administration guideThird-party cookie behavior in browsers
If your design uses an iframe for silent sign-in checks, test it in every browser your users run, with third-party cookies allowed, blocked and partitioned. Browsers change these rules independently of Keycloak, and a silent check that works today can fail after a browser update. Plan a fallback to a full redirect so users are not left in a loop when the check cannot read the session.
Reverse proxy path and hostname rules
Confirm how your reverse proxy routes public frontend URLs, the BFF's endpoints and the Keycloak admin console and Administration REST API. Keycloak's production guidance expects the admin surface on a different hostname or context path from public URLs. For a BFF, verify that the proxy forwards only the paths the BFF needs and that session cookies are scoped to the BFF host and not shared with other applications.
Production configuration guideSession store and logout requirements
A BFF keeps tokens and sessions on the server, so confirm where that session store lives, how it is replicated across instances, and how long sessions last compared with Keycloak's token lifetimes. Test whether a logout from the BFF also ends the Keycloak session, and whether a logout started elsewhere reaches your SPA. Keycloak single logout behavior depends on your client settings, so verify it end to end rather than from the configuration screen alone.
Your organization's security review rules
Find out what your security review requires for browser-based applications before you choose a pattern. Some teams require tokens never to reach the browser, which points to a BFF, while others accept a public client with PKCE if token lifetimes and redirect URI rules are tight. Ask your reviewers which evidence they need, such as client settings exports, token lifetime records and penetration test results, and collect it during the build.
How DeployOpen scopes and delivers a Keycloak SPA integration
DeployOpen plans, implements and hands over Keycloak for SPAs: public client with PKCE or backend for frontend inside your own infrastructure, with the client settings, session behavior and logout design written down before build starts. Each integration is agreed as a fixed-scope engagement so your security, identity and application teams know what they receive.
How we scope
- We confirm whether your SPA suits a public client with PKCE or a backend for frontend, based on your token handling and session requirements.
- We document the Keycloak realm, client settings, redirect URIs, web origins and token lifetimes that the chosen design needs.
- Scope, deliverables and timelines are agreed in writing before any work starts, and the written scope sets the quote.
How we build
- We configure the Keycloak client in your realm, including PKCE enforcement or confidential client settings for the backend component.
- We implement the login, token refresh, session and logout flows in your SPA or BFF code using the libraries Keycloak documents.
- We test redirect handling, expired sessions, token exposure in the browser and logout behavior before handover.
How we hand over
- You receive the client configuration, architecture notes, source changes and a runbook covering each Keycloak setting the integration depends on.
- We walk your engineers through the trade-offs so later changes to the client or session model are made deliberately.
- Deliverables stay in infrastructure you control, with the documentation your security reviewers need to assess the design.
How we support
- Ongoing support, Keycloak upgrade planning and continuous security testing are available as retainers.
- We review client settings again when Keycloak releases change defaults, so your SPA integration keeps its intended behavior.
- Retainer scope, response expectations and service terms are written down in the agreement before support begins.

