The Keycloak Admin API from TypeScript, without the surprises
Описание и применение
Keycloak‑API‑TS устраняет ограничения официального клиента Keycloak, обеспечивая совместимость с CommonJS/ESM, возвращение ошибок как значений, контекстный выбор realm, автоматическое обновление токенов и полное покрытие 415 операций API с типовой безопасностью.
Задача
Automating Keycloak from Node.js hits friction points: ESM-only client, HTTP errors as exceptions, mutable global realm, token renewal issues, and incomplete API coverage.
Результат
keycloak-api-ts eliminates ESM-only constraints, replaces exception‑based errors with discriminated unions, supports per‑call realm context, auto‑refreshes tokens, retries on 401, and offers full 100% API coverage with type safety.
Рабочий процесс
- npm install keycloak-api-ts
- import KeycloakAPI from 'keycloak-api-ts'
- const api = new KeycloakAPI({baseUrl:'https://sso.example.com',credentials:{grantType:'client_credentials',clientId:'admin-service',clientSecret:process.env.KEYCLOAK_CLIENT_SECRET}})
- const created = await api.users.create('acme',{username:'jdoe',enabled:true})
- if (created.success) { console.log('new user id:',created.data) } else if (created.status===409) { console.log('user already exists') } else { console.error(created.status,created.error) }
Доказательства
The package is "type": "module" with no CommonJS build.
HTTP errors are thrown. A missing user (404) or a duplicate username (409) isn't exceptional; it's business logic.
The default realm is global mutable state.
Tokens renew only with a refresh token.
By my count on 26.8.1, the official client covers about 340 of the 415 operations in the OpenAPI spec (≈82%).
keycloak-api-ts ships both builds, so require and import work on any Node 20+, Jest in CommonJS mode included, without relying on require(esm).
Errors as values. Every call resolves to { success, status, data | error }, a discriminated union.
- Дата записи: 2026-10-16T17:41:49.594Z