@lgibbs/keycloak-auth-ts
v1.1.1
Published
Pragmatic Keycloak wrapper with SSR-safe init, single-flight refresh, fetchWithAuth, role helpers, and tiny pub/sub.
Downloads
11
Maintainers
Readme
@lgibbs/keycloak-auth-ts
A pragmatic TypeScript Keycloak wrapper with:
- SSR-safe init
- Queued / single-flight token refresh
fetchWithAuthwith 401 retry- Role helpers
- User profile convenience
- Tiny pub/sub for UI state
- Safe teardown
This wrapper keeps your app code tiny while handling the annoying parts of the Keycloak JS adapter.
Installation
npm install @lgibbs/keycloak-auth-ts keycloak-jsNote:
keycloak-jsis a peer dependency, so you must install it separately.
Quick Start
import { initAuth, fetchWithAuth, getAuthState, subscribe } from "@lgibbs/keycloak-auth-ts";
// Initialize once at app startup
await initAuth({
url: "http://localhost:8180",
realm: "myrealm",
clientId: "my-client",
onLoad: "check-sso",
silentCheckUri: `${window.origin}/silent-check.html`
});
// Subscribe to auth state changes
const unsubscribe = subscribe((state) => {
console.log("Auth state:", state);
});
// Fetch API with auth header (auto-refreshes token, retries once on 401)
const response = await fetchWithAuth("/api/data");
const data = await response.json();
console.log(data);
// Snapshot of current state (cheap read)
const state = getAuthState();
console.log("Current user:", state.profile?.username);
// Unsubscribe later if desired
unsubscribe();API
initAuth(config: InitAuthConfig): Promise<void>
Initialize Keycloak and wire up refresh hooks. SSR-safe and idempotent.
getToken(opts?: { minValidity?: number }): Promise<string | null>
Retrieve a fresh token, ensuring at least minValidity seconds remain.
fetchWithAuth(input, init?, opts?): Promise<Response>
Fetch with Authorization header automatically. Retries once on 401.
subscribe(cb: (state: AuthState) => void): () => void
Subscribe to auth state changes. Returns an unsubscribe function.
getAuthState(): AuthState
Read-only snapshot of current auth state.
hasRealmRole(role: string): boolean
Check if user has a realm-level role.
hasResourceRole(role: string, clientId?: string): boolean
Check if user has a client/resource role.
getAuthHeader(): Promise<string | null>
Convenience function to return "Bearer <token>" or null.
getUserInfo(): Promise<object | null>
Fetch OIDC userinfo from Keycloak.
openAccount(): Promise<void>
Open Keycloak account management page.
login(options?): Promise<void> / logout(options?): Promise<void>
Login and logout helpers.
teardown(): void
Reset internal state and subscribers (e.g., in tests or app reboot).
withKeycloak(fn: (kc: KeycloakInstance) => T): T
Escape hatch to run a function with the raw Keycloak instance.
Development
Build locally:
npm install
npm run buildTest pack:
npm packLicense
MIT © Lauren Gibbs
