---
title: Kysely
description: Store keys in PostgreSQL, MySQL, MariaDB or SQLite through Kysely
---

`KyselyStore` keeps keys in a table in your database, through a Kysely instance. It works with PostgreSQL, MySQL, MariaDB and SQLite. SQL Server is untested, and its updates are not atomic (see below).

## Install

```package-install
keypal kysely
```

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

## Table

The default table has three columns: `id`, `keyHash`, and `metadata`, which holds every other field as JSON. Column names are used exactly as written, so the default hash column is `keyHash` in camelCase. Make it unique; `verify` looks keys up by it.

**PostgreSQL**

```sql
CREATE TABLE api_keys (
  id TEXT PRIMARY KEY,
  "keyHash" TEXT NOT NULL UNIQUE,
  metadata JSONB NOT NULL
);
```

`metadata` must be `JSONB`: owner and tag lookups use the `@>` operator, which `JSON` doesn't have.

**MySQL / MariaDB**

```sql
CREATE TABLE api_keys (
  id VARCHAR(255) PRIMARY KEY,
  keyHash VARCHAR(128) NOT NULL UNIQUE,
  metadata JSON NOT NULL
);
```

**SQLite**

```sql
CREATE TABLE api_keys (
  id TEXT PRIMARY KEY,
  keyHash TEXT NOT NULL UNIQUE,
  metadata TEXT NOT NULL
);
```

## Setup

```ts
import { Kysely, PostgresDialect } from 'kysely'
import { Pool } from 'pg'
import { createKeys } from 'keypal'
import { KyselyStore } from 'keypal/kysely'

// Your own Database type works too: new Kysely<Database>(...)
const db = new Kysely({
  dialect: new PostgresDialect({
    pool: new Pool({ connectionString: process.env.DATABASE_URL }),
  }),
})

const keys = createKeys({
  prefix: 'sk_',
  storage: new KyselyStore({ db, table: 'api_keys' }),
})
```

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

## Options

| Option | Type | Description |
| --- | --- | --- |
| `db` | `Kysely` | Your Kysely instance, typed with any schema |
| `table` | string | The API key table name |
| `provider` | `'pg' \| 'mysql' \| 'sqlite' \| 'mssql'` | Overrides detection |
| `auditLogTable` | string | Enables audit log storage |
| `schema` | object | Column names and `flattenMetadata`; see below |
| `debugLogs` | boolean | Logs every storage call |

## Column names

Rename columns with `schema.apiKeyColumns`. The names are the SQL column names:

```ts
const store = new KyselyStore({
  db,
  table: 'api_keys',
  schema: { apiKeyColumns: { keyHash: 'key_hash', metadata: 'data' } },
})
```

With `flattenMetadata: true`, each field gets its own column instead of `metadata`. The table then needs a column for every field: `ownerId`, `name`, `description`, `scopes`, `resources`, `tags`, `enabled`, `expiresAt`, `revokedAt`, `lastUsedAt`, `createdAt` and `rotatedTo`. Rename them with `apiKeyColumns.metadataColumns`:

```ts
const store = new KyselyStore({
  db,
  table: 'api_keys',
  schema: {
    flattenMetadata: true,
    apiKeyColumns: {
      keyHash: 'key_hash',
      metadataColumns: { ownerId: 'owner_id', expiresAt: 'expires_at' },
    },
  },
})
```

Timestamps are stored as ISO strings. On PostgreSQL, make `scopes` and `tags` `TEXT[]` and `resources` `JSONB`; on the other databases, `scopes`, `resources` and `tags` hold JSON text. Index the owner column: owner lookups then run in SQL on every database.

## Audit logs

Pass `auditLogTable` and turn on `auditLogs` to store [audit logs](/docs/concepts/audit-logging):

```sql
CREATE TABLE api_key_logs (
  id TEXT PRIMARY KEY,
  "keyId" TEXT NOT NULL,
  "ownerId" TEXT NOT NULL,
  action TEXT NOT NULL,
  timestamp TEXT NOT NULL,
  data JSONB
);
```

```ts
const keys = createKeys({
  prefix: 'sk_',
  auditLogs: true,
  storage: new KyselyStore({ db, table: 'api_keys', auditLogTable: 'api_key_logs' }),
})
```

`timestamp` holds an ISO string, which sorts and compares correctly as text. On MySQL and SQLite, `data` can be `TEXT`. Rename columns with `schema.auditLogColumns`.

## Behavior

- **Updates** write only the given fields in one statement on PostgreSQL, MySQL, MariaDB and SQLite, so a background `lastUsedAt` write can't undo a concurrent revoke.
- **SQL Server** with the JSON column rewrites the whole `metadata` value on each update. Two updates at the same moment can overwrite each other, for example a `lastUsedAt` write undoing a revoke. Use `flattenMetadata` there, which writes only the changed columns.
- **Owner and tag lookups** run in SQL on PostgreSQL with the JSON column. On the other databases, `list`, `findByTag` and `revokeAll` read the whole table. With `flattenMetadata`, owner lookups run in SQL everywhere, and tag lookups read the owner's keys (or the whole table when no owner is given) and filter them in your process.
- **Caching** saves nothing here; leave `cache` off. See [Caching](/docs/concepts/caching).
