← Back to dashboard
local-databasedatabasefreshReader view (for NotebookLM)

Local Databases (WSL + Docker) Guide

What is a local database?

The real model

A disposable copy of production's shape, never a place to relax production's rules. Pin everything.

Two version traps define October 2026. `npm install prisma` now pulls the Prisma 8 RC (8.0.0-rc.23), whose CLI ignores `schema.prisma` and has no `generate` or `migrate dev`, so pin `prisma@7` (7.10.1) alongside `@prisma/client@7`. Prisma 7 also needs a driver adapter (`PrismaPg`), reads its URL from `prisma.config.ts`, doesn't load `.env` on its own, and no longer auto-runs `generate` or the seed. Drizzle's docs install `@rc` (1.0.0-rc.4) while npm `latest` is 0.45.4. On images, `mongo:latest` jumped to 9.0.4 and `mariadb:latest` to 13.0.2 (non-LTS), and Postgres 18 mounts at `/var/lib/postgresql` while 17 and below need `/data`; get that backwards and data silently vanishes on re-create. PGlite's pgvector now comes from `@electric-sql/pglite-pgvector`, and PGlite runs as a superuser, so RLS tests belong in the container or `supabase start`. For codeAmani: tests on PGlite, daily dev on the container, Neon Local for prod-shaped checks, and for Kenya-targeted users on 2G/3G a device-side SQLite outbox or PowerSync, never trusting the client with payment state.

Seven moving parts of a local database setup

Pick the mirror by what you need to exercise, then pin it, persist it, and keep one migration history across all of them.

Text
██╗      ██████╗  ██████╗ █████╗ ██╗
██║     ██╔═══██╗██╔════╝██╔══██╗██║
██║     ██║   ██║██║     ███████║██║
██║     ██║   ██║██║     ██╔══██║██║
███████╗╚██████╔╝╚██████╗██║  ██║███████╗
╚══════╝ ╚═════╝  ╚═════╝╚═╝  ╚═╝╚══════╝

██████╗  █████╗ ████████╗ █████╗ ██████╗  █████╗ ███████╗███████╗
██╔══██╗██╔══██╗╚══██╔══╝██╔══██╗██╔══██╗██╔══██╗██╔════╝██╔════╝
██║  ██║███████║   ██║   ███████║██████╔╝███████║███████╗█████╗
██║  ██║██╔══██║   ██║   ██╔══██║██╔══██╗██╔══██║╚════██║██╔══╝
██████╔╝██║  ██║   ██║   ██║  ██║██████╔╝██║  ██║███████║███████╗
╚═════╝ ╚═╝  ╚═╝   ╚═╝   ╚═╝  ╚═╝╚═════╝ ╚═╝  ╚═╝╚══════╝╚══════╝

Local Databases (WSL + Docker) Guide

Focus: Every way codeAmani runs a database on a laptop: pinned Docker containers inside WSL Ubuntu (Postgres + pgvector, Redis, MongoDB, MySQL/MariaDB) with one compose.yaml; the Supabase CLI local stack; Neon Local; PGlite (in-process Postgres for tests); the SQLite family (node:sqlite, better-sqlite3, Turso); Prisma 7 / Drizzle migrations and seeding against all of them; and offline-first sync (PowerSync, Electric, Zero, Turso Sync) for low-connectivity users. Image tags checked against Docker Hub and package versions against npm on 2026-10-20.

Overview

codeAmani ships production data to [[supabase]] (Postgres + RLS) or [[neon]] (serverless Postgres with branching). Neither is a good place to try a migration you're unsure about at 2am on hotel Wi-Fi. A local database is the mirror: same engine, same major version, same extensions, zero network, zero bill, and a two-second reset.

Pick the mirror by what you need to exercise:

You need…UsePostgres versionNeeds DockerWorks offline
Plain Postgres (+ pgvector, RLS) for app devDocker container (§3–4)18.6✅✅
Supabase Auth / Storage / Realtime / Edge Functions locallySupabase CLI supabase start (§5)Supabase's image✅ (or experimental native runtime on Linux/macOS)✅
A real Neon branch, per git branch or per docker compose upNeon Local proxy (§6)your Neon project's✅❌ (proxies to cloud)
Fast, isolated DB per unit test; browser/demo DBPGlite (§7)18.6 (WASM)❌✅
On-device store, CLI tools, offline queueSQLite: node:sqlite / better-sqlite3 / Turso (§8)—❌✅
App keeps working for days offline, syncs laterSync engine: PowerSync / Electric / Zero / Turso Sync (§11)upstream Postgresfor the sync service✅
Redis / MongoDB / MySQL stand-insDocker container (§3)—✅✅
Local containerSupabase CLINeon LocalPGlite
CostfreefreeNeon compute time on the branchfree
Reset to emptycompose down -v (~2 s)supabase db resetstop container (ephemeral branch deleted)new instance (~ms)
RLS + pgvector✅✅✅✅ (@electric-sql/pglite-pgvector)
Auth / Storage / Realtime❌✅❌ (Neon Auth lives in the cloud)❌
Where the data livesDocker named volumeDocker volumesNeon cloudmemory, a directory, or IndexedDB

Official Documentation

Versions verified 2026-10-20

ThingPinNotes
postgres image18.6-trixie (latest == 18.6)19rc1 and 19beta4 tags exist; don't pin pre-releases
pgvector/pgvector0.8.7-pg18-trixiepgvector 0.8.7 (was 0.8.6)
redis8.10.2-alpine (latest == 8.10.2)
mongo8.0.34-noblemongo:latest is now 9.0.4; pin the major your Atlas cluster runs
mysql9.7.2 (lts)latest == innovation == 26.7.0 (calendar versioning)
mariadb12.3.3 (lts)mariadb:latest is now 13.0.2 (not LTS)
neondatabase/neon_localv1.5 (== latest, built 2025-09-25)
Node.js24 LTS (tested on 24.15.0)node:sqlite = Stability 1.2 Release candidate since v24.15.0
@electric-sql/pglite0.5.10embeds PostgreSQL 18.6; pgvector via @electric-sql/pglite-pgvector 0.0.11
prisma / @prisma/client7.10.1npm latest for prisma is 8.0.0-rc.23 — see §9
drizzle-orm / drizzle-kit0.45.4 / 0.31.11rc tag = 1.0.0-rc.4; Drizzle's docs install @rc
supabase (CLI, npm)2.121.0Node ≥ 20 when run via npx
neonctl8.8.0
better-sqlite313.0.3
@tursodatabase/database / @tursodatabase/sync0.8.3 / 0.8.3Turso Sync is beta
@libsql/client0.18.0embedded replicas
pg / postgres / mysql2 / ioredis / mongodb8.23.1 / 3.4.9 / 3.24.6 / 6.0.0 / 7.7.0

1. Get a Docker daemon inside WSL Ubuntu

Two supported paths. Pick one, and do not run both.

Install Docker Desktop, then Settings → Resources → WSL integration → enable your Ubuntu distro. docker and docker compose then work inside Ubuntu, and published ports land on Windows localhost. See the [[docker]] guide.

Path B: Docker Engine straight into Ubuntu (no Desktop)

Inside the WSL Ubuntu shell (commands re-checked against docs.docker.com/engine/install/ubuntu/ on 2026-10-20; supported: Ubuntu 22.04, 24.04, 26.04 LTS and 26.10):

Bash
# 1. Docker's official GPG key
sudo apt update
sudo apt install ca-certificates curl
sudo install -m 0755 -d /etc/apt/keyrings
sudo curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc
sudo chmod a+r /etc/apt/keyrings/docker.asc

# 2. Add the repository to Apt sources
sudo tee /etc/apt/sources.list.d/docker.sources <<EOF
Types: deb
URIs: https://download.docker.com/linux/ubuntu
Suites: $(. /etc/os-release && echo "${UBUNTU_CODENAME:-$VERSION_CODENAME}")
Components: stable
Architectures: $(dpkg --print-architecture)
Signed-By: /etc/apt/keyrings/docker.asc
EOF
sudo apt update

# 3. Install engine + CLI + compose plugin
sudo apt install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin

# 4. Run docker without sudo (then `wsl --shutdown` to pick up the group)
sudo usermod -aG docker $USER

# 5. Verify
docker run --rm hello-world
docker compose version

Enable systemd once so the daemon starts with the distro:

Bash
sudo tee /etc/wsl.conf <<'EOF'
[boot]
systemd=true
EOF
# then from PowerShell on the host:  wsl --shutdown

Without systemd, start the daemon each session with sudo service docker start.

Filesystem rule (same as [[docker]]): keep the project on the Linux filesystem (~/code/...), never /mnt/c/.... A database data directory bind-mounted from /mnt/c crosses the 9p boundary on every fsync. Named volumes live on the WSL VM's ext4 disk and avoid it.


2. Environment variables

One .env.local per app (gitignored), one .env next to compose.yaml for Compose interpolation (also gitignored). Only real secrets go on VAR= lines; even local dev passwords are treated as secrets so the habit protects the production string that later lives in the same file.

Bash
# .env / .env.local: local only, never committed
POSTGRES_PASSWORD=<dev-only-password>
DATABASE_URL=postgresql://app:<dev-only-password>@localhost:5432/appdb
# Only if you use Neon Local (§6): a real Neon API key, store it in Hazina
NEON_API_KEY=napi_...
# Only if you use Turso Sync / embedded replicas (§8)
TURSO_AUTH_TOKEN=...

Non-secret settings:

VariableExampleUsed by
REDIS_URLredis://localhost:6379ioredis
NEON_PROJECT_ID<project-id>Neon Local
PARENT_BRANCH_ID / BRANCH_IDbr-...Neon Local (mutually exclusive)
DELETE_BRANCHfalse to keep the branch after the container stopsNeon Local
TURSO_DATABASE_URLlibsql://<db>-<org>.turso.ioTurso
SUPABASE_TELEMETRY_DISABLED1Supabase CLI
Supabase local DB URLpostgresql://postgres:postgres@127.0.0.1:54322/postgresprinted by supabase start; fixed well-known local creds

3. docker run one-liners (pinned tags)

Pin the minor version. latest moves: on 2026-10-20 mongo:latest jumped to 9.0 and mariadb:latest to 13.0, and a Postgres major bump silently invalidates the data directory.

Postgres 18 (+ pgvector)

Bash
docker run -d --name pg \
  -e POSTGRES_USER=app \
  -e POSTGRES_PASSWORD="$POSTGRES_PASSWORD" \
  -e POSTGRES_DB=appdb \
  -p 127.0.0.1:5432:5432 \
  -v pgdata:/var/lib/postgresql \
  pgvector/pgvector:0.8.7-pg18-trixie      # or postgres:18.6-trixie without pgvector

⚠️ Postgres 18 changed the volume target. For 18+ the image sets PGDATA=/var/lib/postgresql/18/docker and declares VOLUME /var/lib/postgresql. For 17 and below mount at /var/lib/postgresql/data; mounting 17 at the bare path writes to an anonymous volume and your data vanishes on re-create, silently.

Bash
# Postgres 17 and below: note the /data suffix
docker run -d --name pg17 -e POSTGRES_PASSWORD="$POSTGRES_PASSWORD" \
  -p 127.0.0.1:5432:5432 -v pg17data:/var/lib/postgresql/data postgres:17.11-trixie

The pgvector image ships the extension but your database still needs CREATE EXTENSION IF NOT EXISTS vector;, exactly like Supabase and Neon.

MySQL 9.7 LTS / MariaDB 12.3 LTS

Bash
docker run -d --name mysql -e MYSQL_ROOT_PASSWORD="$POSTGRES_PASSWORD" -e MYSQL_DATABASE=appdb \
  -p 127.0.0.1:3306:3306 -v mysqldata:/var/lib/mysql mysql:9.7.2

docker run -d --name mariadb -e MARIADB_ROOT_PASSWORD="$POSTGRES_PASSWORD" -e MARIADB_DATABASE=appdb \
  -p 127.0.0.1:3306:3306 -v mariadbdata:/var/lib/mysql mariadb:12.3.3

mysql:latest follows the Innovation track (calendar versioning, 26.7.0 = YY.M.P). mariadb:lts is 12.3.3; mariadb:latest is the short-term 13.0.2. MariaDB env vars are MARIADB_* (MYSQL_* are legacy aliases).

Redis 8

Bash
docker run -d --name redis -p 127.0.0.1:6379:6379 -v redisdata:/data \
  redis:8.10.2-alpine redis-server --save 60 1 --appendonly yes --loglevel warning

Redis persists nothing and has no password by default; the flags above turn on RDB snapshots + AOF. This is the local stand-in for [[upstash]]; see [[caching]].

MongoDB 8.0 (single-node replica set)

Bash
docker run -d --name mongo -p 127.0.0.1:27017:27017 -v mongodata:/data/db \
  mongo:8.0.34-noble --replSet rs0 --bind_ip_all
docker exec -it mongo mongosh --eval 'rs.initiate({_id:"rs0",members:[{_id:0,host:"localhost:27017"}]})'
# mongodb://localhost:27017/appdb?replicaSet=rs0&directConnection=true

Transactions and change streams need a replica set even locally. mongo:latest is now 9.0.4: match your Atlas cluster's major instead of following latest. See [[mongodb]].

Why 127.0.0.1:PORT:PORT

-p 5432:5432 binds 0.0.0.0 inside the WSL VM. With mirrored networking, a netsh portproxy, or a café network, that is a database with a dev password answering the LAN. -p 127.0.0.1:5432:5432 costs nothing. Make it the default.


4. The whole local stack: compose.yaml

The runnable file is examples/compose.yaml: pgvector-Postgres 18.6 + Redis 8.10.2, an opt-in Mongo profile, healthchecks, named volumes, loopback-only ports, and ${POSTGRES_PASSWORD:?} interpolation so no password is committed. The core:

YAML
name: appdb-local            # no top-level `version:` key: obsolete, Compose warns
services:
  postgres:
    image: pgvector/pgvector:0.8.7-pg18-trixie
    environment:
      POSTGRES_USER: app
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in .env}
      POSTGRES_DB: appdb
    ports: ["127.0.0.1:5432:5432"]
    volumes:
      - pgdata:/var/lib/postgresql              # pg18+ target, NOT /data
      - ./db/init:/docker-entrypoint-initdb.d:ro
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U app -d appdb"]
      interval: 5s
      retries: 10
      start_period: 20s
volumes:
  pgdata:
Bash
docker compose up -d && docker compose ps     # STATUS shows (healthy)
docker compose exec postgres psql -U app -d appdb
docker compose --profile mongo up -d          # add Mongo when the project needs it

An app service must wait for a healthy DB (depends_on: {postgres: {condition: service_healthy}}); the short list form only waits for started. Inside the Compose network use the service name + container port (postgres:5432); from the Windows host use localhost:5432.

Seeding with /docker-entrypoint-initdb.d

Scripts run in alphabetical order only on first init of an empty data directory (Postgres: .sh, .sql, .sql.gz/.xz/.zst; Mongo: .sh, .js).

SQL
-- db/init/001_schema.sql
CREATE EXTENSION IF NOT EXISTS vector;

CREATE TABLE deliveries (
  id          uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  tenant_id   uuid NOT NULL,
  rider_phone text NOT NULL CHECK (rider_phone ~ '^254[0-9]{9}$'),
  fare_kes    integer NOT NULL CHECK (fare_kes > 0),
  created_at  timestamptz NOT NULL DEFAULT now()
);

-- Mirror production: RLS on locally too.
ALTER TABLE deliveries ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON deliveries
  USING (tenant_id = current_setting('app.tenant_id', true)::uuid);

Once a project has real migrations (Prisma/Drizzle/Supabase, §5 and §9), keep db/init to extensions only and let the migration tool own the schema, so there is one source of truth.


5. Supabase CLI local stack

When the feature touches Supabase Auth, Storage, Realtime, PostgREST or Edge Functions, a bare Postgres container is not enough. The Supabase CLI runs the whole stack in Docker.

Bash
npm install supabase@2.121.0 --save-dev     # pin per project; Windows alt: scoop install supabase
npx supabase init                           # creates ./supabase (commit it) + config.toml
npx supabase start                          # first run pulls every image; slow once

supabase start prints the local endpoints. The defaults:

ServiceURL
API gateway (REST, Auth, Storage, Realtime, Functions)http://127.0.0.1:54321
Postgrespostgresql://postgres:postgres@127.0.0.1:54322/postgres
Studiohttp://127.0.0.1:54323
Mailpit (captured auth emails)http://127.0.0.1:54324
Local MCP endpointhttp://127.0.0.1:54321/mcp

Keys print as sb_publishable_... / sb_secret_...; they are local-only but the secret key still never goes in client code.

The migration loop:

Bash
npx supabase migration new add_deliveries     # writes supabase/migrations/<ts>_add_deliveries.sql
npx supabase db reset                         # re-create local DB: all migrations + supabase/seed.sql
npx supabase db diff --schema public -f fix   # capture changes made in Studio as a migration
npx supabase gen types typescript --local > lib/database.types.ts
npx supabase stop                             # keeps data; `stop --no-backup` deletes it
# Ship: npx supabase link --project-ref <ref> && npx supabase db push
  • One supabase start per machine on default ports; for worktrees or two projects, change ports per Supabase's "Running multiple local projects" guide.
  • In a CI runner or agent sandbox without Docker, Supabase documents an experimental native runtime (Linux, macOS on Apple silicon). Not for Windows/WSL day-to-day.
  • Before upgrading the CLI: db diff -f, db dump --local --data-only > supabase/seed.sql, then stop --no-backup, per the docs.
  • From a local Edge Function, reach the DB at host.docker.internal, not localhost.

Full Supabase detail lives in [[supabase]].


6. Neon Local

Neon Local is not a local Postgres. It is a proxy container that gives your app a localhost:5432 endpoint and routes it to a Neon cloud branch, either an existing one (BRANCH_ID) or an ephemeral branch created on container start and deleted on stop (PARENT_BRANCH_ID, the default behaviour).

YAML
# compose.override.yaml: Neon Local instead of the local Postgres container
services:
  db:
    image: neondatabase/neon_local:v1.5
    ports: ["127.0.0.1:5432:5432"]
    environment:
      NEON_API_KEY: ${NEON_API_KEY}
      NEON_PROJECT_ID: ${NEON_PROJECT_ID}
      PARENT_BRANCH_ID: ${PARENT_BRANCH_ID}   # omit → branch from the default branch
      # DELETE_BRANCH: "false"                # keep it after `down`
    # Persistent branch per git branch:
    # volumes:
    #   - ./.neon_local/:/tmp/.neon_local      # add .neon_local/ to .gitignore
    #   - ./.git/HEAD:/tmp/.git/HEAD:ro,consistent

Connect with postgres://neon:npg@localhost:5432/<db>?sslmode=require. The proxy uses a self-signed certificate, so pg/postgres.js need ssl: { rejectUnauthorized: false } for this localhost proxy only; never copy that into the production config. The Neon serverless driver works over HTTP only:

TypeScript
import { neon, neonConfig } from "@neondatabase/serverless"; // 1.2.0

neonConfig.fetchEndpoint = "http://localhost:5432/sql";
neonConfig.useSecureWebSocket = false;
neonConfig.poolQueryViaFetch = true;
const sql = neon("postgres://neon:npg@localhost:5432/neondb");

Use it when the thing under test depends on Neon itself (branch data, Neon extensions, prod-sized data). It needs the network and bills compute, so it is not the offline story. neonctl 8.8.0 (npx neonctl branches create, connection-string) covers scripted branches; see [[neon]].


7. PGlite: Postgres 18.6 inside your process

@electric-sql/pglite 0.5.10 is real Postgres (18.6 at this version, confirmed with SELECT version()) compiled to WASM. No Docker, no port, starts in milliseconds, one fresh database per test.

TypeScript
import { PGlite } from "@electric-sql/pglite";
import { vector } from "@electric-sql/pglite-pgvector"; // separate package now

const mem = await PGlite.create({ extensions: { vector } });              // memory://
const disk = await PGlite.create("./.pglite/dev", { extensions: { vector } }); // Node: directory
// Browser: new PGlite("idb://my-app")  (IndexedDB)
await mem.exec("CREATE EXTENSION IF NOT EXISTS vector;");
const { rows } = await mem.query<{ v: string }>("SELECT version() AS v");
  • pgvector moved to @electric-sql/pglite-pgvector (0.0.11, peer @electric-sql/pglite 0.5.10). Older guides import from @electric-sql/pglite/vector. Bundled extensions also include pg_trgm, pgcrypto, uuid-ossp, hstore, ltree, citext, PostGIS, pg_uuidv7, pgtap and more (see pglite.dev/extensions).
  • Drizzle: drizzle({ client }) from drizzle-orm/pglite, plus migrate(db, { migrationsFolder }) from drizzle-orm/pglite/migrator. Runnable example: examples/pglite-drizzle.test-db.mts.
  • Prisma: there is no first-party PGlite adapter (@prisma/adapter-pglite does not exist on npm). A community pglite-prisma-adapter (0.7.2) exists; it is unvetted, so prefer Drizzle for PGlite tests or run @electric-sql/pglite-socket (0.2.13) and point the normal pg adapter at it.
  • PGlite is single-connection and single-user. It is a test/demo/offline-client database, not a replacement for the server.

8. SQLite family: node:sqlite, better-sqlite3, Turso

SQLite is the right store on the device: CLI tools, kiosk/POS terminals, desktop apps, mobile caches, and the outbox of an offline-first app.

node:sqlite (built into Node)

Node lineStatus
v22.13.0 / v23.4.0unflagged (no --experimental-sqlite), still experimental
v24.15.0 (current LTS line)Stability 1.2: Release candidate

Tested on Node 24.15.0 (SQLite 3.51.3), no warning printed. Synchronous API: new DatabaseSync(path, { enableForeignKeyConstraints, timeout, readBigInts, ... }), db.exec(), db.prepare() → run/get/all/iterate, plus sqlite.backup() (async) and session/changeset APIs (createSession, applyChangeset). Runnable offline outbox: examples/offline-outbox.mts (zero dependencies).

codeAmani rule: node:sqlite is fine for local tools, scripts, kiosks and test fixtures. For a long-running production server keep better-sqlite3 13.0.3 (stable, native addon) until node:sqlite reaches Stability 2.

Turso / libSQL

PackageUse
@tursodatabase/database 0.8.3local/embedded Turso Database (the Rust SQLite rewrite); connect("local.db")
@tursodatabase/sync 0.8.3local-first reads and writes with explicit push() / pull() to Turso Cloud (beta)
@libsql/client 0.18.0libSQL client; embedded replicas (local reads, writes go to the cloud primary, client.sync())

Turso's own guidance: if a local database is involved, use the @tursodatabase/* packages; for offline writes and multi-writer convergence, @tursodatabase/sync. Drizzle support for @tursodatabase/database is beta.


9. ORMs: migrations and seeding locally

Prisma ORM 7 (pin it)

⚠️ npm install prisma / npx prisma now install the Prisma 8 release candidate (prisma npm latest = 8.0.0-rc.23, docs default to v8). The v8 CLI does not read schema.prisma and has no generate, migrate dev or db push. Prisma 8 is RC (GA expected October 2026), PostgreSQL-only at RC quality (SQLite experimental, MySQL "coming soon"), and lacks $extends, most nested writes and isolation levels. Stay on 7: "prisma": "^7" and "@prisma/client": "^7" (both 7.10.1 today), and write npx prisma@7 in CI. Prisma 7 gets fixes for 18 months after v8 GA; Prisma 6 security patches end 2026-11-19.

Prisma 7 changes that bite in local dev (all from the v7 upgrade guide):

  • Driver adapter required for every database: new PrismaClient({ adapter: new PrismaPg({ connectionString }) }); SQLite uses @prisma/adapter-better-sqlite3. Pool settings now come from the driver: pg has no connect timeout by default (v6 used 5 s), so set connectionTimeoutMillis.
  • prisma.config.ts holds the datasource URL, schema path, migrations path and seed command. url/directUrl in schema.prisma are deprecated; put the direct URL in the config, because the CLI uses it for migrations.
  • Env vars are not auto-loaded: import "dotenv/config" in prisma.config.ts.
  • Generator provider = "prisma-client" with a required output; import from the generated path, not @prisma/client. Ships as ESM ("type": "module"); Node ≥ 20.19, TS ≥ 5.4.
  • migrate dev / db push no longer run generate or the seed: run prisma generate and prisma db seed yourself. --skip-generate / --skip-seed are gone.
  • SSL is now validated (node-pg). A local container has no TLS, so don't pass sslmode=require to localhost.

Runnable: examples/prisma7/ (schema.prisma, prisma.config.ts, src/db.ts, prisma/seed.ts; type-checked against 7.10.1).

Bash
npm i @prisma/client@7.10.1 @prisma/adapter-pg@7.10.1 dotenv && npm i -D prisma@7.10.1 tsx
npx prisma@7 migrate dev --name init   # create + apply migration to the local DB
npx prisma@7 generate                  # no longer implicit
npx prisma@7 db seed                   # no longer implicit
npx prisma@7 migrate reset             # drop + re-apply (local only)

Drizzle ORM

npm latest is 0.45.4 (drizzle-kit 0.31.11). Drizzle's get-started pages now install drizzle-orm@rc / drizzle-kit@rc (1.0.0-rc.4, published 2026-06-27; the roadmap shows v1 at "98%"). codeAmani pins 0.45.4 for app code until 1.0 is tagged latest; trying the RC on a branch is fine.

TypeScript
// drizzle.config.ts
import "dotenv/config";
import { defineConfig } from "drizzle-kit";

export default defineConfig({
  out: "./drizzle",
  schema: "./src/db/schema.ts",
  dialect: "postgresql",
  dbCredentials: { url: process.env.DATABASE_URL! },
});
Bash
npx drizzle-kit generate   # SQL migration files from schema diffs (commit them)
npx drizzle-kit migrate    # apply to DATABASE_URL
npx drizzle-kit push       # prototype only: sync schema without migration files
npx drizzle-kit studio     # local data browser

The same schema runs on drizzle-orm/node-postgres (container/Supabase/Neon Local), drizzle-orm/pglite (tests) and drizzle-orm/neon-http (prod). drizzle-seed (0.3.1) generates deterministic fake rows.

Seeding rules (any tool)

  1. Seeds are deterministic and idempotent (fixed UUIDs, deleteMany / ON CONFLICT DO NOTHING), so reset → seed is repeatable.
  2. Seeds use realistic formats: integer KES, 254XXXXXXXXX phones, Africa/Nairobi timestamps for Kenya-targeted projects; ZIP codes and USD cents for US projects.
  3. Seeds never contain production data or real customer phone numbers. Use Daraja's sandbox test number 254708374149 and obviously fake ranges.

10. Connecting from the Windows host and Next.js

WSL 2's default NAT mode forwards published ports to Windows localhost, so psql, TablePlus, DBeaver, Prisma/Drizzle Studio and a host-side next dev all reach localhost:5432. Docker Desktop does the same through its proxy.

PowerShell
psql "postgresql://app:<dev-only-password>@localhost:5432/appdb"
wsl.exe hostname -I        # distro IP, rarely needed in NAT mode

Windows 11 22H2+ mirrored mode ([wsl2] networkingMode=mirrored in %UserProfile%\.wslconfig, then wsl --shutdown) shares one loopback both ways, and also makes WSL reachable from the LAN, which is why every -p above starts with 127.0.0.1:.

Use a pooled client held on globalThis so Next.js HMR doesn't open a new pool per reload, and parameterized queries only. Runnable: examples/db.ts (pg 8.23.1, getDeliveries, and withTenant() that sets app.tenant_id with set_config(..., true) inside a transaction so RLS behaves as on Supabase). TLS is decided from the parsed hostname: off for localhost/127.0.0.1, verified everywhere else.


11. Offline-first sync (low-connectivity users)

A local dev database helps the developer. A local client database helps the user whose connection drops. Pattern: the app reads and writes a database on the device (SQLite, PGlite or IndexedDB), and a sync layer reconciles with Postgres when the uplink returns.

EngineModelWritesStatus (2026-10-20)Notes
PowerSyncPostgres / MongoDB / MySQL → client SQLiteLocal first → upload queue → your backend API validatesPostgres GA; Open Edition (self-host) GASDKs @powersync/web 2.5.0, @powersync/react-native 2.3.3, @powersync/node 1.2.0; Supabase integration guide; "Sync Streams" config
ElectricPostgres → shapes streamed over HTTPRead-path only: writes go through your APIOpen source; Electric Cloud managed@electric-sql/client 1.5.28; pairs with PGlite via @electric-sql/pglite-sync 0.6.11
Zero (Rocicorp)Postgres → zero-cache (SQLite replica) → clientCustom mutators via your /mutate endpoint1.x (@rocicorp/zero 1.11.0; docs show rocicorp/zero:1.10.0 image)Needs wal_level=logical and a direct (non-pgbouncer) upstream connection
Turso SyncTurso Cloud ↔ local Turso DBLocal reads and writes, explicit push()/pull()Beta@tursodatabase/sync 0.8.3; SQLite-shaped, not Postgres
DIY outboxAnyLocal SQLite outbox + idempotency key, flush on reconnect—examples/offline-outbox.mts; enough for "queue orders while offline"

Decision rule: if you only need "don't lose the user's action while offline", the DIY outbox is enough. If users need to read and edit shared data for hours offline, use PowerSync (writes-through-your-API matches codeAmani's "server validates everything" rule). Electric is the read-heavy choice. Zero is the reactive-UI choice when you are online most of the time. Pricing for the hosted tiers was not verified in this refresh: check each vendor's pricing page before committing.


12. Teardown, reset, inspection

Bash
docker compose stop                  # pause; data survives
docker compose down                  # remove containers + network; volumes SURVIVE
docker compose down -v               # remove volumes too: the true reset (re-runs db/init)
docker compose up -d --force-recreate --pull always

docker volume ls && docker system df
docker system prune -a --volumes     # nuclear: everything unused, all projects

# Back up / restore a local Postgres
docker compose exec -T postgres pg_dump -U app -d appdb > backup.sql
docker compose exec -T postgres psql -U app -d appdb < backup.sql

npx supabase db reset                # Supabase CLI equivalent of down -v + migrate + seed
npx prisma@7 migrate reset           # Prisma equivalent against DATABASE_URL

13. Picking the store


codeAmani notes

  • The local mirror copies production's shape, never relaxes its rules. Enable RLS locally exactly as Supabase has it. A policy only added in production is a policy nobody has tested.
  • POSTGRES_HOST_AUTH_METHOD=trust never leaves your machine, and neither does -p 0.0.0.0:.... The image docs: trust "allows anyone to connect without a password, even if one is set." Grep for both before every push; the [[supply-chain]] and SECURITY.md checklists cover the same ground.
  • Dev credentials are still credentials. .env/.env.local are gitignored; compose files use ${POSTGRES_PASSWORD:?} interpolation; production strings and NEON_API_KEY / TURSO_AUTH_TOKEN live in Hazina. ssl: { rejectUnauthorized: false } is acceptable only for the Neon Local proxy on localhost.
  • Pin, don't float. Image minors (postgres:18.6, not latest), prisma@7 (not bare prisma, which is now v8 RC), drizzle-orm@0.45.4 (not @rc) unless a branch is deliberately evaluating the RC. Record the bump in the project's changelog.
  • Parameterized queries, pooled connections. $1 placeholders, pool.query, client.release() in finally, a connect timeout set explicitly. Local Postgres tolerates leaked connections; Supabase's pooler and Neon's compute do not.
  • Tests run on PGlite, not on a shared dev DB. One in-process Postgres 18.6 per test file means no flaky cross-test state and no Docker in CI for the fast suite. Keep a smaller integration suite against the container or supabase start for RLS/auth paths.
  • AI routing: develop retrieval SQL, the HNSW index and the vector_cosine_ops choice against local pgvector (container or PGlite) before spending tokens against a hosted DB; embed with whichever provider the [[anthropic]] / [[open-ai]] / [[hugging-face]] routing picks.
  • Payments: Stripe is the default rail and webhook flows are tested with the Stripe CLI against the local DB. Kenya-targeted projects only: seed M-Pesa tables with integer KES and 254XXXXXXXXX numbers behind CHECK constraints, and dedupe on CheckoutRequestID locally exactly as in production.
  • Kenya-targeted projects (offline): two different stories. Developer offline: docker compose up -d or PGlite keeps Postgres + pgvector working with the uplink down, with no round-trip to a US-region database. User offline (2G/3G, intermittent): put a local SQLite/PGlite store on the device and sync with PowerSync or a DIY outbox (§11); keep sync payloads small (partial shapes / sync streams scoped per user), and never mark an M-Pesa payment as paid from the client: the server callback is the source of truth.
  • What the local container can't do: Supabase Auth/Storage/Realtime/Edge Functions (use §5) and Neon branching (use §6).

Troubleshooting

IssueFix
Cannot connect to the Docker daemon in WSLPath B without systemd: sudo service docker start, or [boot] systemd=true in /etc/wsl.conf + wsl --shutdown
permission denied ... /var/run/docker.socksudo usermod -aG docker $USER, then wsl --shutdown
Data gone after recreate (Postgres ≤17)Mounted at /var/lib/postgresql instead of /var/lib/postgresql/data. 18+ uses the bare path
database files are incompatible with serverVolume initialized by another Postgres major. pg_dump from the old tag, down -v, restore
port is already allocatedNative Windows Postgres, or supabase start and a container both want a port. Remap: -p 127.0.0.1:55432:5432
Windows can't reach localhost:5432 after sleep/VPNwsl --shutdown, restart the distro; or try networkingMode=mirrored
App container ECONNREFUSED postgres:5432Add depends_on: {postgres: {condition: service_healthy}} + pg_isready healthcheck
type "vector" does not existCREATE EXTENSION vector; (container) or pass extensions: { vector } from @electric-sql/pglite-pgvector (PGlite)
Cannot find module '@electric-sql/pglite/vector'pgvector moved to the @electric-sql/pglite-pgvector package
npx prisma generate: unknown command / schema ignoredYou got the Prisma 8 RC CLI. npm i -D prisma@7 and use npx prisma@7
Prisma 7: DATABASE_URL undefined in CLIv7 doesn't load .env; add import "dotenv/config" to prisma.config.ts
Prisma 7: seed didn't run after migrate devExpected in v7: run npx prisma@7 db seed
Prisma 7 hangs connectingpg has no connect timeout by default; set connectionTimeoutMillis on PrismaPg
Drizzle docs code fails on 0.45.4The docs target @rc (1.0). Match the docs version or pin and read the 0.x docs
Neon Local: self-signed certificateExpected: ssl: { rejectUnauthorized: false } for the localhost proxy only
Neon serverless driver can't reach Neon LocalIt supports HTTP only: set fetchEndpoint, useSecureWebSocket = false, poolQueryViaFetch = true
supabase start port clash between two worktreesOne stack per machine on default ports; change ports in each config.toml
Mongo: Transaction numbers are only allowed on a replica set memberStart with --replSet rs0 --bind_ip_all, run rs.initiate(...) once
Redis empty after restartPass --save 60 1 --appendonly yes and mount /data
Postgres crawls / fsync stormsData on /mnt/c via bind mount. Use a named volume
the attribute 'version' is obsoleteDelete the top-level version: key