Migrating from Keycloak-js
Polyfilling keycloak-js with oidc-spa
If you're using keycloak-js in an existing codebase, you can migrate to oidc-spa without a painful rewrite.
oidc-spa ships a keycloak-js polyfill. It’s a literal drop-in replacement.
Enable Security Features
If you're moving to oidc-spa, you likely want to enable DPoP and other security features.
Pick the setup option that best fits your project:
If you're in a Vite project, the recommended approach is to use oidc-spa’s Vite plugin.
import { defineConfig } from "vite";
import { oidcSpa } from "oidc-spa/vite-plugin";
export default defineConfig({
plugins: [
// ...
oidcSpa({
// See: https://docs.oidc-spa.dev/v/v10/security-features/browser-runtime-freeze
browserRuntimeFreeze: {
enabled: true
//exclude: [ "fetch", "XMLHttpRequest"]
},
// See: https://docs.oidc-spa.dev/v/v10/security-features/dpop
DPoP: {
enabled: true,
mode: "auto"
}
})
]
});Pick this approach if:
You're not in a Vite project (or want more control) and
Your app has a single client entrypoint.
Let's assume your app entrypoint is src/main.ts.
First, rename it to src/main.lazy.ts.
Then create a new src/main.ts file:
If you’re not using Vite and you can’t edit your app’s entry file, run oidcEarlyInit() in the same module where you call new Keycloak().
Note: this option downgrades the security posture of your app compared to the two other approaches. It can also conflict with some client-side routing libraries.
You can enable keycloak.init({ enableLogging: true }) to see a console report for the security features.
(OPTIONAL) Display a Warning Before Auto Logout
oidc-spa implements auto logout by respecting the idle session lifetime you configured in Keycloak.
To warn the user when they are about to be logged out due to inactivity, you can show an overlay like: “Are you still here? Your session will expire in 30…29…”
Get the underlying oidc-spa core object like this:
import { Keycloak } from "oidc-spa/keycloak-js";
const keycloak = new Keycloak({ ... });
await keycloak.init({ ... });
// Can call this only after keycloak.init() has resolved.
const oidc = keycloak.getOidc();Then implement the overlay as described here: Displaying a Warning Before Auto Logout.
You're Done 🎉
If you run into some issue do not hesitate to reach out on Discord.
Last updated
Was this helpful?