Quick start
Create an API key and verify your first request.
This page takes you from a new project to a request that keypal has authenticated. The examples use the Fetch API’s Request, which Hono, Next.js route handlers, Bun, Deno, and Cloudflare Workers all hand you. verify also takes a plain header object or the key as a string.
Create a manager
createKeys returns the manager you create and verify keys with. Make one per process and share it.
import { createKeys } from 'keypal'
import Redis from 'ioredis'
export const keys = createKeys({
prefix: 'sk_live_',
salt: process.env.API_KEY_SALT,
storage: 'redis',
redis: new Redis(), // localhost:6379; pass a URL or options for other servers
})The prefix is added to every key and lets keypal reject keys without it before touching storage. The salt is mixed into every hash; keep it secret and never change it, because existing keys stop matching. To try keypal without Redis, leave out storage and redis and keys are kept in memory. For SQL databases, see Storage.
Create a key
import { keys } from './keys'
const { key, record } = await keys.create({
ownerId: 'user_123',
name: 'CI deploys',
scopes: ['deploy'],
})key is the secret: sk_live_ followed by 32 random characters. Show it to the user once; keypal stores only its hash and cannot show it again. record is what was stored: its id, ownerId, scopes, and the other fields described in API keys.
Verify a request
Clients send the key in Authorization: Bearer <key> or x-api-key: <key>. Pass the request’s headers to verify:
import { keys } from './keys'
export async function handler(request: Request) {
const result = await keys.verify(request.headers)
if (!result.record) {
return Response.json(
{ error: result.error, code: result.errorCode },
{ status: 401 }
)
}
return Response.json({ owner: result.record.ownerId })
}record is set only when valid is true. Otherwise errorCode says why: MISSING_KEY, INVALID_FORMAT, INVALID_KEY, REVOKED, EXPIRED, or DISABLED. See Error handling for mapping them to responses.
Check scopes
A valid key is not necessarily allowed to do everything. Check its scopes before acting:
if (!keys.hasScope(result.record, 'deploy')) {
return Response.json({ error: 'forbidden' }, { status: 403 })
}Scopes and permissions covers the other checks, and resource scopes covers keys limited to one project or site.
Revoke it
await keys.revoke(record.id)The next verify of that key, on any server sharing the storage, returns REVOKED.
Already have an API keys table?
If your app already stores hashed keys, pass a lookup instead of a storage adapter. verify runs the same checks against your rows (prefix and length, hashing, revoked, expired, disabled, usage tracking) and returns them with your row type.
import { createKeys } from 'keypal'
import { eq } from 'drizzle-orm'
import { db } from './db'
import { apiKeys } from './schema'
export const keys = createKeys({
prefix: 'sk_',
storage: {
// Rows need id and keyHash; enabled, expiresAt and revokedAt are read when present.
findByHash: async (keyHash) =>
(await db.query.apiKeys.findFirst({ where: eq(apiKeys.keyHash, keyHash) })) ?? null,
// Optional. Without it, keypal does not track lastUsedAt.
update: async (id: string, { lastUsedAt }: { lastUsedAt: string }) => {
await db.update(apiKeys).set({ lastUsedAt: new Date(lastUsedAt) }).where(eq(apiKeys.id, id))
},
},
})
const result = await keys.verify(request.headers)
// result.record has your row's type, e.g. result.record.organizationId
Your table’s keyHash values must be what keys.hashKey(secret) returns with the same salt and algorithm. Creating and revoking keys stays in your code: keys.generateKey() gives you a new secret and keys.hashKey() its hash to store. keypal’s own management methods (create, revoke, list, and the rest) throw STORAGE_NOT_SUPPORTED in this mode.
Next
- Configuration lists every option.
- API keys explains what
verifychecks and in what order.