Skip to content

PGlite

Sync into a lightweight WASM Postgres with real-time, reactive bindings.

Lightweight WASM Postgres

PGlite is a lightweight WASM Postgres build, packaged into a TypeScript library for the browser, Node.js, Bun and Deno. PGlite allows you to run Postgres in JavaScript, with no need to install any other dependencies. It is under 3MB gzipped.

ts
import { PGlite } from '@electric-sql/pglite'

const db = new PGlite()
await db.query("select 'Hello world' as message;")
// -> { rows: [ { message: "Hello world" } ] }

Unlike previous "Postgres in the browser" projects, PGlite does not use a Linux virtual machine - it is simply Postgres in WASM, compiled directly in single-user mode.

It can be used as an ephemeral in-memory database, or with persistence either to the filesystem (Node/Bun) or indexedDB (in the browser). It's:

Syncing into PGlite

You can use Electric to sync between a cloud Postgres and an embedded PGlite instance. For example, to sync an items Shape into an items table:

tsx
import { PGlite } from '@electric-sql/pglite'
import { live } from '@electric-sql/pglite/live'
import { electricSync } from '@electric-sql/pglite-sync'
import { useLiveQuery } from '@electric-sql/pglite-react'

// Create a persistent local PGlite database
const pg = await PGlite.create({
  dataDir: 'idb://my-database',
  extensions: {
    electric: electricSync(),
    live
  }
})

// Setup the local database schema
await pg.exec(`
  CREATE TABLE IF NOT EXISTS items (
    id SERIAL PRIMARY KEY,
  );
`)

// Establish a persistent shape subscription
await pg.electric.syncShapeToTable({
  // TODO update this when the sync plugin is updated.
  url: `${BASE_URL}/v1/shape`,
  table: 'items',
  primaryKey: ['id'],
})

// Bind data to your components using live queries
// against the local embedded database
const Component = () => {
  const items = useLiveQuery(
    `SELECT * FROM items;`
  )

  return <pre>{JSON.stringify(items)}</pre>
}

More information

See the PGlite website at pglite.dev for comprehensive Docs, a list of Examples and a live in-browser REPL. The source code is on GitHub at electric-sql/pglite.