npm package: @kiavi/kiavi-browser
Description: Kiavi browser authentication client
Latest version: 0.2.2

# @kiavi/kiavi-browser

Browser client for apps that sign users in through a Kiavi-hosted auth server.

## Install

```bash
pnpm add @kiavi/kiavi-browser
```

## Usage

```ts
import { KiaviClient } from '@kiavi/kiavi-browser'

const auth = new KiaviClient('https://auth.your-domain.com')

// Guard a route — if there's no session, the user is redirected to login.
const { session } = await auth.requireSession()

// Attach the token to API calls.
const token = await auth.getAccessToken()
fetch('/api/things', { headers: { Authorization: `Bearer ${token}` } })

// Sign out.
auth.signOut()
```

That's the whole thing. `requireSession()` at the top of your app and `getAccessToken()` on
every API call is enough for most apps.

## Options

```ts
new KiaviClient('https://auth.your-domain.com', {
  locale: 'en', // adds ?lang=en to hosted pages; will auto-detect otherwise
  debug: true, // structured console logs; pass a function to route them elsewhere
})
```

## Reference

### Methods

- `requireSession()` — ensures a session exists. Returns `{ session, returnTo }`. If there's
  no session, redirects to the hosted login page and never resolves.
- `getAccessToken()` — returns a valid JWT, refreshing silently if the current one is near or
  past expiry. Throws `KiaviSessionExpiredError` if a new token can't be obtained.
- `checkSession()` — synchronous read of the in-memory session. Returns `null` if none.
- `authenticate()` — redirect to the hosted login page immediately.
- `signOut()` — clears state and redirects to the hosted signout page.
- `getAuthPolicy()` — returns `'passkey_required'` or `'passkey_preferred'`, for UI that
  adapts to the configured policy.
- `resendVerificationEmail({ email, callbackURL? })` — unauthenticated. Asks the auth server
  to send another verification email. Throws `KiaviAuthError` on failure (`code` includes
  `'rate_limited'`, in which case `retryAfterSeconds` is populated).
- `changeEmail({ newEmail, callbackURL? })` — requires an active session. Asks the auth server
  to change the signed-in user's email. If the current email is verified, a confirmation link
  is sent to the **current** address and the change only takes effect once the user clicks it.
  Throws `KiaviAuthError` on failure.
- `setLocale(locale)` / `setDebugLogger(debug)` — update configuration at runtime.

### Types

`KiaviClient`, `KiaviSession`, `KiaviSessionUser`, `KiaviSessionResult`, `KiaviClientOptions`,
`KiaviAuthenticateOptions`, `KiaviAuthPolicy`, `KiaviSessionExpiredError`, `KiaviAuthError`,
`KiaviAuthErrorCode`, `KiaviResendVerificationEmailOptions`, `KiaviChangeEmailOptions`,
`KiaviDebugLogger`, `KiaviDebugLogEntry`.

### How it works (if you're curious)

The client talks to the Kiavi auth server at `authBaseUrl`. On first use it fetches
`/.well-known/kiavi-auth.json` to discover the endpoints and capabilities of that server,
then transparently uses whichever flow the server is configured for — you don't need to pick
one.

Session refresh happens silently: a timer fires ~30 seconds before the current token expires
and mints a new one, and `getAccessToken()` also refreshes on demand if the in-memory token
has expired. If all of that fails, the next call to `requireSession()` sends the user back
through login.

The server-side counterpart that verifies the JWTs this client produces is
[`@kiavi/kiavi-js`](../kiavi-js/README.md).

This package is browser-only — it depends on `window`, `localStorage`, and `fetch`.