Multitenant

Kysely

`@multitenant/kysely` — per-tenant or shared `pg` pools with Kysely.

Kysely + pg helpers: per-tenant URL with a bounded Pool cache, or shared DB with createNodePgKysely and tenant isolation from @multitenant/database.

Install

npm install @multitenant/kysely kysely pg

Per-tenant database URL

import type { ResolvedTenant, TenantDefinition } from '@multitenant/core';
import { BoundedTenantDbResourceCache } from '@multitenant/database';
import { getTenantNodePgKysely } from '@multitenant/kysely';
import type { DB } from './types'; // your Kysely codegen / hand types

const poolCache = new BoundedTenantDbResourceCache<import('pg').Pool>({
  maxPools: 48,
  onEvict: (pool) => void pool.end(),
});

export function kyselyForTenant(
  resolved: ResolvedTenant,
  tenants: Record<string, TenantDefinition>,
) {
  return getTenantNodePgKysely<DB>(poolCache, resolved, tenants, {
    poolOptions: { max: 10 },
  });
}

Shared database

import { Pool } from 'pg';
import { createNodePgKysely } from '@multitenant/kysely';
import type { DB } from './types';

const pool = new Pool({ connectionString: process.env.DATABASE_URL });
export const db = createNodePgKysely<DB>(pool);

Then inside runWithTenantScope, filter queries by requireTenantKey() or use assignTenantIdForWrite on inserts.

See also

On this page