Add Keycloak login to a Vue app
Add Keycloak login to a Vue 3 single-page app built with Vite, using oidc-client-ts with the authorization code flow and PKCE.
A Vue single-page app signs users in with the authorization code flow and PKCE through oidc-client-ts. It runs entirely in the browser and cannot keep a secret, so the client is public.
Written against oidc-client-ts 3.5, Vue 3.5, Vite 8.3, vue-tsc 3.3, jose 6.2 and Keycloak 26.8, checked on 25 November 2026.
Replace auth.example.com with your RealmDeploy hostname and acme with your realm.
Create the client in Keycloak
Open Clients, choose Create client, and use these values:
| Setting | Value |
|---|---|
| Client type | OpenID Connect |
| Client ID | vue-app |
| Client authentication | Off |
| Authentication flow | Standard flow. Turn Direct access grants off. |
| PKCE Method | S256 |
| Root URL | http://localhost:5173 |
| Valid redirect URIs | http://localhost:5173/ |
| Valid post logout redirect URIs | http://localhost:5173/ |
| Web origins | http://localhost:5173 |
Choose Save. A public client has no Credentials tab and no secret.
Web origins matters here: the browser calls Keycloak's token endpoint from JavaScript, and Keycloak answers that cross-origin request only for the origins listed. The Web origins helper explains the values.
For production, add your app's real URLs next to the local ones, for example https://app.example.com/ and the origin https://app.example.com. Keycloak compares redirect URIs exactly.
Environment variables
VITE_OIDC_AUTHORITY=https://auth.example.com/realms/acme
VITE_OIDC_CLIENT_ID=vue-app
VITE_API_URL=http://localhost:3000Vite puts every VITE_ variable into the JavaScript bundle, so put only public values here. Declare their types in a new file:
/// <reference types="vite/client" />
interface ImportMetaEnv {
readonly VITE_OIDC_AUTHORITY: string
readonly VITE_OIDC_CLIENT_ID: string
readonly VITE_API_URL: string
}Install
npm create vite@latest vue-app -- --template vue-ts
cd vue-app
npm install oidc-client-tsAdd login
One UserManager holds the settings and the signed-in user. oidc-client-ts uses the authorization code flow and PKCE by default, so neither needs a setting.
import { ref } from "vue"
import { UserManager, type User } from "oidc-client-ts"
export const userManager = new UserManager({
authority: import.meta.env.VITE_OIDC_AUTHORITY,
client_id: import.meta.env.VITE_OIDC_CLIENT_ID,
redirect_uri: `${window.location.origin}/`,
post_logout_redirect_uri: `${window.location.origin}/`,
scope: "openid profile email",
})
// The signed-in user, or null. Components read this ref.
export const user = ref<User | null>(null)
userManager.events.addUserLoaded((loaded) => {
user.value = loaded
})
userManager.events.addUserUnloaded(() => {
user.value = null
})
// Call once before mounting the app.
export async function initAuth() {
const params = new URLSearchParams(window.location.search)
if (params.has("state") && (params.has("code") || params.has("error"))) {
// Back from Keycloak: exchange the code for tokens (PKCE),
// then remove ?code=...&state=... from the address bar.
await userManager.signinCallback()
window.history.replaceState({}, document.title, window.location.pathname)
}
const current = await userManager.getUser()
user.value = current && !current.expired ? current : null
}
export const login = () => userManager.signinRedirect()
export const logout = () => userManager.signoutRedirect()import { createApp } from "vue"
import App from "./App.vue"
import { initAuth } from "./auth"
initAuth()
.catch((error) => console.error("Sign-in failed", error))
.finally(() => createApp(App).mount("#app"))<script setup lang="ts">
import { user, login, logout } from "./auth"
async function callApi() {
const response = await fetch(`${import.meta.env.VITE_API_URL}/api/me`, {
headers: { Authorization: `Bearer ${user.value?.access_token}` },
})
console.log(await response.json())
}
</script>
<template>
<main v-if="user">
<p>Signed in as {{ user.profile.preferred_username }}</p>
<button @click="callApi">Call API</button>
<button @click="logout">Log out</button>
</main>
<button v-else @click="login">Log in</button>
</template>Run npm run dev, open http://localhost:5173 and sign in with a user of your realm. The app mounts only after initAuth has finished, so components never see a half-done login.
oidc-client-ts keeps the tokens in the browser's sessionStorage by default, which any script on the page can read. That is the trade-off of a pure single-page app; for apps that handle sensitive data, put a backend-for-frontend in front of it that keeps the tokens on the server and gives the browser only a session cookie, as in the Express guide.
Protect an API
The app sends the access token to your API as Authorization: Bearer <access token>. The API must check the token's signature, issuer and audience before it trusts it.
Keycloak does not put your API in the access token's aud claim by default, so add an Audience mapper to this client:
- Open Clients, choose
vue-app, and open its Client scopes tab. - Choose
vue-app-dedicated. - Choose Configure a new mapper (or Add mapper → By configuration), then Audience.
- Enter a Name, set Included Custom Audience to
orders-api, keep Add to access token on, and choose Save.
Sign in again to get a token with the new audience. On the API side, a Node.js check with jose looks like this (set OIDC_ISSUER to https://auth.example.com/realms/acme and API_AUDIENCE to orders-api):
import { createRemoteJWKSet, jwtVerify, type JWTPayload } from "jose"
const issuer = process.env.OIDC_ISSUER!
const audience = process.env.API_AUDIENCE
// The realm's public signing keys. jose caches them and fetches
// them again when a token arrives with a key ID it has not seen.
const jwks = createRemoteJWKSet(new URL(`${issuer}/protocol/openid-connect/certs`))
export async function verifyBearerToken(request: Request): Promise<JWTPayload | null> {
// jose skips the audience check when audience is undefined, so fail loudly.
if (!audience) throw new Error("API_AUDIENCE is not set")
const header = request.headers.get("authorization")
if (!header?.startsWith("Bearer ")) return null
try {
const { payload } = await jwtVerify(header.slice("Bearer ".length), jwks, {
issuer,
audience,
})
return payload
} catch {
return null
}
}It takes a standard Request, so it fits any runtime with the Fetch API. For an Express middleware, see Protect an API in the Express guide. Your API on another origin must also answer CORS requests from http://localhost:5173; the CORS checker shows what it sends back.
Log out
userManager.signoutRedirect() removes the stored user, then sends the browser to the realm's end-session endpoint with the ID token as id_token_hint and post_logout_redirect_uri from the settings. Keycloak ends its session without asking and sends the user back to http://localhost:5173/, which must be listed in Valid post logout redirect URIs.
userManager.removeUser() only forgets the tokens in the browser. The Keycloak session stays, and the next login goes straight through without a password.
Common errors
| Error | Cause | Fix |
|---|---|---|
Keycloak shows Invalid parameter: redirect_uri | http://localhost:5173/ is not in Valid redirect URIs, or differs in scheme, port or trailing slash. | Add it exactly. Compare both with the redirect URI matcher. |
| Browser console: the token request was blocked by CORS policy | The app's origin is not in Web origins. | Add http://localhost:5173, without a path or trailing slash. |
No matching state found in storage | The login started on one origin and came back on another, for example 127.0.0.1 and localhost, or the callback URL was reloaded. | Use one origin everywhere and start the login again. |
Token request fails with unauthorized_client | Client authentication is on, so Keycloak expects a secret. | Turn Client authentication off for this client. |
Keycloak shows Invalid redirect uri after Log out | post_logout_redirect_uri is not in Valid post logout redirect URIs. | Add http://localhost:5173/. |
API returns 401, jose says unexpected "aud" claim value | The access token has no orders-api audience. | Add the Audience mapper above and sign in again. |
Decode a token with the JWT decoder to see its iss, aud and expiry. For other OAuth error codes, see the OAuth error lookup.
FAQ
Does the token renew itself?
Yes. automaticSilentRenew is on by default in oidc-client-ts, and it uses the refresh token Keycloak issues when the access token is about to expire. The addUserLoaded handler then updates user with the new tokens.
How do I protect a route with Vue Router?
Add a global beforeEach guard that calls login() when user.value is null for routes that need a signed-in user. This only decides what the browser shows; the API must still check every token.
Can I use a separate /callback route instead of /?
Yes. Set redirect_uri to ${window.location.origin}/callback, add http://localhost:5173/callback to Valid redirect URIs, and call signinCallback() when the app loads on that path.
Sources
- https://github.com/authts/oidc-client-ts
- https://authts.github.io/oidc-client-ts/
- https://authts.github.io/oidc-client-ts/interfaces/UserManagerSettings.html
- https://vite.dev/guide/env-and-mode
- https://vuejs.org/guide/scaling-up/tooling
- https://github.com/panva/jose
- https://www.keycloak.org/docs/latest/server_admin/#audience-support
- https://www.keycloak.org/docs/latest/server_admin/#_oidc-logout
- https://datatracker.ietf.org/doc/html/draft-ietf-oauth-browser-based-apps
Add Keycloak login to an Angular app
Add Keycloak login to an Angular 22 app with angular-oauth2-oidc, the standalone provideOAuthClient API, and the code flow with PKCE.
Add Keycloak login to a Node.js Express app
Sign users in to an Express app with Keycloak using openid-client v6 and sessions, protect API routes with jose, and log out of Keycloak.