---
title: "@xid-kit/backend"
description: "Networkless JWT verification, request authentication, and webhook signature validation for edge and server runtimes."
locale: "en"
---

> Documentation Index
> Fetch the locale documentation index at: https://xid.dev/en/llms.txt
> Use this file to discover all available pages before exploring further.

# @xid-kit/backend

## Runtime support

- Cloudflare Workers (primary target)
- Vercel Edge Runtime and Node.js server runtimes
- Any Web Crypto compatible runtime (Bun, Deno)

## authenticateRequest

Extract a bearer token or session cookie from an incoming `Request`, verify signature and claims, and return a signed-in or signed-out state object.

```ts
import { authenticateRequest } from '@xid-kit/backend'

const state = await authenticateRequest(request, {
  jwtKey: env.XID_JWKS_PUBLIC_KEY,
  issuer: 'https://xid.dev',
})
if (state.status === 'signed-in') {
  const { userId } = state.toAuth()
}
```

## verifyToken

Low-level access token verification. Pass `jwtKey` from JWKS to skip network round-trips on cold start. Expected failures return a Result type, not an exception.

```ts
import { verifyToken } from '@xid-kit/backend'

const result = await verifyToken(token, {
  jwtKey: env.XID_JWKS_PUBLIC_KEY,
  issuer: 'https://xid.dev',
  audience: 'my-api',
})
if (!result.ok) return new Response('Unauthorized', { status: 401 })
```

## verifyWebhook

Validates Svix-style webhook signatures (`svix-id`, `svix-timestamp`, `svix-signature`) with a five-minute replay window.

```ts
import { verifyWebhook } from '@xid-kit/backend'

const event = await verifyWebhook(request, {
  secret: env.XID_WEBHOOK_SECRET,
})
```

## Exported API

| Export | Kind | Purpose |
| --- | --- | --- |
| `authenticateRequest` | function | Extract and verify bearer token or session cookie; returns RequestState discriminated union |
| `verifyToken` | function | Low-level access token verification: signature, exp, nbf, iss, aud, azp |
| `verifyWebhook` | function | Svix-style HMAC-SHA256 webhook signature validation with 5-minute replay window |
| `toVerifyKeySet` | function | Convert JwtKey (JWK, JWKS, or CryptoKey) to VerifyKeySet for verification |
| `JwksCache` | class | Optional network-fetching JWKS cache with configurable TTL (default 3600 s); use only when jwtKey is not pre-loaded |
| `AppError` | class | Thrown for unrecoverable SDK errors: missing JWT key, JWKS fetch failure, invalid options |
| `BACKEND_ERROR_CODES` | as const tuple | All BackendErrorCode values: missing\_jwt\_key, jwks\_fetch\_failed, invalid\_options |
| `PACKAGE` | string constant | Package name identifier '@xid-kit/backend' |

## Types

| Type | Description |
| --- | --- |
| `JwtKey` | Accepted public key forms: PublicJwk, Jwks, or &#123; alg, publicKey: CryptoKey &#125; |
| `JwksCacheOptions` | Constructor options for JwksCache: jwksUri, ttlSec, fetchFn |
| `VerifyTokenOptions` | Options for verifyToken: jwtKey, issuer, audience, clockSkewSec, signal |
| `VerifyTokenError` | Structured error returned when token verification fails (expected failure; not thrown) |
| `AuthenticateRequestOptions` | Options for authenticateRequest: jwtKey, issuer, audience, cookieName |
| `RequestState` | Discriminated union of SignedInState and SignedOutState |
| `SignedInState` | Valid session token found; includes toAuth() for claims access |
| `SignedOutState` | No valid token present; reason field indicates cause |
| `VerifyWebhookOptions` | Options for verifyWebhook: secret, tolerance (replay window seconds) |
| `WebhookVerifyError` | Structured error when webhook signature is invalid or replayed |
| `VerifiedWebhook` | Parsed and verified webhook payload |
| `BackendErrorCode` | Union of BACKEND\_ERROR\_CODES values |

## Security boundaries

- Uses public JWKS only. Never loads instance signing private keys.
- Verification uses Web Crypto via @xid-kit/crypto.
- Expected failures return Result types; unexpected errors throw AppError.

Source: https://xid.dev/sdks/backend/index.mdx
