Verification
Verify API keys from a string or request headers
verify()
verify(
keyOrHeader: string | Record<string, string | undefined> | Headers,
options?: VerifyOptions
): Promise<VerifyResult<TKey>>
Checks a key and returns the stored record when it may be used. verify never throws for a bad key; it returns valid: false with an errorCode. Errors from your storage are not caught.
Input
- A string is trimmed and a leading
Beareris removed, unless the string starts with the configuredprefix(so a prefix such asbearer_stays part of the key). - Headers are read with
extractKey():headerNamesare checked in order, and when aprefixis configured the first value that starts with it wins, so an unrelatedAuthorizationheader doesn’t hide a key inx-api-key.
VerifyOptions
skipCache?boolean
Look the key up by hash without reading or writing the cache.
booleanfalseheaderNames?string[]
Headers to check for this call. Defaults to the manager's headerNames.
string[]extractBearer?boolean
Strip "Bearer " from header values for this call. Defaults to the manager's extractBearer. String input always has it stripped.
booleanskipTracking?boolean
Don't write lastUsedAt for this call.
booleanfalseVerifyResult
type VerifyResult<TKey = ApiKeyRecord> = {
valid: boolean
record?: TKey // set when valid
error?: string // message, set when not valid
errorCode?: ApiKeyErrorCode
}
Checks and error codes
Checks run in this order; the first failure is returned.
errorCode |
When |
|---|---|
MISSING_KEY |
No key in the string or any checked header. |
INVALID_FORMAT |
The key doesn’t start with the configured prefix, or is longer than 512 characters (or than prefix + length, if that is longer). Rejected before hashing. |
INVALID_KEY |
No stored key has this hash. |
REVOKED |
revokedAt is set. Rotated keys are revoked. |
EXPIRED |
expiresAt is now or in the past, or can’t be parsed. |
DISABLED |
enabled is false. |
A key that is revoked, expired and disabled reports REVOKED; expired and disabled reports EXPIRED. From INVALID_KEY on, a failure also removes the key’s cache entry.
Usage tracking
After a successful verify, lastUsedAt is written in the background unless autoTrackUsage is false, skipTracking is set, or the storage has no update. Each manager writes a given key at most once per usageTrackingInterval seconds (default 60), so lastUsedAt can lag by up to that long. A failed write is logged, never returned, and retried on a later verify after at most 5 seconds.
Example
import { ApiKeyErrorCode } from 'keypal'
const result = await keys.verify(request.headers)
if (!result.valid) {
const status = result.errorCode === ApiKeyErrorCode.MISSING_KEY ? 401 : 403
return Response.json({ error: result.error }, { status })
}
const ownerId = result.record?.ownerId
To map every code to a response, see Error handling.
verifyFromHeaders()
verifyFromHeaders(
headers: Record<string, string | undefined> | Headers,
options?: VerifyOptions
): Promise<TKey | null>
Calls verify(headers, options) and returns the record when valid, or null for any failure. Use verify when you need the reason.
const record = await keys.verifyFromHeaders(request.headers)
if (!record) {
return new Response('Unauthorized', { status: 401 })
}