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.
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.
stringlength?number
Characters in the random part of the key, not counting the prefix. Must be a positive integer.
number32alphabet?string
Characters the random part is drawn from. Needs 2 to 256 characters with at least 2 distinct.
stringA-Z, a-z, 0-9algorithm?"sha256" | "sha512"
Hash used to store keys.
"sha256" | "sha512""sha256"salt?string
Added to every key before hashing. Changing it invalidates every stored key.
stringstorage?"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.
"memory" | "redis" | Storage | KeyLookup<TKey>"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.
boolean | "redis" | CachefalsecacheTtl?number
Cache entry lifetime in seconds.
number60headerNames?string[]
Headers checked, in order, when verify is given headers.
string[]["authorization", "x-api-key"]extractBearer?boolean
Strip a leading "Bearer " from header values.
booleantrueredis?RedisClient
ioredis client. Required for storage: "redis" or cache: "redis".
RedisClientrevokedKeyTtl?number
Seconds Redis keeps a revoked or rotated key's record (7 days). 0 keeps it forever. Applies only to storage: "redis".
number604800autoTrackUsage?boolean
Write lastUsedAt in the background after a successful verify. Off when the storage has no update method.
booleantrueusageTrackingInterval?number
Minimum seconds between lastUsedAt writes for the same key, per manager instance. 0 writes on every verify.
number60impliedScopes?Record<string, string[]>
Scopes that grant other scopes in the manager's scope checks, applied transitively, e.g. { admin: ["read", "write"] }.
Record<string, string[]>auditLogs?boolean
Record created, revoked, rotated, enabled and disabled actions. Needs a storage with audit-log methods.
booleanfalseauditContext?ActionContext
Default context merged into every audit log entry. Per-call context overrides it; metadata objects are merged.
ActionContextFor what each option does in practice, see Configuration.
Throws
createKeys throws synchronously when:
lengthis not a positive integer, oralphabethas fewer than 2 distinct characters or more than 256 characters (RangeError).storage: "redis"orcache: "redis"is set withoutredis.storage: "redis"gets a client withoutpipeline, 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.