Back to blog

Bun, Elysia and Drizzle: A Tested Starter and 3 Traps

Davron14 min read
BunElysiadrizzle

Wire Drizzle into an Elysia API on Bun with a tested MIT starter, then meet three Drizzle behaviours that report success and leave the database wrong.

A fresh clone of our Bun, Elysia and Drizzle starter passes six tests in 620 ms. Remove the owner filter from the list route and the suite notices: on a clean database 5 tests pass and 1 fails, and on a database that already holds rows from an earlier run, 4 pass and 2 fail. The filter is in the code; we removed it only to see what the suite would say. The stranger-list test exists because, on CI's fresh database, no other test could notice a missing filter: the earlier tests ran before any other user had notes.

That is the setup half of this article, covering the schema, the client, an auth macro and tests that need no server. The second half covers three behaviours of drizzle-orm and drizzle-kit that report success and leave the database wrong.

What the starter contains

The repository is MIT-licensed and ours. It is a monorepo with apps/api (Elysia on Bun), apps/web (Next.js App Router), packages/db (the Drizzle schema and client) and a docker-compose.yml that starts Postgres. Next.js rewrites /api/* to the API, so the Better Auth cookie is first-party for both apps, and a single .env at the repo root is read by both. If you are still choosing a base, our list of 21 Elysia starters sorted by what you are building covers the field.

The root scripts are db:up (docker compose up -d --wait), db:push, setup (which is db:up && db:push), test and typecheck. The starter has no migrations folder. It uses drizzle-kit push and nothing else, which matters for the second half of this article.

The whole database client is one short file:

import { drizzle } from "drizzle-orm/postgres-js"
import postgres from "postgres"
import * as schema from "./schema"

const url = process.env.DATABASE_URL
if (!url) throw new Error("DATABASE_URL is not set — copy .env.example to .env")

// postgres-js connects lazily, on the first query.
export const sql = postgres(url, { max: 10 })
export const db = drizzle(sql, { schema })
export { schema }

The Drizzle Kit config next to it is shorter still, and the push script in packages/db/package.json loads the root .env with bun --env-file=../../.env drizzle-kit push:

import { defineConfig } from "drizzle-kit"

export default defineConfig({
  schema: "./src/schema.ts",
  dialect: "postgresql",
  dbCredentials: { url: process.env.DATABASE_URL! },
})

Wiring Drizzle into Elysia

Three pieces carry the integration: a table that belongs to a user, a plugin that turns a Better Auth session into a typed user in the route context, and a module that scopes every query to that user. The web app takes its types from the API.

The schema and the client

schema.ts holds Better Auth's four core tables (user, session, account, verification), with column names that follow Better Auth's Drizzle schema, plus the one example resource:

// The one example resource. Every row belongs to a user; the API only ever
// reads and writes the caller's own rows.
export const notes = pgTable(
  "notes",
  {
    id: text("id")
      .primaryKey()
      .$defaultFn(() => crypto.randomUUID()),
    userId: text("user_id")
      .notNull()
      .references(() => user.id, { onDelete: "cascade" }),
    title: text("title").notNull(),
    body: text("body").notNull().default(""),
    createdAt: timestamp("created_at").defaultNow().notNull(),
  },
  (t) => [index("notes_user_id_idx").on(t.userId)],
)

export type Note = typeof notes.$inferSelect

The foreign key cascades when a user is deleted, and notes_user_id_idx covers the lookup the API makes. Better Auth gets the same db and schema through drizzleAdapter(db, { provider: "pg", schema }), so auth and notes share one connection pool.

An auth macro in front of every route

Elysia macros let a route declare a requirement in its options. This one mounts Better Auth's handler, which serves /api/auth/*, and adds an auth macro:

import { Elysia } from "elysia"
import { auth } from "./auth"

/**
 * Mounts Better Auth's handler (it serves /api/auth/*) and adds an `auth`
 * macro. A route with `{ auth: true }` answers 401 without a valid session and
 * otherwise receives `user` and `session` in its context, typed.
 */
export const authPlugin = new Elysia({ name: "auth" })
  .mount(auth.handler)
  .macro({
    auth: {
      async resolve({ status, request: { headers } }) {
        const result = await auth.api.getSession({ headers })
        if (!result) return status(401, "Unauthorized")
        return { user: result.user, session: result.session }
      },
    },
  })

The notes module uses it. Here are the list route and the delete route; the create route is cut:

export const notesModule = new Elysia({ prefix: "/api/notes" })
  .use(authPlugin)
  .get(
    "/",
    ({ user }) =>
      db.select().from(notes).where(eq(notes.userId, user.id)).orderBy(desc(notes.createdAt)),
    { auth: true },
  )
  // ...
  .delete(
    "/:id",
    async ({ user, params, status }) => {
      // Scoped by owner: another user's id deletes nothing and reads as 404.
      const deleted = await db
        .delete(notes)
        .where(and(eq(notes.id, params.id), eq(notes.userId, user.id)))
        .returning({ id: notes.id })
      if (deleted.length === 0) return status(404, "Not found")
      return { id: deleted[0]!.id }
    },
    { auth: true, params: t.Object({ id: t.String() }) },
  )

Both queries filter on user.id, so a stranger's id matches no row.

A typed client for the web app

apps/api/src/app.ts ends with export type App = typeof app. The web app imports that as a type only, and treaty<App> from Eden gives it typed routes, bodies and responses:

import { treaty } from "@elysiajs/eden"
import type { App } from "@starter/api"

// ...
export const api = treaty<App>(typeof window === "undefined" ? "http://localhost:3000" : window.location.origin)

In the browser the client uses the page's origin; the localhost fallback only lets the module load during server rendering, so call it from client components.

Can six tests catch a missing owner filter?

They can, if one of them is written to. The tests live in apps/api/test/notes.test.ts, run on bun:test against the database named in .env, and call app.handle(new Request(...)), so no server starts. Each run signs up fresh users with test-${crypto.randomUUID()}@example.com, which keeps runs from colliding with each other or with existing data.

The six cover the health route without a session; the notes list without a session (401); one test that creates (201), lists and deletes the caller's own note (200); an empty title (422); a stranger deleting the owner's note (404); and a stranger listing notes (an empty array while the owner's note exists). A fresh clone, bun run db:push and bun run test on Bun 1.4.4 gave:

@starter/api test: bun test v1.4.4 (38afee6c8)
@starter/api test:  6 pass
@starter/api test:  0 fail
@starter/api test:  23 expect() calls
@starter/api test: Ran 6 tests across 1 file. [620.00ms]

bun run typecheck exited 0 in all three packages.

A green run proves little unless a test can fail, so we broke the code on purpose. We deleted the owner filter from the list route, leaving this:

db.select().from(notes).orderBy(desc(notes.createdAt))

On a fresh database (docker compose down -v, up, db:push, then the test run) one test failed:

(fail) api > does not show one user's notes to another user [120.74ms]
 5 pass
 1 fail

Run the same broken code against a database that already held rows from the first run and the picture is worse, because the own-notes test fails as well:

(fail) api > creates, lists and deletes the caller's own notes
(fail) api > does not show one user's notes to another user
 4 pass
 2 fail

The commit that added the stranger-list test (f959168, 2026-11-02) explains why it is there: on CI's fresh database the earlier tests ran before any other user had notes, so the owner filter on the list route was never exercised. A comment in the last test says the same thing: "The owner's note exists while the stranger lists, so an unscoped query would return it here even on a fresh database." We restored the file after the experiment (git status --short came back empty).

Where Drizzle goes quiet

The starter pushes and has no migration files, and it has no generated columns or PostGIS types, so it never meets what follows. The moment a project commits migrations, it can. Our team met these in client work in 2026: a deploy pre-check stopped because the migrations table held fewer rows than the journal had entries, and a reviewer noticed a generated migration with no CREATE INDEX for its GIN indexes. The third showed up when drizzle-kit push turned SRID 4326 columns into SRID 0 on development databases, and spatial tests failed with errors that did not point at the column type.

Each is reproduced below in a scratch project (drizzle-orm 0.44.7, drizzle-kit 0.31.11, postgres 3.4.9, the versions in the starter's lockfile). Traps A and C hold for drizzle-orm 0.45.4, the current npm latest on 2026-11-18, because the migrate function and the geometry file are unchanged from 0.44.7; trap B is drizzle-kit 0.31.11, also the current latest.

The trap runs used PostgreSQL 18.6 with PostGIS 3.7.0; traps A and B gave the same result again on PostgreSQL 17.11, the starter's image. We ran drizzle-orm 0.44.7 only and diffed the 0.45.4 source.

A migration dated before the newest one is skipped

migrate() keeps its state in drizzle.__drizzle_migrations (id SERIAL PRIMARY KEY, hash text NOT NULL, created_at bigint). It does not compare that table with your migration files. It reads one row, the newest by created_at, and runs every journal entry whose when (milliseconds, written to meta/_journal.json by drizzle-kit generate) is greater. This is the check in drizzle-orm 0.44.7, abridged (the table name and the surrounding transaction loop are cut):

const dbMigrations = await session.all(
  sql`select id, hash, created_at from ${...} order by created_at desc limit 1`
);
const lastDbMigration = dbMigrations[0];
...
if (!lastDbMigration || Number(lastDbMigration.created_at) < migration.folderMillis) {
  // run the statements, then insert (hash, created_at = folderMillis)
}

The migrator also writes a sha256 hash of each SQL file, and never compares it with anything. All pending entries run in one transaction.

We built a database from two migrations, 0000_first and 0001_second:

public tables: a, b
__drizzle_migrations: [{"id":1,"hash":"4f1a3cb04c08","created_at":"1794982262771"},{"id":2,"hash":"c35811f7acbf","created_at":"1794982264278"}]
journal when: [(0, '0000_first', 1794982262771), (1, '0001_second', 1794982264278)]

Then we generated a third migration, 0002_from_branch, containing CREATE TABLE "c", and set its when ten minutes before 0001. That reproduces a migration generated on a branch before another migration reached the database first. Migrate ran without an error:

0002 when changed 1794982275027 -> 1794981664278 (10 min before 0001 = 1794982264278 )
== step 2: migrate with 0002 dated before the last applied row
public tables: a, b
__drizzle_migrations: [{"id":1,...},{"id":2,...}]
exit=0

Exit code 0, no table c, no new row. The migration is skipped on every database that has applied a later one, while a database built from scratch would run it.

The mirror image is harmless, and that is what the deploy pre-check was tripping over. We deleted the row for 0000 and migrated again:

== step 3: delete the row for 0000, migrate again
public tables: a, b
__drizzle_migrations: [{"id":2,"hash":"c35811f7acbf","created_at":"1794982264278"}]
exit=0

Nothing re-ran; CREATE TABLE "a" would have failed on the existing table. A missing row costs nothing, while an old timestamp costs a migration. Giving 0002 a fresh when fixes the run:

0002 when -> 1794982275367
public tables: a, b, c
__drizzle_migrations: [{"id":2,...},{"id":3,"hash":"a0f4355d0ba8","created_at":"1794982275367"}]
exit=0

In the source of 1.0.0-beta.22 (read, never run) the table gains name and applied_at, the migrator selects all rows, and it runs the local migrations whose name is not in the table. Time order no longer decides there.

A generated column loses its index

The schema has a tsvector custom type and a search column generated from title, with a GIN index on it:

import { sql } from "drizzle-orm"
import { customType, index, pgTable, text } from "drizzle-orm/pg-core"
const tsvector = customType<{ data: string }>({ dataType: () => "tsvector" })
export const docs = pgTable(
  "docs",
  {
    id: text("id").primaryKey(),
    title: text("title").notNull(),
    search: tsvector("search").generatedAlwaysAs(sql`to_tsvector('english', title)`),
  },
  (t) => [index("docs_search_idx").using("gin", t.search)],
)

That is the second version. The first used to_tsvector('simple', title), and its migration, 0000_search.sql, creates the table and the index:

CREATE TABLE "docs" (
	"id" text PRIMARY KEY NOT NULL,
	"title" text NOT NULL,
	"search" "tsvector" GENERATED ALWAYS AS (to_tsvector('simple', title)) STORED
);
--> statement-breakpoint
CREATE INDEX "docs_search_idx" ON "docs" USING gin ("search");

We changed 'simple' to 'english' and nothing else, then ran generate. This is the whole new file, 0001_english.sql:

ALTER TABLE "docs" drop column "search";--> statement-breakpoint
ALTER TABLE "docs" ADD COLUMN "search" "tsvector" GENERATED ALWAYS AS (to_tsvector('english', title)) STORED;

PostgreSQL drops an index together with its column, and nothing in this file re-creates it. After applying it, only docs_pkey remained. The snapshot, 0001_snapshot.json, still lists docs_search_idx, so the next generate saw nothing to do:

docs 3 columns 1 indexes 0 fks
No schema changes, nothing to migrate 😴

We then loaded 5,000 rows plus one titled 'zebra crossing', ran analyze, and explained a search for to_tsquery('english','zebra'):

Seq Scan on docs  (cost=0.00..123.51 rows=1 width=4)
  Filter: (search @@ '''zebra'''::tsquery)

drizzle-kit push compares the schema with the live database, not with the snapshot, and it printed exactly the statement the migration lost:

 Warning  You are about to execute current statements:
CREATE INDEX "docs_search_idx" ON "docs" USING gin ("search");
[✓] Changes applied

With the index back, the same query plans as a bitmap index scan, and a second push said [i] No changes detected:

Bitmap Heap Scan on docs  (cost=4.12..5.24 rows=1 width=4)
  Recheck Cond: (search @@ '''zebra'''::tsquery)
  ->  Bitmap Index Scan on docs_search_idx  (cost=0.00..4.12 rows=1 width=0)

The fix is to add the missing statement to the generated file by hand before it is applied. Generate separates statements with --> statement-breakpoint and the migrator splits the file on it (migrator.js), so the generated second line gets a marker and the new statement goes last. With this as 0001_english.sql, a fresh database ended with both indexes, and generate still saw no changes:

ALTER TABLE "docs" drop column "search";--> statement-breakpoint
ALTER TABLE "docs" ADD COLUMN "search" "tsvector" GENERATED ALWAYS AS (to_tsvector('english', title)) STORED;--> statement-breakpoint
CREATE INDEX "docs_search_idx" ON "docs" USING gin ("search");

A database that already applied the original file needs a migration of its own. drizzle-kit generate --custom --name restore_search_index prepares an empty file holding one comment line, -- Custom SQL migration file, put your code below! --, with no newline after it. Our first, scripted append put the statement on that line, so it became part of the comment: migrate exited 0, recorded the migration as applied and created nothing. On its own line it worked:

-- Custom SQL migration file, put your code below! --
CREATE INDEX "docs_search_idx" ON "docs" USING gin ("search");

Migrate brought the index back, and generate again answered No schema changes, nothing to migrate.

geometry() accepts srid and ignores it

In geometry.js of drizzle-orm 0.44.7 (the file is identical in 0.45.4), the SQL type is a constant and the builder reads only the mode:

getSQLType() {
  return "geometry(point)";
}
...
mapToDriverValue(value) {
  return `point(${value.x} ${value.y})`;
}
...
function geometry(a, b) {
  const { name, config } = getColumnNameAndConfig(a, b);
  if (!config?.mode || config.mode === "tuple") {
    return new PgGeometryBuilder(name);
  }
  return new PgGeometryObjectBuilder(name);
}

The types still accept { mode, type, srid }, so srid: 4326 compiles and does nothing. We declared the column that way:

import { geometry, pgTable, text } from "drizzle-orm/pg-core"
export const stores = pgTable("stores", {
  id: text("id").primaryKey(),
  location: geometry("location", { type: "point", mode: "xy", srid: 4326 }).notNull(),
})

Generate wrote this file, and after migrating, geometry_columns reported stores|location|0|POINT, SRID 0:

CREATE TABLE "stores" (
	"id" text PRIMARY KEY NOT NULL,
	"location" geometry(point) NOT NULL
);

A geometry(point) column takes any SRID, so two writers can disagree without an error. We inserted one point by SQL with ST_SetSRID(ST_MakePoint(69.24, 41.31), 4326) and one through Drizzle as { x: 69.24, y: 41.31 }. The first row came out as SRID 4326 and the second as SRID 0. A distance query with a 4326 point then failed:

mixed-SRID query error: LWGEOM_dwithin: Operation on mixed SRID geometries (Point, 0) != (Point, 4326)

With a column that really is geometry(Point,4326), the write side is fine: a Drizzle insert came back as 4326, the column's own SRID. The damage comes from drizzle-kit push, which sees geometry(point) in the schema and wants the database to match. Against a hand-made 4326 column with the default config, it planned this and stopped to ask:

 Warning  You are about to execute current statements:
ALTER TABLE "spatial_ref_sys" DISABLE ROW LEVEL SECURITY;
DROP VIEW "public"."geography_columns";
DROP VIEW "public"."geometry_columns";
DROP TABLE "spatial_ref_sys" CASCADE;
ALTER TABLE "stores" ALTER COLUMN "location" SET DATA TYPE geometry(point);
 Warning  Found data-loss statements:
· You're about to delete spatial_ref_sys table with 8500 items
THIS ACTION WILL CAUSE DATA LOSS AND CANNOT BE REVERTED
Do you still want to push changes?

We did not confirm, and the column stayed 4326|POINT. Without a TTY the same push fails with Error: Interactive prompts require a TTY terminal. Setting extensionsFilters: ["postgis"] in drizzle.config.ts leaves PostGIS's own objects alone, and that is where it turns silent. The first push above ran against an empty table. For this one we had inserted a row through Drizzle (it came back as 4326), and the push ran with no prompt:

 Warning  You are about to execute current statements:
ALTER TABLE "stores" ALTER COLUMN "location" SET DATA TYPE geometry(point);
[✓] Changes applied

The column became SRID 0. The row already in it kept 4326, and the next Drizzle insert came back as after-push:0 before-push:4326, so the table now holds mixed SRIDs.

A custom type keeps the SRID in the DDL:

import { customType, pgTable, text } from "drizzle-orm/pg-core"

// drizzle-orm 0.44 and 0.45 drop the srid option of geometry(); a custom type keeps it in the DDL
const point4326 = customType<{ data: string }>({ dataType: () => "geometry(Point,4326)" })

export const stores = pgTable("stores", {
  id: text("id").primaryKey(),
  location: point4326("location").notNull(),
})

Generate writes "location" geometry(Point,4326) NOT NULL. Push against the 4326 column, with extensionsFilters: ["postgis"] set as above, answered [i] No changes detected, and the SRID stayed 4326. We did not run this column with the default config.

The price is that data is now a string, so the { x, y } mapping of mode: "xy" is gone. We tested three ways to write through Drizzle: plain WKT "POINT(69.24 41.31)", which was stored as 4326; EWKT "SRID=4326;POINT(69.24 41.31)"; and an SQL expression, sql`ST_SetSRID(ST_MakePoint(69.24, 41.31), 4326)`. All three stored SRID 4326 and all three matched ST_DWithin against a 4326 point. A value carrying another SRID was rejected:

ewkt-3857 insert error: Failed query: insert into "stores" ("id", "location") values ($1, $2)
params: ewkt-3857,SRID=3857;POINT(1 2)
srid per row: ewkt:4326:POINT(69.24 41.31) | plain-wkt:4326:POINT(69.24 41.31) | sql:4326:POINT(69.24 41.31)
ST_DWithin rows: ewkt, plain-wkt, sql

Reads come back as hex EWKB strings, "0101000020E6100000...", so coordinates come out through SQL with ST_AsText or ST_X and ST_Y.

In the source of 1.0.0-beta.22, getSQLType() returns geometry(point,<srid>) when srid is set. Values are still written as point(x y) there.

Two checks to run in CI

Two small checks cover two of the three traps: one reads the journal, the other asks drizzle-kit whether the committed files build the schema you wrote. The third slips past both.

Trap Guard Needs a database Notes
A: older migration skipped check-journal.ts No Run it on the merged journal (and again on main); on a branch alone it can pass.
B: index lost with its column check-drift.sh Yes, a scratch one only push applies what it prints.
C: srid missing from the DDL Neither The SRID is missing from both the files and the schema as drizzle-kit reads it; the customType workaround keeps the SRID, at the cost of the { x, y } mapping.

check-journal.ts takes the journal path (default drizzle/meta/_journal.json) and fails when an entry's when is not after the previous entry's:

// Fails when a journal entry is not newer than the one before it.
// drizzle-orm 0.44/0.45 skip such an entry on every database that already applied a later one.
const path = process.argv[2] ?? "drizzle/meta/_journal.json"
const { entries } = (await Bun.file(path).json()) as { entries: { tag: string; when: number }[] }

let previous = 0
for (const entry of entries) {
  if (entry.when <= previous) {
    console.error(`${entry.tag}: when ${entry.when} is not after the previous entry's ${previous}`)
    process.exit(1)
  }
  previous = entry.when
}
console.log(`${entries.length} entries, timestamps in order`)

That is enough when the journal only grows at the end: if timestamps increase in file order, every entry appended after the last deployed one is newer than that deployment's newest row. The check compares entries with each other, not with a deployed database, so it cannot see an entry that a merge placed before one that is already deployed.

On the in-order journal it printed 3 entries, timestamps in order and exited 0. On the journal with 0002 re-dated:

0002_from_branch: when 1794981664278 is not after the previous entry's 1794982264278

That run exited 1.

check-drift.sh is for trap B. Point DATABASE_URL at a scratch database that migrate has just built from the committed files, then run it:

#!/usr/bin/env sh
# Point DATABASE_URL at a scratch database that `migrate` has just built from the
# committed files. If drizzle-kit push still wants to change something, the files
# do not produce the schema in schema.ts.
out=$(bunx drizzle-kit push --verbose 2>&1)
if echo "$out" | grep -q "No changes detected"; then
  echo "migrations match schema.ts"
  exit 0
fi
echo "$out" | grep -v -E "^\s*$"
echo "migrations do not match schema.ts"
exit 1

On a database migrated from trap B's two files it printed the missing statement and failed:

 Warning  You are about to execute current statements:
CREATE INDEX "docs_search_idx" ON "docs" USING gin ("search");
[✓] Changes applied
migrations do not match schema.ts
exit=1

A second run on the same database printed migrations match schema.ts and exited 0. Push had applied the index during the first run, which is why this check belongs on a scratch database and never on one you care about.

We ran it on a database without PostGIS. On a PostGIS database, set extensionsFilters: ["postgis"] first: with the default config push plans the spatial_ref_sys drop from trap C and, without a TTY, errors out, so the check would fail for a reason that has nothing to do with your migrations.

FAQ

Does Drizzle work with Bun and Elysia?

Yes, on the versions we ran: Bun 1.4.4 with the starter's lockfile versions (elysia 1.4.16, drizzle-orm 0.44.7, postgres-js 3.4.9, better-auth 1.7.10), and a fresh clone passes 6 tests and typechecks in all three packages. We only ran postgres-js, so we have nothing to say about other drivers.

Should I run drizzle-kit push against production?

Our team stopped doing it. push applies the statements it prints whenever no prompt is needed, and trap C shows what it can plan against a PostGIS database: with the default config, a DROP TABLE "spatial_ref_sys" CASCADE and a confirmation prompt; with extensionsFilters: ["postgis"], a silent SET DATA TYPE geometry(point) that turns a 4326 column into SRID 0. We apply reviewed DDL instead.

Does the Drizzle 1.0 beta fix these?

Partly, going by the source of 1.0.0-beta.22, which we read and never ran. For trap A, the migrator tracks migrations by name, so ordering by time no longer decides. For trap C, getSQLType() emits geometry(point,<srid>) when srid is set, though values are still written as point(x y). We did not check trap B in the beta.

Get the starter

bun-elysia-nextjs-starter is MIT-licensed and free to fork. If you would rather buy a base than assemble one, ShipKit is the paid kit from our team on the same stack. The starter's HEAD at the time of writing is f959168, committed on 2026-11-02.