Why a single-page app needs authorization code with PKCE in Zitadel
A React, Angular or Vue front end that signs users in through self-hosted Zitadel should use the authorization code flow with PKCE, with the application registered as a user agent application in Zitadel. The reason is that the code runs entirely in the browser, where anything shipped to the client can be read by the user and by anyone who obtains the bundle. A single-page app is therefore a public client: it cannot keep a client secret confidential, so the OAuth 2.0 and OpenID Connect design replaces the secret with a per-login proof. Zitadel implements OpenID Connect and OAuth 2.0 as documented in its APIs introduction, and the flow you configure should match what that documentation describes for your Zitadel version.
PKCE (Proof Key for Code Exchange) adds a one-time secret generated by the app for each sign-in. The app creates a random code_verifier, sends a hashed code_challenge with the authorization request, and presents the original verifier when it exchanges the returned authorization code for tokens. An attacker who intercepts the code in the redirect cannot redeem it without the verifier. The app keeps the verifier in memory for the duration of the login, and the team should confirm that Zitadel enforces PKCE for this application type in the version they deploy, rather than assuming the default.
Choose this pattern when the browser app calls APIs directly with an access token, or when the app is a static bundle served from a CDN. Teams that need to keep tokens out of JavaScript entirely, or that must meet stricter session requirements, should evaluate a backend-for-frontend pattern, where a small server performs the code exchange and the browser holds only a secure session cookie. That choice changes the redirect, logout and token storage work covered in the rest of this page, so decide it before the front-end build starts.
How the authorization code with PKCE flow moves through the browser
The flow starts in the single-page app, which creates a random code verifier and derives a code challenge from it before redirecting the user to Zitadel's authorization endpoint. The authorization code returns to the registered redirect URI in the browser, and the app sends it back with the original verifier to the token endpoint. Check that the challenge method matches on both sides, that the redirect URI matches exactly, and that the access token only travels to the API it was issued for.
Authorization code with PKCE, showing where the browser, app and Zitadel exchange messages.
Choosing the application type and token design for your front end
A pure single-page app runs entirely in the browser, so it cannot keep a client secret confidential. The user agent application type in Zitadel is designed for this case: the app uses the authorization code flow with PKCE, generates a one-time code verifier for each login, and never holds a client secret. This keeps the setup simple and lets the front end talk directly to Zitadel for sign-in and token refresh. The trade-off is that every token the app receives is reachable by JavaScript running in the page, so cross-site scripting becomes the main risk to manage.
- No client secret: the application type must be set so that PKCE is required and no secret is issued to the browser.
- Exact redirect URIs: register each callback URL per environment and avoid wildcards, since they widen where authorization codes can be sent.
- Post-logout URIs: register the return addresses for sign-out separately from login redirects.
- Refresh token behavior: confirm whether refresh tokens are issued to this application type and for how long they remain valid before you rely on silent renew.
- Scope of tokens: confirm which scopes and audiences the console adds to the access token for your API.
Before you approve this design, check each of these settings in the Zitadel console for your application and record the values in your configuration review.
A backend-for-frontend (BFF) keeps tokens out of the browser. A small server component that you run alongside the app performs the OIDC flow as a confidential client, holds the tokens and a client secret server-side, and gives the browser only an HTTP-only session cookie. The browser never sees an access or refresh token, so a script injected into the page cannot read them directly. The cost is an extra service to build, deploy, scale and patch, plus cookie and CSRF handling that your team must get right.
- Confidential client: create a web application in Zitadel with a client secret or private key authentication, stored in your secret manager and not in the front-end bundle.
- Session cookies: confirm the cookie flags you will set, including Secure, HttpOnly and SameSite, and how sessions expire.
- Cross-site request forgery: plan a CSRF defense for state-changing requests, because cookies are sent automatically.
- Operational load: the BFF becomes a path for every API call from the front end, so include its capacity and availability in your design.
- Ownership: name the team that owns the BFF and its upgrades, since it becomes part of your security boundary.
Before you choose this option, confirm with your application team that the BFF can run in the same domain as the app and that your API gateway can accept the session-based calls.
Whichever front-end pattern you pick, the access token type affects what a browser holds. A JWT is self-contained and can be validated offline by any API using Zitadel's published keys, so the token carries claims such as the subject, audience and roles. An opaque token is a random reference that the API must send to introspection to learn whether it is still valid. For a browser-held token, a JWT exposes more readable claims if it leaks, while an opaque token reveals little but adds a call to Zitadel for each validation unless the API caches results. Your choice should match your revocation needs and your API latency budget.
- Claim exposure: a JWT in the browser discloses its payload to anyone who reads it, so review which claims and roles it contains.
- Revocation: confirm how quickly a revoked session stops working with each token type in your configuration.
- Validation path: decide whether APIs will validate JWTs locally or use introspection for opaque tokens.
- Lifetime: set access token lifetimes in the application settings and match them to silent renew.
- Key rotation: confirm how signing keys are rotated and how relying parties refresh their key sets.
In the Zitadel console, check the token type and lifetime settings on the application and confirm them with the API team before go-live.
Configuration options and when each fits
This table compares the Zitadel application settings and token handling choices that matter for a single-page app using PKCE, and the situation each one suits. Confirm exact labels and defaults in the Zitadel version you deploy, because the console layout changes between releases. The main takeaway is that the application type and redirect settings are hard to change later, so decide them before the first environment is built.
| Setting or choice | What it controls | When it fits |
|---|---|---|
| Application type: user agent | Makes the app a public client that uses authorization code with PKCE and no client secret, so the code verifier replaces a secret held in the browser. | Any browser-based React, Angular or Vue app. Do not use a confidential web application type or embed a client secret in the bundle. |
| Redirect URIs | The exact callback addresses Zitadel may return the authorization code to. Matching is strict, so each dev, staging and production origin needs its own entry. | Add one entry per environment and avoid wildcards unless your version documents them. Confirm the exact matching rules in your Zitadel release. |
| Post-logout URIs | Addresses Zitadel may redirect to after the session ends at the identity provider. | Use a dedicated signed-out page per app. Missing entries usually cause a redirect error at sign-out, not at sign-in. |
| Scopes requested by the app | Which claims the ID token and userinfo return, such as openid, profile, email, and offline_access when refresh tokens are wanted. | Request the minimum set the UI needs. Add offline_access only if you choose refresh-token renewal and confirm it is granted for this application. |
| Roles in tokens (project settings) | Whether project roles are returned in the ID token or userinfo, depending on project and application settings. | Use when the front end must show or hide features by role. Authorization decisions belong in the API, so do not treat these claims as enforcement. |
| Silent renew via refresh tokens | The app exchanges a refresh token for new access tokens in the background, with rotation handled by the authorization server. | Preferred when the browser can keep the refresh token in memory and your session length policy allows it. Confirm rotation and expiry settings for your version. |
| Silent renew via hidden iframe | The app loads the authorize endpoint in a hidden frame with prompt=none to obtain a new token without a refresh token. | Suits deployments where refresh tokens are not wanted. Third-party cookie restrictions in current browsers can block it, so test every target browser. |
| Token storage in the browser | Where access and refresh tokens live, such as memory, session storage or local storage, which determines exposure to script injection. | Keep tokens in memory where the library allows it. Local storage survives reloads but is readable by any script on the page, so pair it with a strict content security policy. |
Setting up the SPA client in Zitadel step by step
This sequence takes a single-page app from no Zitadel configuration to a working PKCE sign-in, sign-out and silent token refresh, with each environment's URIs set exactly. The output is an application client that your team has tested end to end in every environment it will run in.
Create or select the project
Start in the Zitadel console and open the organization that will own the application. Create a new project for the SPA, or select an existing one if the SPA belongs to a product that already has an API and roles. Keep the project in the organization where your users live, since projects hold the applications, roles and grants. Done when the project appears in the organization's project list and you can open its settings page without errors.
Register the user agent application with PKCE
Inside the project, add an application and choose the user agent type, which is the OIDC application type for browser-based apps. Select the authorization code flow and require PKCE, so the browser sends a code challenge and no client secret is stored in the front end. Record the generated client ID, which your app will use. Done when the application is listed with the PKCE setting on and a client ID is shown.
Set exact redirect and post-logout URIs per environment
Enter the callback URI your app uses after sign-in and the URI it returns to after sign-out, once for local development, once for staging and once for production. Match scheme, host, port and path exactly, because wildcard or partial matches are a common source of open redirect risk and of sign-in failures. Keep environments in separate application configurations or clearly separated URI lists. Done when each environment's URIs are written down in your configuration inventory and a mismatched test URI is rejected by the login page.
Configure scopes and token settings
Decide which scopes the SPA requests, typically the standard OpenID Connect scopes for identity plus any scope needed to receive project roles or API audiences. Confirm the token settings for the application, including whether the access token is opaque or a JWT, and check the options that add roles or user information to tokens. Ask your Zitadel contact to confirm which options your version exposes. Done when a test sign-in returns an ID token and an access token whose audience and claims match what the SPA expects.
Add the OIDC library to the app
In the React, Angular or Vue project, add a maintained OpenID Connect client library that supports authorization code with PKCE, and configure it with the Zitadel issuer URL, the client ID and the redirect and post-logout URIs for the current environment. Keep these values in environment configuration rather than in source code. Done when the app builds and the library reports the expected issuer and client ID on startup.
Wire the login, callback and logout routes
Create a route that starts sign-in, a callback route that completes the code exchange, and a logout route that ends the session and returns to the post-logout URI. Handle the case where the user opens the callback URL directly without a pending login, and show an error instead of a blank page. Decide where tokens are held in memory and how silent renewal is triggered, and document that choice for your security review. Done when clicking sign-in redirects to Zitadel, returns to the callback, and lands on the protected page.
Verify sign-in, sign-out and token refresh
Test the full cycle in each environment: sign in with a test user, confirm the protected page loads, refresh the page and confirm the session persists, wait for the token to approach expiry and confirm a silent renew succeeds, then sign out and confirm the session cannot be reused. Also try a sign-in with a redirect URI that is not registered and confirm Zitadel refuses it. Done when every check passes in each environment and the results are recorded for your release sign-off.
Where tokens should live in the browser and why it matters
Keeping access and refresh tokens in memory, rather than in sessionStorage or localStorage, gives the smallest window for theft, because any script running on the page can read whatever the application stores in the browser's web storage. Both localStorage and sessionStorage are readable by any script in the same origin, so a single cross-site scripting flaw in a React, Angular or Vue component, or in a third-party script the page loads, can copy tokens and use them from another machine. localStorage adds persistence across tabs and restarts, which lengthens the period an attacker can use a stolen token. Memory storage is lost on reload, so the trade-off is convenience against exposure. Choose deliberately and document the choice in your threat model.
After a full page reload, a token held only in memory is gone, so the app must re-establish it. With PKCE, the usual path is a silent authorization request in a hidden iframe or a fresh redirect, which depends on the Zitadel session cookie still being valid in the browser. Test this explicitly: reload the page, let the access token expire, open a second tab, and confirm the app recovers without a visible sign-in prompt. Also test what happens when third-party cookies are blocked, because silent renew via iframe can fail in that case and the app must fall back to a redirect rather than leave the user on a broken screen. Confirm the behavior of the chosen Zitadel application settings and your client library with your own environment before you promise users a seamless experience.
Ask for a security review of the chosen storage model and the content security policy together, since the policy is the main control that limits what an injected script can do. The review should confirm that the policy restricts script sources, blocks inline script where the framework allows it, and avoids unreviewed third-party scripts on pages that handle tokens. It should also check for dangerous DOM sinks in the codebase and dependency audit results for the front-end toolchain. Record the outcome as evidence: the storage decision, the policy text, and the test results for reload and renew. Keep the review with your release artifacts so that the next change to a script source is checked against it.
Security and operational considerations for SPA sessions
A single-page app runs entirely in the browser, so its security depends on settings outside the app code: the redirect URIs Zitadel accepts, the scripts the page can run, the origins allowed to call APIs, and how sessions end. The cards below cover the checks to complete before go-live and the signals to watch after it.
Exact redirect URI matching
Register each full callback and post-logout URI exactly as the app uses it, including scheme, host, port and path. Wildcards in redirect URIs let an attacker point an authorization response at a page they control, so avoid them in production. Use separate client registrations for each environment so a staging URI never reaches the production client. Check the final list during every release, because a forgotten localhost entry is a common leftover.
Zitadel APIs docsCross-site scripting as the main theft path
A browser app keeps tokens where its JavaScript can read them, so any injected script can take them. Treat XSS prevention as the primary control: avoid rendering untrusted HTML, use framework escaping, and restrict script sources with a strict Content Security Policy. Keep third-party scripts to a reviewed minimum. Ask your security team to test the app for DOM-based XSS, since bundled dependencies are a frequent entry point.
CORS settings on Zitadel and APIs
The SPA calls Zitadel endpoints and your APIs from its own origin, so each service must allow only the origins that need access. Permit the exact production origin rather than a broad pattern, and confirm that preflight responses allow only the methods and headers the app uses. Review CORS on every API the SPA calls, since each one is configured separately from Zitadel. Test with a browser from an unapproved origin to confirm the block.
Logout across tabs
A user who signs out in one tab can leave another tab holding a valid session in memory. Clear tokens from storage and memory in every tab, using a storage event or broadcast channel to propagate the sign-out. Redirect to the post-logout URI registered in Zitadel so the identity session also ends. Test sign-out with two tabs open, then confirm that a reload in the second tab shows the login page.
Key and client configuration per environment
Each environment needs its own Zitadel client ID, redirect and post-logout URIs, allowed origins and API audience. Store these values in environment-specific build or runtime configuration, not in shared code, and document who may change them. Review the Zitadel client settings after each environment change to confirm that the production client has no development entries. Keep an inventory of clients so retired applications are disabled rather than left active.
Monitoring failed callbacks
Failed logins often show up first as callbacks that never complete, such as a state mismatch, a rejected redirect URI or a token request error. Log these events in the app with the request correlation data and alert when the rate rises after a deployment. Review Zitadel audit and login events for repeated failures from one source. Rising callback failures after a release usually point to a changed URI or origin.
Questions teams ask before securing a single-page app with Zitadel
What drives the cost and effort of an SPA integration with Zitadel?
The main drivers are how many applications and environments you run, how many identity providers and login flows you need, and how much of your current authentication code must change. A single React or Vue front end with one Zitadel project, one set of redirect URIs and a staging and production pair is a small job. Costs rise when you add multiple SPAs, per-tenant branding, custom claims for roles, or a rewrite of an existing login flow. Ask any partner for a quote that lists the applications in scope, the environments, the identity providers to connect, and whether token handling changes in your APIs. Your own engineering time is a recurring cost to plan for, not only the one-time build.
How long does it take to secure a single-page app with Zitadel?
Duration depends on scope rather than on the framework. The work is shorter when Zitadel is already running, the application is a single front end, and your team can register the client, set redirect and post-logout URIs and wire the OIDC library in one pass. It takes longer when Zitadel itself must be deployed, when several SPAs share a login experience, or when silent renew, logout and role claims must be tested across browsers. Ask for a written plan with milestones for configuration, integration, testing and handover, and confirm which items depend on your infrastructure or change approvals.
What does the work need from our internal team?
You need an owner for the Zitadel instance, someone who can approve the application registration and its redirect URIs, and a front-end engineer who knows the framework's routing and build pipeline. Security or architecture review is needed to agree on token storage and session lifetime. Your team also provides test accounts, the staging and production domains, and access to the pipelines where the app is deployed. Expect review time from these people throughout the work, not only at the start.
Can an internal team implement this alone?
Yes, a team with front-end and identity experience can implement PKCE with the authorization code flow without an outside partner. The parts that most often need a second pair of eyes are the redirect URI allowlist, the post-logout flow, the choice of what the browser stores, and whether silent renew works when third-party cookies are blocked. Those are checks you can do internally, but they should be reviewed against your own threat model. If the team has not built OIDC clients before, budget time for learning and for a security test of the finished flow.
Do we need a backend-for-frontend with Zitadel?
A backend-for-frontend is not required by Zitadel. A pure SPA can use the authorization code flow with PKCE directly in the browser. A BFF keeps tokens out of JavaScript, which lowers exposure to cross-site scripting, and it suits applications that handle sensitive data or must meet strict internal controls. It adds a server to deploy, scale and monitor, and it changes session handling and CORS. Decide this during design, based on the data the app handles and your organization's token-storage policy, and document the decision so auditors and developers can follow it.
What changes for an existing app moving from another identity provider?
The redirect flow, client registration, token validation and logout logic change, while your application's business logic usually does not. You will register a new client in Zitadel, update the issuer and client ID settings, and replace the old SDK or login callback. User accounts need a migration plan: Zitadel publishes migration guides for several source systems, and approaches such as just-in-time migration can move users on first sign-in. Plan a period when both providers run, test sessions that span the cutover, and confirm how existing refresh tokens and sessions are invalidated.
Which Zitadel configuration mistakes cause the most failures?
The most common failures come from mismatched redirect URIs, missing or incorrect post-logout URIs, and tokens issued for a different audience than the API expects. Silent renew often breaks when the identity provider's domain is on a different site than the app and browsers block the iframe or cookies. Check each environment separately, confirm that the issuer URL matches the deployed domain exactly, and test logout from every entry point. Ask your implementation team to document these checks as a test plan you can rerun after upgrades.
How DeployOpen scopes an SPA integration in your environment
DeployOpen agrees the scope of a single-page app integration in writing before any configuration starts, and most engagements are fixed-scope, so the deliverables and acceptance checks are known to both sides up front. The scoping work begins with an inventory of every front end and environment that will use Zitadel: each React, Angular or Vue application, its development, staging and production hosts, the Zitadel instance and organization it will sign users into, and the APIs it calls with access tokens. Teams often find that one SPA is deployed under several hostnames, or that a preview environment reuses a production client, and both need to be settled before redirect rules are written.
From that inventory, DeployOpen drafts a redirect and post-logout URI map that lists, for each application and environment, the exact redirect URIs, post-logout URIs and allowed origins. The same review covers the token and storage design: whether the application type is user agent with PKCE, where tokens live in the browser, how silent renew is triggered and what happens when a refresh fails. Each decision is recorded with its reason so a security team can review it without reverse engineering the code. Ask for the map and the design review as named documents in the quote, not as informal notes.
Testing and handover close the scope. DeployOpen tests sign-in, silent renew and logout in each environment against the agreed URI map, including expired sessions and a user who signs out in another tab. The handover documentation covers the configuration as built, the owners of each client, the procedure for adding a new environment and the checks to repeat after a change. Ongoing support, upgrades and continuous testing are available as a retainer, which is useful when front ends change often. Confirm with DeployOpen which of these items are included in the fixed scope and which would be priced as a retainer or change request.
How DeployOpen delivers and supports Zitadel SPA security
DeployOpen plans, implements, documents and supports self-hosted open-source platforms inside your own infrastructure. For a single-page app on Zitadel, that means fixing the OIDC client configuration, the PKCE flow, redirect and logout URIs and token handling in writing before any code is changed, then verifying the result in your environment.
How we scope
- Inventory the SPA frameworks, hosting domains, environments and users that the Zitadel application must cover.
- Agree in writing which Zitadel instance, organization and project the application belongs to, and who administers them.
- Record the redirect URIs, post-logout URIs, token storage approach and silent renew requirements as part of the written scope.
How we build
- Configure the user agent application type with authorization code and PKCE, without a client secret in browser code.
- Wire the chosen OIDC library into the React, Angular or Vue app, including login, callback, logout and silent renew paths.
- Test sign-in, token expiry, refresh behavior and logout against each target browser and environment before handover.
How we hand over
- Deliver configuration records listing client settings, URIs, scopes, token lifetimes and the role of each Zitadel object.
- Document the token storage decision, the reasons for it and the residual browser risks your security team should review.
- Walk your engineers through the setup and leave runbooks for adding environments, rotating settings and troubleshooting login failures.
How we support
- Ongoing support, Zitadel upgrades and continuous testing are available as retainers after the initial engagement.
- Retesting of the SPA integration after Zitadel upgrades or frontend framework changes can be included in a retainer scope.
- Ask for the support boundaries, response arrangements and upgrade responsibilities in the written quote before work starts.

