---
title: createKeys()
description: Create an API key manager and the options it takes
---

## Signature

```typescript
function createKeys(config?: ConfigInput): ApiKeyManager

// Verify against your own table; verify returns your row type
function createKeys<TKey extends VerifiableKey>(
  config: Omit<ConfigInput<TKey>, "storage"> & { storage: KeyLookup<TKey> }
): ApiKeyManager<TKey>
```

Returns an `ApiKeyManager`. `TKey` is `ApiKeyRecord` unless `storage` is a `KeyLookup` that returns your own rows. The `ApiKeyManager` type is exported for annotations; create instances with `createKeys`.

## Options

All options are optional.

| Prop | Type | Default | Description |
| - | - | - | - |
| `prefix?` | `string` | - | Prepended to every generated key, e.g. "sk_live_". When set, verify rejects keys that don't start with it (INVALID_FORMAT), and header extraction prefers a header whose value starts with it. |
| `length?` | `number` | `32` | Characters in the random part of the key, not counting the prefix. Must be a positive integer. |
| `alphabet?` | `string` | `A-Z, a-z, 0-9` | Characters the random part is drawn from. Needs 2 to 256 characters with at least 2 distinct. |
| `algorithm?` | `"sha256" \| "sha512"` | `"sha256"` | Hash used to store keys. |
| `salt?` | `string` | - | Added to every key before hashing. Changing it invalidates every stored key. |
| `storage?` | `"memory" \| "redis" \| Storage \| KeyLookup<TKey>` | `"memory"` | Where keys live. "redis" needs an ioredis client in the redis option. A KeyLookup ({ findByHash, findById?, update? }) verifies keys kept in your own table; management methods then throw STORAGE_NOT_SUPPORTED. |
| `cache?` | `boolean \| "redis" \| Cache` | `false` | Caches which key id a key hash belongs to. true is an in-memory cache, "redis" uses the redis client, or pass your own Cache. verify still re-reads the key by id, so it needs findById; a KeyLookup without it skips the cache. |
| `cacheTtl?` | `number` | `60` | Cache entry lifetime in seconds. |
| `headerNames?` | `string[]` | `["authorization", "x-api-key"]` | Headers checked, in order, when verify is given headers. |
| `extractBearer?` | `boolean` | `true` | Strip a leading "Bearer " from header values. |
| `redis?` | `RedisClient` | - | ioredis client. Required for storage: "redis" or cache: "redis". |
| `revokedKeyTtl?` | `number` | `604800` | Seconds Redis keeps a revoked or rotated key's record (7 days). 0 keeps it forever. Applies only to storage: "redis". |
| `autoTrackUsage?` | `boolean` | `true` | Write lastUsedAt in the background after a successful verify. Off when the storage has no update method. |
| `usageTrackingInterval?` | `number` | `60` | Minimum seconds between lastUsedAt writes for the same key, per manager instance. 0 writes on every verify. |
| `impliedScopes?` | `Record<string, string[]>` | - | Scopes that grant other scopes in the manager's scope checks, applied transitively, e.g. { admin: ["read", "write"] }. |
| `auditLogs?` | `boolean` | `false` | Record created, revoked, rotated, enabled and disabled actions. Needs a storage with audit-log methods. |
| `auditContext?` | `ActionContext` | - | Default context merged into every audit log entry. Per-call context overrides it; metadata objects are merged. |

For what each option does in practice, see [Configuration](/docs/getting-started/configuration).

## Throws

`createKeys` throws synchronously when:

- `length` is not a positive integer, or `alphabet` has fewer than 2 distinct characters or more than 256 characters (`RangeError`).
- `storage: "redis"` or `cache: "redis"` is set without `redis`.
- `storage: "redis"` gets a client without `pipeline`, i.e. not an ioredis client.

## Examples

```typescript title="Redis storage"
import Redis from 'ioredis'
import { createKeys } from 'keypal'

const keys = createKeys({
  prefix: 'sk_live_',
  storage: 'redis',
  redis: new Redis(),
})
```

```typescript title="Verify against your own table"
import { createKeys } from 'keypal'

const keys = createKeys({
  prefix: 'sk_',
  storage: {
    findByHash: (keyHash) => db.apiKey.findUnique({ where: { keyHash } }),
    update: async (id, fields) => {
      await db.apiKey.update({ where: { id }, data: fields })
    },
  },
})

const result = await keys.verify(request.headers)
// result.record has your table's row type
```

A `KeyLookup` row needs `id` and `keyHash`, and may have `enabled`, `expiresAt` and `revokedAt`; verify applies the same checks as with built-in storage. For full adapters, see [Storage](/docs/storage/overview) and [Custom storage](/docs/storage/custom-storage).
