---
title: Utilities
description: 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](/docs/utilities/standalone-functions).

## extractKey()

```typescript
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`.

```typescript
// prefix: 'sk_'
keys.extractKey({ authorization: 'Basic dXNlcjpwYXNz', 'x-api-key': 'sk_abc' })
// 'sk_abc'
```

## hasKey()

```typescript
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()

```typescript
generateKey(): string
```

Returns a new key (`prefix` + `length` random characters from `alphabet`) without saving it. Use [`create()`](/docs/api-reference/key-management) to issue a key.

## hashKey()

```typescript
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.

:::note
The manager hashes the configured `salt` with SHA-256 before using it, so the standalone `hashKey(key, { salt })` gives a different hash. Use the manager's method when a salt is set.
:::

## validateKey()

```typescript
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()

```typescript
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](/docs/concepts/caching).

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