Some notes about PGlite (with Next.js and Drizzle ORM)

Anh-Thi Dinh
PGlite allows you to run a full Postgres database locally (especially in a browser) using WASM, with support for reactivity and live sync.
  • This guide focuses on using PGlite with Drizzle ORM and Next.js.
  • If you cannot use drizzle-kit to generate IF NOT EXISTS with CREATE TABLE, this is expected since they removed it in v3.0.0. Here's a workaround to add it back (ref):
    • We want to use the SQL commands generated by Drizzle without rewriting them.
    • Modify the command in package.json. You need to install yarn add -D tsx.
      • 1{
        2	"scripts": {
        3		"db:generate": "drizzle-kit generate && tsx scripts/export-db-migrations.ts"
        4	}
        5}
        Now, you just need to run yarn run db:generate.
  • Use Multi-tab worker to ensure only one PGlite instance runs across multiple browser tabs.
    • Use .create() instead of the constructor to ensure proper typing for any extensions added to PGliteWorker
      • 1// instead of
        2const pg = new PGliteWorker()
        3
        4// use
        5const pg = await PGliteWorker.create()
  • Using PGlite React Hooks ← read the official docs first.
    • If you use Multi-tab worker, the extension live must be placed in the PGliteWorker() definition rather than inside the PGlite() definition.
    • When using Drizzle ORM to wrap the PGlite instance (e.g., const db = drizzle({ client: pg })), you need to pass the PGlite instance to <PGliteProvider using db={pg}, not the Drizzle-wrapped db.