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

Drizzle

Store keys in PostgreSQL, MySQL, MariaDB or SQLite through Drizzle ORM

DrizzleStore keeps keys in a table in your database, through the Drizzle instance your app already has. It works with PostgreSQL, MySQL, MariaDB and SQLite (including libSQL and Cloudflare D1).

Install

npm install keypal drizzle-orm
pnpm add keypal drizzle-orm
yarn add keypal drizzle-orm
bun add keypal drizzle-orm
nub add keypal drizzle-orm
aube add keypal drizzle-orm

Plus the driver for your database, such as pg, mysql2 or better-sqlite3.

Table

The default table has three columns: id, keyHash, and metadata, a JSON column holding every other field. Make keyHash unique; verify looks keys up by it.

keypal ships this table. Re-export it from your schema so drizzle-kit creates it:

export { apikey } from 'keypal/drizzle/schema'

It creates a table named apikey with id text, key_hash text (unique and indexed) and metadata jsonb. If you define it yourself, metadata must be jsonb, not json.

import { json, mysqlTable, varchar } from 'drizzle-orm/mysql-core'

export const apikey = mysqlTable('apikey', {
  id: varchar('id', { length: 255 }).primaryKey(),
  keyHash: varchar('key_hash', { length: 128 }).notNull().unique(),
  metadata: json('metadata').notNull(),
})
import { sqliteTable, text } from 'drizzle-orm/sqlite-core'

export const apikey = sqliteTable('apikey', {
  id: text('id').primaryKey(),
  keyHash: text('key_hash').notNull().unique(),
  // Plain text: keypal writes the JSON itself, so don't use { mode: 'json' }.
  metadata: text('metadata').notNull(),
})

Then generate and run the migration with drizzle-kit generate and drizzle-kit migrate (or drizzle-kit push).

Setup

import { drizzle } from 'drizzle-orm/node-postgres'
import { createKeys } from 'keypal'
import { DrizzleStore } from 'keypal/drizzle'
import { apikey } from './db/schema'

const db = drizzle(process.env.DATABASE_URL!)

const keys = createKeys({
  prefix: 'sk_',
  storage: new DrizzleStore({ db, table: apikey }),
})

keypal detects the database from the Drizzle instance. If it can’t, it logs a warning and assumes PostgreSQL; set provider: 'pg' | 'mysql' | 'sqlite' to say which.

Options

Option Type Description
db Drizzle database Your Drizzle instance
table Drizzle table The API key table
provider 'pg' | 'mysql' | 'sqlite' Overrides detection
auditLogTable Drizzle table Enables audit log storage
schema object Column names and flattenMetadata; see below
debugLogs boolean Logs every storage call

Column names

Column names in schema are the property names on your Drizzle table object, not the SQL names. If your table calls the hash column hash:

const store = new DrizzleStore({
  db,
  table: apiKeys,
  schema: { apiKeyColumns: { keyHash: 'hash' } },
})

One column per field

With flattenMetadata: true, each field gets its own column instead of the JSON column. Use it to index or query fields such as ownerId directly. On MySQL, MariaDB and SQLite it also stops owner lookups from reading the whole table.

The table needs a column for every field. Property names match keypal’s field names unless you rename them with apiKeyColumns.metadataColumns.

import { boolean, index, jsonb, pgTable, text } from 'drizzle-orm/pg-core'

export const apiKeys = pgTable(
  'api_keys',
  {
    id: text('id').primaryKey(),
    keyHash: text('key_hash').notNull().unique(),
    ownerId: text('owner_id').notNull(),
    name: text('name'),
    description: text('description'),
    scopes: jsonb('scopes'),
    resources: jsonb('resources'),
    tags: jsonb('tags'),
    enabled: boolean('enabled'),
    // keypal stores timestamps as ISO strings
    expiresAt: text('expires_at'),
    revokedAt: text('revoked_at'),
    lastUsedAt: text('last_used_at'),
    createdAt: text('created_at'),
    rotatedTo: text('rotated_to'),
  },
  (table) => [index('api_keys_owner_id_idx').on(table.ownerId)]
)
const store = new DrizzleStore({
  db,
  table: apiKeys,
  schema: { flattenMetadata: true },
})

Audit logs

Pass auditLogTable and turn on auditLogs to store audit logs:

import { jsonb, pgTable, text } from 'drizzle-orm/pg-core'

export const apiKeyLogs = pgTable('api_key_logs', {
  id: text('id').primaryKey(),
  keyId: text('key_id').notNull(),
  ownerId: text('owner_id').notNull(),
  action: text('action').notNull(),
  timestamp: text('timestamp').notNull(),
  data: jsonb('data'),
})
const keys = createKeys({
  prefix: 'sk_',
  auditLogs: true,
  storage: new DrizzleStore({ db, table: apikey, auditLogTable: apiKeyLogs }),
})

timestamp holds an ISO string, which sorts and compares correctly as text. Use json for data on MySQL and text on SQLite. Rename columns with schema.auditLogColumns.

Behavior

  • Updates write only the given fields in one statement (a JSONB merge on PostgreSQL, json_set on MySQL, MariaDB and SQLite), so a background lastUsedAt write can’t undo a concurrent revoke.
  • Owner and tag lookups run in SQL on PostgreSQL. On MySQL, MariaDB and SQLite with the JSON column, list, findByTag and revokeAll read the whole table. With flattenMetadata there, owner lookups run in SQL, and tag lookups read the owner’s keys (or the whole table when no owner is given) and filter them in your process.
  • Duplicates are rejected by your table’s constraints, so keep id as the primary key and keyHash unique.
  • Caching saves nothing here; leave cache off. See Caching.

Was this page helpful?