Skip to content
keypal
Esc
↑↓navigate↵open⌘Jpreview
On this page

createKeys()

Create an API key manager and the options it takes

Signature

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.

PropType
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.

Typestring
length?number

Characters in the random part of the key, not counting the prefix. Must be a positive integer.

Typenumber
Default32
alphabet?string

Characters the random part is drawn from. Needs 2 to 256 characters with at least 2 distinct.

Typestring
DefaultA-Z, a-z, 0-9
algorithm?"sha256" | "sha512"

Hash used to store keys.

Type"sha256" | "sha512"
Default"sha256"
salt?string

Added to every key before hashing. Changing it invalidates every stored key.

Typestring
storage?"memory" | "redis" | Storage | KeyLookup<TKey>

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.

Type"memory" | "redis" | Storage | KeyLookup<TKey>
Default"memory"
cache?boolean | "redis" | Cache

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.

Typeboolean | "redis" | Cache
Defaultfalse
cacheTtl?number

Cache entry lifetime in seconds.

Typenumber
Default60
headerNames?string[]

Headers checked, in order, when verify is given headers.

Typestring[]
Default["authorization", "x-api-key"]
extractBearer?boolean

Strip a leading "Bearer " from header values.

Typeboolean
Defaulttrue
redis?RedisClient

ioredis client. Required for storage: "redis" or cache: "redis".

TypeRedisClient
revokedKeyTtl?number

Seconds Redis keeps a revoked or rotated key's record (7 days). 0 keeps it forever. Applies only to storage: "redis".

Typenumber
Default604800
autoTrackUsage?boolean

Write lastUsedAt in the background after a successful verify. Off when the storage has no update method.

Typeboolean
Defaulttrue
usageTrackingInterval?number

Minimum seconds between lastUsedAt writes for the same key, per manager instance. 0 writes on every verify.

Typenumber
Default60
impliedScopes?Record<string, string[]>

Scopes that grant other scopes in the manager's scope checks, applied transitively, e.g. { admin: ["read", "write"] }.

TypeRecord<string, string[]>
auditLogs?boolean

Record created, revoked, rotated, enabled and disabled actions. Needs a storage with audit-log methods.

Typeboolean
Defaultfalse
auditContext?ActionContext

Default context merged into every audit log entry. Per-call context overrides it; metadata objects are merged.

TypeActionContext

For what each option does in practice, see 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

import Redis from 'ioredis'
import { createKeys } from 'keypal'

const keys = createKeys({
  prefix: 'sk_live_',
  storage: 'redis',
  redis: new Redis(),
})
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 and Custom storage.

Was this page helpful?