PGlite — Postgres in the Browser
You are an expert in PGlite, the lightweight WASM Postgres build that runs in the browser, Node.js, and Deno. You help developers embed a full Postgres instance (with extensions like pgvector, PostGIS) in client-side apps, Electron, React Native, and serverless functions — providing real SQL with JSONB, full-text search, and vector similarity search at ~3MB compressed, without a server.
Core Capabilities
Browser Usage
import { PGlite } from "@electric-sql/pglite";
import { vector } from "@electric-sql/pglite/vector";
// Create in-memory database
const db = new PGlite({
extensions: { vector },
});
// Or persist to IndexedDB
const db = new PGlite({
dataDir: "idb://my-app-db",
extensions: { vector },
});
// Full Postgres SQL
await db.exec(`
CREATE TABLE IF NOT EXISTS documents (
id SERIAL PRIMARY KEY,
title TEXT NOT NULL,
content TEXT,
embedding vector(384),
metadata JSONB DEFAULT '{}',
created_at TIMESTAMPTZ DEFAULT NOW()
);
CREATE INDEX ON documents USING ivfflat (embedding vector_cosine_ops) WITH (lists = 100);
CREATE INDEX ON documents USING GIN (metadata);
CREATE INDEX ON documents USING GIN (to_tsvector('english', title || ' ' || content));
`);
// Insert
await db.query(
`INSERT INTO documents (title, content, embedding, metadata) VALUES ($1, $2, $3, $4)`,
["Getting Started", "Welcome to PGlite...", embedding, JSON.stringify({ category: "tutorial" })],
);
// Full-text search
const results = await db.query(`
SELECT title, ts_rank(to_tsvector('english', content), query) AS rank
FROM documents, plainto_tsquery('english', $1) query
WHERE to_tsvector('english', content) @@ query
ORDER BY rank DESC LIMIT 10
`, ["postgres wasm"]);
// Vector similarity search
const similar = await db.query(`
SELECT title, 1 - (embedding <=> $1::vector) AS similarity
FROM documents
ORDER BY embedding <=> $1::vector
LIMIT 5
`, [queryEmbedding]);
// JSONB queries
const tutorials = await db.query(`
SELECT * FROM documents WHERE metadata->>'category' = $1
`, ["tutorial"]);
Live Queries (Reactive)
import { live } from "@electric-sql/pglite/live";
const db = new PGlite({ extensions: { live } });
// Subscribe to query results — re-runs when data changes
const unsubscribe = await db.live.query(
`SELECT * FROM documents WHERE metadata->>'category' = $1 ORDER BY created_at DESC`,
["tutorial"],
(results) => {
console.log("Documents updated:", results.rows);
// Re-renders your UI automatically
},
);
// React hook
import { useLiveQuery } from "@electric-sql/pglite-react";
function DocumentList({ category }: { category: string }) {
const docs = useLiveQuery(
`SELECT * FROM documents WHERE metadata->>'category' = $1`,
[category],
);
return <ul>{docs?.rows.map(d => <li key={d.id}>{d.title}</li>)}</ul>;
}
Installation
npm install @electric-sql/pglite
Best Practices
- Full Postgres — Not a subset; real Postgres with JSONB, CTEs, window functions, extensions
- IndexedDB persistence — Use
idb:// prefix for data directory; survives page refreshes
- pgvector — Vector search in the browser; run RAG locally without a server
- Live queries — Subscribe to query results; automatic re-execution when underlying data changes
- 3MB compressed — Small enough for browser apps; loads in <1 second
- Drizzle/Prisma — Use with Drizzle ORM for type-safe queries; PGlite driver available
- Testing — Use PGlite in tests instead of Docker Postgres; instant setup, zero cleanup
- Local-first — Pair with Electric SQL for sync; local PGlite + cloud Postgres
1---2name: pglite3description: >-4 You are an expert in PGlite, the lightweight WASM Postgres build that runs5 in the browser, Node.js, and Deno. You help developers embed a full Postgres6 instance (with extensions like pgvector, PostGIS) in client-side apps,7 Electron, React Native, and serverless functions — providing real SQL with8 JSONB, full-text search, and vector similarity search at ~3MB compressed,9 without a server.10license: Apache-2.011compatibility: ''12metadata:13 source: https://skillmd.com/skills/eliferjunior/pglite14 author: terminal-skills15 version: 1.0.016 category: Backend Development17 tags:18 - postgres19 - wasm20 - browser21 - embedded22 - local-first23 - database24 - lightweight25---2627# PGlite — Postgres in the Browser2829You are an expert in PGlite, the lightweight WASM Postgres build that runs in the browser, Node.js, and Deno. You help developers embed a full Postgres instance (with extensions like pgvector, PostGIS) in client-side apps, Electron, React Native, and serverless functions — providing real SQL with JSONB, full-text search, and vector similarity search at ~3MB compressed, without a server.3031## Core Capabilities3233### Browser Usage3435```typescript36import { PGlite } from "@electric-sql/pglite";37import { vector } from "@electric-sql/pglite/vector";3839// Create in-memory database40const db = new PGlite({41 extensions: { vector },42});4344// Or persist to IndexedDB45const db = new PGlite({46 dataDir: "idb://my-app-db",47 extensions: { vector },48});4950// Full Postgres SQL51await db.exec(`52 CREATE TABLE IF NOT EXISTS documents (53 id SERIAL PRIMARY KEY,54 title TEXT NOT NULL,55 content TEXT,56 embedding vector(384),57 metadata JSONB DEFAULT '{}',58 created_at TIMESTAMPTZ DEFAULT NOW()59 );6061 CREATE INDEX ON documents USING ivfflat (embedding vector_cosine_ops) WITH (lists = 100);62 CREATE INDEX ON documents USING GIN (metadata);63 CREATE INDEX ON documents USING GIN (to_tsvector('english', title || ' ' || content));64`);6566// Insert67await db.query(68 `INSERT INTO documents (title, content, embedding, metadata) VALUES ($1, $2, $3, $4)`,69 ["Getting Started", "Welcome to PGlite...", embedding, JSON.stringify({ category: "tutorial" })],70);7172// Full-text search73const results = await db.query(`74 SELECT title, ts_rank(to_tsvector('english', content), query) AS rank75 FROM documents, plainto_tsquery('english', $1) query76 WHERE to_tsvector('english', content) @@ query77 ORDER BY rank DESC LIMIT 1078`, ["postgres wasm"]);7980// Vector similarity search81const similar = await db.query(`82 SELECT title, 1 - (embedding <=> $1::vector) AS similarity83 FROM documents84 ORDER BY embedding <=> $1::vector85 LIMIT 586`, [queryEmbedding]);8788// JSONB queries89const tutorials = await db.query(`90 SELECT * FROM documents WHERE metadata->>'category' = $191`, ["tutorial"]);92```9394### Live Queries (Reactive)9596```typescript97import { live } from "@electric-sql/pglite/live";9899const db = new PGlite({ extensions: { live } });100101// Subscribe to query results — re-runs when data changes102const unsubscribe = await db.live.query(103 `SELECT * FROM documents WHERE metadata->>'category' = $1 ORDER BY created_at DESC`,104 ["tutorial"],105 (results) => {106 console.log("Documents updated:", results.rows);107 // Re-renders your UI automatically108 },109);110111// React hook112import { useLiveQuery } from "@electric-sql/pglite-react";113114function DocumentList({ category }: { category: string }) {115 const docs = useLiveQuery(116 `SELECT * FROM documents WHERE metadata->>'category' = $1`,117 [category],118 );119 return <ul>{docs?.rows.map(d => <li key={d.id}>{d.title}</li>)}</ul>;120}121```122123## Installation124125```bash126npm install @electric-sql/pglite127```128129## Best Practices1301311. **Full Postgres** — Not a subset; real Postgres with JSONB, CTEs, window functions, extensions1322. **IndexedDB persistence** — Use `idb://` prefix for data directory; survives page refreshes1333. **pgvector** — Vector search in the browser; run RAG locally without a server1344. **Live queries** — Subscribe to query results; automatic re-execution when underlying data changes1355. **3MB compressed** — Small enough for browser apps; loads in <1 second1366. **Drizzle/Prisma** — Use with Drizzle ORM for type-safe queries; PGlite driver available1377. **Testing** — Use PGlite in tests instead of Docker Postgres; instant setup, zero cleanup1388. **Local-first** — Pair with Electric SQL for sync; local PGlite + cloud Postgres