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

Utilities

Manager helpers for extracting, generating and hashing keys and clearing the cache

These methods use the manager’s configured prefix, length, alphabet, algorithm, salt and header settings. For the same helpers without a manager, see Standalone functions.

extractKey()

extractKey(
  headers: Record<string, string | undefined> | Headers,
  options?: { headerNames?: string[]; extractBearer?: boolean; prefix?: string }
): string | null

Returns the key from the request headers, or null. Options default to the manager’s headerNames, extractBearer and prefix.

  • Headers are checked in headerNames order; names match case-insensitively. Values are trimmed and empty values skipped.
  • With extractBearer, Bearer <token> yields <token>; a bare Bearer is skipped. A value starting with prefix is returned as is, even if the prefix starts with “bearer”.
  • With a prefix, the first value that starts with it wins. If none does, the first non-empty value is returned, and verify then rejects it with INVALID_FORMAT.
// prefix: 'sk_'
keys.extractKey({ authorization: 'Basic dXNlcjpwYXNz', 'x-api-key': 'sk_abc' })
// 'sk_abc'

hasKey()

hasKey(
  headers: Record<string, string | undefined> | Headers,
  options?: { headerNames?: string[]; extractBearer?: boolean; prefix?: string }
): boolean

true when extractKey returns a key. It doesn’t verify the key.

generateKey()

generateKey(): string

Returns a new key (prefix + length random characters from alphabet) without saving it. Use create() to issue a key.

hashKey()

hashKey(key: string): string

Returns the hex hash that storage keeps for key, using the configured algorithm and salt. Use it to look a key up with findByHash, or to hash keys you import into a custom table.

validateKey()

validateKey(key: string, storedHash: string): boolean

Hashes key with the manager’s settings and compares it to storedHash in constant time. It only compares hashes; it doesn’t read storage or check revocation, expiry or enabled.

invalidateCache()

invalidateCache(keyHash: string): Promise<void>

Removes the cache entry for a key hash. Does nothing without a cache. Unlike the internal clears, a cache error is thrown.

revoke, rotate, enable, disable and failed verifies already clear the entry, and verify re-reads the record on every call, so you need this only after changing a key’s stored hash outside keypal. See Caching.

await keys.invalidateCache(keys.hashKey(oldKey))

Was this page helpful?