---
title: Verification
description: Verify API keys from a string or request headers
---

## verify()

```typescript
verify(
  keyOrHeader: string | Record<string, string | undefined> | Headers,
  options?: VerifyOptions
): Promise<VerifyResult<TKey>>
```

Checks a key and returns the stored record when it may be used. `verify` never throws for a bad key; it returns `valid: false` with an `errorCode`. Errors from your storage are not caught.

**Input**

- A string is trimmed and a leading `Bearer ` is removed, unless the string starts with the configured `prefix` (so a prefix such as `bearer_` stays part of the key).
- Headers are read with [`extractKey()`](/docs/api-reference/utilities): `headerNames` are checked in order, and when a `prefix` is configured the first value that starts with it wins, so an unrelated `Authorization` header doesn't hide a key in `x-api-key`.

### VerifyOptions

| Prop | Type | Default | Description |
| - | - | - | - |
| `skipCache?` | `boolean` | `false` | Look the key up by hash without reading or writing the cache. |
| `headerNames?` | `string[]` | - | Headers to check for this call. Defaults to the manager's headerNames. |
| `extractBearer?` | `boolean` | - | Strip "Bearer " from header values for this call. Defaults to the manager's extractBearer. String input always has it stripped. |
| `skipTracking?` | `boolean` | `false` | Don't write lastUsedAt for this call. |

### VerifyResult

```typescript
type VerifyResult<TKey = ApiKeyRecord> = {
  valid: boolean
  record?: TKey           // set when valid
  error?: string          // message, set when not valid
  errorCode?: ApiKeyErrorCode
}
```

### Checks and error codes

Checks run in this order; the first failure is returned.

| `errorCode` | When |
| --- | --- |
| `MISSING_KEY` | No key in the string or any checked header. |
| `INVALID_FORMAT` | The key doesn't start with the configured `prefix`, or is longer than 512 characters (or than `prefix` + `length`, if that is longer). Rejected before hashing. |
| `INVALID_KEY` | No stored key has this hash. |
| `REVOKED` | `revokedAt` is set. Rotated keys are revoked. |
| `EXPIRED` | `expiresAt` is now or in the past, or can't be parsed. |
| `DISABLED` | `enabled` is `false`. |

A key that is revoked, expired and disabled reports `REVOKED`; expired and disabled reports `EXPIRED`. From `INVALID_KEY` on, a failure also removes the key's cache entry.

### Usage tracking

After a successful verify, `lastUsedAt` is written in the background unless `autoTrackUsage` is `false`, `skipTracking` is set, or the storage has no `update`. Each manager writes a given key at most once per `usageTrackingInterval` seconds (default 60), so `lastUsedAt` can lag by up to that long. A failed write is logged, never returned, and retried on a later verify after at most 5 seconds.

### Example

```typescript
import { ApiKeyErrorCode } from 'keypal'

const result = await keys.verify(request.headers)

if (!result.valid) {
  const status = result.errorCode === ApiKeyErrorCode.MISSING_KEY ? 401 : 403
  return Response.json({ error: result.error }, { status })
}

const ownerId = result.record?.ownerId
```

To map every code to a response, see [Error handling](/docs/utilities/error-handling).

## verifyFromHeaders()

```typescript
verifyFromHeaders(
  headers: Record<string, string | undefined> | Headers,
  options?: VerifyOptions
): Promise<TKey | null>
```

Calls `verify(headers, options)` and returns the record when valid, or `null` for any failure. Use `verify` when you need the reason.

```typescript
const record = await keys.verifyFromHeaders(request.headers)
if (!record) {
  return new Response('Unauthorized', { status: 401 })
}
```
