---
title: API keys
description: What a key is, what keypal stores, how verify decides, and how a key moves from created to revoked.
---

## The key and its hash

A key is your `prefix` followed by random characters: `sk_live_` and then 32 characters from A–Z, a–z and 0–9 by default. The random part comes from `nanoid`, which uses the platform's secure random generator.

keypal never stores the key. `create` returns it once and saves its SHA-256 or SHA-512 hash, with your `salt` mixed in if you set one. When a request arrives, keypal hashes the key it was given and looks the hash up. Someone who reads your database gets hashes, not working keys.

To compare a key with a hash you already hold, `keys.validateKey(key, hash)` uses a timing-safe comparison.

## What a stored key holds

`create` and `verify` give you an `ApiKeyRecord`. All its fields are top-level:

| Field | Set by | Meaning |
| --- | --- | --- |
| `id` | keypal | Unique id. Use it to revoke, rotate, enable, or disable the key. |
| `keyHash` | keypal | Hash of the key. |
| `ownerId` | you | The user or account the key belongs to. `''` if you leave it out. |
| `name`, `description` | you | Labels for people. |
| `scopes` | you | What the key may do. See [Scopes and permissions](/docs/concepts/scopes-and-permissions). |
| `resources` | you | Scopes limited to one resource. See [Resource scopes](/docs/concepts/resource-scopes). |
| `tags` | you | Labels for finding keys, stored lowercase. See [Tags](/docs/concepts/tags). |
| `expiresAt` | you | When the key stops working, or `null`. See [Expiration](/docs/concepts/expiration). |
| `enabled` | you, `enable`, `disable` | `false` turns the key off without revoking it. Defaults to `true`. |
| `createdAt` | keypal | ISO timestamp. |
| `lastUsedAt` | keypal | ISO timestamp of a recent successful verify, written at most once per `usageTrackingInterval`. |
| `revokedAt` | `revoke`, `rotate` | When the key was revoked. |
| `rotatedTo` | `rotate` | Id of the key that replaced this one. |

## What verify checks

`keys.verify(input)` takes request headers or the key itself, and returns `{ valid, record?, error?, errorCode? }`. It stops at the first failed check:

1. **Find the key.** From headers, it reads `headerNames` in order and strips `Bearer `. From a string, it trims it and strips `Bearer `. Nothing found returns `MISSING_KEY`.
2. **Check the format.** A key without the configured `prefix`, or longer than 512 characters (or your prefix plus `length`, if that is longer), returns `INVALID_FORMAT` without reading storage.
3. **Look it up.** keypal hashes the key and finds the stored record by hash. No match returns `INVALID_KEY`.
4. **Check its status.** A revoked key returns `REVOKED`, an expired one `EXPIRED`, a disabled one `DISABLED`. When several apply, the earliest in that list wins.
5. **Accept it.** keypal records `lastUsedAt` in the background and returns `{ valid: true, record }`.

`verify` checks that the key is genuine and usable, not what it may do. Check scopes yourself after it succeeds.

The status rule in step 4 is exported as `getKeyStatus(record)`, which returns `'active'`, `'revoked'`, `'expired'`, or `'disabled'`. Use it when you load a key some other way and need the same answer `verify` would give.

## Lifecycle

```ts
const { key, record } = await keys.create({ ownerId: 'user_123', scopes: ['read'] })

await keys.disable(record.id) // verify returns DISABLED
await keys.enable(record.id)  // works again

const { key: newKey, record: newRecord } = await keys.rotate(record.id)
// The old key is revoked now; newKey has the same scopes, tags, and expiry.

await keys.revoke(newRecord.id)       // verify returns REVOKED
await keys.revokeAll('user_123')      // revokes every remaining key the owner has
```

**Disable** when you may want the key back. **Revoke** when you don't: a revoked key cannot be enabled, rotated, or revoked again. These calls throw `ALREADY_REVOKED`, `CANNOT_MODIFY_REVOKED`, `ALREADY_ENABLED`, or `ALREADY_DISABLED` when the key is already in that state.

**Rotate** issues a new key that copies the old one's settings, including being disabled. Fields you pass replace the copied ones, so `keys.rotate(id, { expiresAt: null })` clears an expiry. The old key is revoked in the same call, with `rotatedTo` pointing at the new one. There is no overlap period, so hand the new key to the client before old requests stop working.

Revocation is soft: the record stays in storage with `revokedAt` set, so you can still list it and see its audit history. With `storage: 'redis'`, Redis deletes revoked records after `revokedKeyTtl` (7 days by default).

## Changes apply at once

Every `verify` reads the key's current record from storage, even with a cache. A key revoked or disabled on one server fails on every other server sharing that storage on its next request. Nothing has to expire first.

Memory storage is per process, so this only holds across servers when they share Redis or a database.
