Skip to content

Database (Drizzle)

WebJs uses Drizzle as the default ORM. It fits the buildless thesis: there is no codegen and no engine binary (what you write is what runs), it runs on Node and Bun, and the types are inferred straight from your schema. SQLite is the default; Postgres is a flag away. The scaffold wires it all up under a db/ folder.

What the scaffold gives you

db/
  schema.server.ts       your models + relations, plain Drizzle
  connection.server.ts   opens the driver, exports `db`
  seed.server.ts         optional seed (run via `webjs db seed`)
  migrations/            generated SQL (committed)
drizzle.config.ts        drizzle-kit config (root)

The schema is plain Drizzle, written as Drizzle's own docs write it, so nothing WebJs-specific stands between you and the builders. The schema's column builders (drizzle-orm/sqlite-core or drizzle-orm/pg-core) and db/connection.server.ts are the dialect-specific parts; your queries and actions are identical whether you run SQLite or Postgres.

The schema

Write models with Drizzle's builders directly:

// db/schema.server.ts (SQLite)
import { defineRelations } from 'drizzle-orm';
import { sqliteTable, integer, text, index } from 'drizzle-orm/sqlite-core';

export const users = sqliteTable('users', {
  id: integer().primaryKey({ autoIncrement: true }),
  email: text().notNull().unique(),
  name: text(),
  createdAt: integer({ mode: 'timestamp_ms' }).notNull().defaultNow(),
});

export const posts = sqliteTable('posts', {
  id: integer().primaryKey({ autoIncrement: true }),
  slug: text().notNull().unique(),
  title: text().notNull(),
  body: text().notNull(),
  authorId: integer().notNull().references(() => users.id, { onDelete: 'cascade' }),
  createdAt: integer({ mode: 'timestamp_ms' }).notNull().defaultNow(),
}, (t) => [index('posts_author_id_idx').on(t.authorId)]);

export const relations = defineRelations({ users, posts }, (r) => ({
  users: { posts: r.many.posts({ from: r.users.id, to: r.posts.authorId }) },
  posts: { author: r.one.users({ from: r.posts.authorId, to: r.users.id }) },
}));

export type Post = typeof posts.$inferSelect;

A column's SQL name is its key unless you give one (integer('created_at', { mode: 'timestamp_ms' })). integer({ mode: 'timestamp_ms' }) reads and writes a JavaScript Date; plain integer() is a number. A JSON column is text({ mode: 'json' }).$type<T>() on SQLite and jsonb().$type<T>() on Postgres. A UUID key is text().primaryKey().$defaultFn(() => crypto.randomUUID()) on SQLite and uuid().primaryKey().defaultRandom() on Postgres.

Migrations

Drizzle has no client to generate. generate turns your schema into SQL; migrate applies it.

npm run db:generate     # webjs db generate -> drizzle-kit generate (schema to SQL)
npm run db:migrate      # webjs db migrate  -> drizzle-kit migrate (apply)

Both webjs dev and webjs start run webjs db migrate before serving (the webjs.dev.before / webjs.start.before steps, idempotent), so after you db:generate a migration it is applied on the next boot with no manual db:migrate, and a deploy applies pending migrations before serving. generate stays a deliberate, manual step (it authors migration files from a schema diff), never auto-run on boot.

The connection

// db/connection.server.ts (SQLite, runtime-neutral)
import * as schema from './schema.server.ts';

const url = process.env.DATABASE_URL?.replace(/^file:/, '') ?? 'db/dev.db';

// node:sqlite and bun:sqlite default busy_timeout to 0, so a contended write
// throws "database is locked". Set a 5s wait (+ WAL) so it waits instead.
function tune<T extends { exec(sql: string): unknown }>(client: T): T {
  client.exec('PRAGMA busy_timeout = 5000');
  client.exec('PRAGMA journal_mode = WAL');
  return client;
}

// Cache the DRIVER handle, never the Drizzle instance (see below).
const g = globalThis as unknown as { __webjs_db_clients?: Map<string, unknown> };
const clients = (g.__webjs_db_clients ??= new Map());
function cached<T>(open: () => T): T {
  if (!clients.has(url)) clients.set(url, open());
  return clients.get(url) as T;
}

async function connect() {
  if ((globalThis as { Bun?: unknown }).Bun) {
    const { Database } = await import('bun:sqlite');
    const { drizzle } = await import('drizzle-orm/bun-sqlite');
    return drizzle({ client: cached(() => tune(new Database(url))), relations: schema.relations });
  }
  const { DatabaseSync } = await import('node:sqlite');
  const { drizzle } = await import('drizzle-orm/node-sqlite');
  return drizzle({ client: cached(() => tune(new DatabaseSync(url))), relations: schema.relations });
}

export const db = await connect();

The globalThis cache reuses one open connection per database url across dev-server reloads. It holds the driver handle only: the Drizzle instance is rebuilt each time the module is evaluated, because it captures schema.relations. Caching the instance instead kept the relations from the first load, so a table added while npm run dev ran stayed undefined on db.query until a restart. This is the only file that opens the driver, and it is server-only (.server.ts), so it never reaches the browser.

Queries and mutations

Reads use the relational query builder with object filters; writes use the builder with .returning() (both SQLite and Postgres support it).

// modules/posts/queries/list-posts.server.ts
'use server';
import { db } from '#db/connection.server.ts';

export async function listPosts() {
  return db.query.posts.findMany({
    orderBy: { createdAt: 'desc' },
    with: { author: { columns: { name: true } } },
  });
}
// modules/posts/actions/create-post.server.ts
'use server';
import { db } from '#db/connection.server.ts';
import { posts } from '#db/schema.server.ts';

export async function createPost(input: { slug: string; title: string; body: string; authorId: number }) {
  const [row] = await db.insert(posts).values(input).returning();
  return { success: true as const, data: row };
}

Import the query or action from a page or component as a normal import; WebJs rewrites it into a typed RPC stub on the client.

// app/page.ts
import { listPosts } from '#modules/posts/queries/list-posts.server.ts';

export default async function Home() {
  const posts = await listPosts();
  return html`<ul>${posts.map(p => html`<li>${p.title}</li>`)}</ul>`;
}

Why the .server.ts boundary? Page modules (and layouts, loading, error, not-found, plus all components) load in the browser so transitively imported components register. A top-level import of db/connection.server.ts would pull the DB driver (pg, or the built-in node:sqlite, which need Node APIs) into the browser graph and crash. The .server.{js,ts} extension lets the framework rewrite the import into an RPC stub; the driver and your DB code never reach the client. The rule across the framework: server-only code goes in .server.{js,ts} files, route.ts handlers, or middleware.ts. Never in pages, layouts, or components.

Type safety

Types are inferred from the schema, never hand-written. typeof posts.$inferSelect is the row type; a .ts server action's return type flows through the RPC boundary to the client, and webjs's rich-type serializer keeps a Date a Date on both sides.

Switching to Postgres

Scaffold with the dialect you want:

webjs create my-app --db postgres

That writes the Postgres variants of db/schema.server.ts (pgTable from drizzle-orm/pg-core) and db/connection.server.ts (and the pg driver). The deploy files follow the dialect too: compose.yaml runs a postgres:17-alpine db service the app waits on (healthy before the boot-time migrate), and the generated CI workflow starts a Postgres service container, so docker compose up and the first CI run both work with no edits. Your schema.server.ts, queries, and actions are unchanged. To move an existing app, swap those two files for the Postgres variants and point DATABASE_URL at your Postgres instance. Migrations are generated per dialect, and runtime behaviour differs (case-sensitivity, constraints), so run your tests against the production engine before relying on a dev-SQLite / prod-Postgres setup. The generated DATABASE_URL names a lowercased, separator-folded form of the app name, so MyApp gets myapp, which is the same name Postgres folds an unquoted CREATE DATABASE MyApp to.

CLI

webjs db generate    # schema -> SQL migration (drizzle-kit generate)
webjs db migrate     # apply pending migrations (drizzle-kit migrate)
webjs db push        # push the schema straight to the dev DB (drizzle-kit push)
webjs db studio      # visual DB browser (drizzle-kit studio)
webjs db seed        # run db/seed.server.ts
webjs db <verb>      # any verb webjs.db maps in package.json (see below)

Bring your own ORM

Drizzle is the default, not lock-in. The runtime never imports it, db/connection.server.ts is your own file, and the webjs db verbs are adapter-driven. A db block in the package.json webjs config maps each verb to the shell command webjs db <verb> runs instead of the drizzle-kit default, with node_modules/.bin on the PATH and any extra arguments appended, so a Prisma app looks like this.

"webjs": {
  "db": {
    "generate": "prisma migrate dev --create-only",
    "migrate":  "prisma migrate deploy",
    "push":     "prisma db push",
    "studio":   "prisma studio",
    "reset":    "prisma migrate reset --force"
  }
}

Any key is a verb, so reset above adds a webjs db reset command. A verb the block does not name keeps its default (drizzle-kit for the four kit verbs, db/seed.server.ts for seed), so an app with no block behaves exactly as before and the scaffold emits none. The point is that webjs db migrate stays one spelling whatever sits behind it, so the scaffolded dev.before and start.before steps, the Dockerfile, CI, and the deployment guide all keep working after a swap. Write the bare binary (prisma migrate deploy) rather than npx prisma ..., since a pure Bun image ships no npx. The rest of the swap is your own files: replace db/connection.server.ts with the new client, delete drizzle.config.ts and db/columns.server.ts, and keep the server-only imports behind .server.ts exactly as with Drizzle.