PGlite: Run PostgreSQL in Browser & Node.js - No Server Required
Add to your RSS feed17 January 20254 min readTable of Contents
PGlite represents a groundbreaking advancement in database technology, bringing the robust capabilities of PostgreSQL directly to your browser and Node.js applications without requiring a traditional server setup. This innovative solution empowers developers to harness PostgreSQL's full potential in environments where running a dedicated database server was previously impossible or impractical.
What is PGlite?
PGlite is a PostgreSQL server compiled to WebAssembly (WASM), enabling it to run directly in browsers or Node.js environments without needing a standalone server or Linux-based image. At just 3MB (compressed), it supports key extensions like pgvector and offers seamless integration with JavaScript/TypeScript libraries.
Key Features
- Lightweight: Minimal 3MB compressed size.
- Easy API: Import the library and call methods like any ORM (e.g., Drizzle, TypeORM).
- Extension Support: Pre-packaged with popular plugins like pgvector.
- Storage Options: Use as an in-memory database or enable persistent storage via IndexedDB (browser) or file system (Node.js/Bun/Deno).
Browser-Native Operation
PGlite leverages WebAssembly to run PostgreSQL directly in modern web browsers, enabling developers to create sophisticated database-driven applications that operate entirely on the client side. This approach significantly reduces deployment complexity and eliminates the need for backend infrastructure for many use cases.
Node.js Integration
Beyond the browser, PGlite seamlessly integrates with Node.js applications, providing a consistent database experience across different JavaScript environments. This versatility makes it an excellent choice for full-stack JavaScript applications.
Zero Configuration Required
Getting started with PGlite is remarkably straightforward. There's no need for complex server setup, database installation, or configuration files. Simply import the library and begin working with PostgreSQL immediately.
How It Works
PGlite leverages PostgreSQL’s single-user mode, originally intended for recovery tasks. By adapting its I/O and runtime for WebAssembly, it runs as a library in a single thread, supporting one connection and one user.
Getting Started
In Browsers
Install the package or import it:
1 import { PGlite } from "@electric-sql/pglite";23 async function initDatabase() {4 // Create a new PGlite instance5 const pglite = new PGlite();67 // Initialize the database8 await pglite.query(`9 CREATE TABLE users (10 id SERIAL PRIMARY KEY,11 name TEXT NOT NULL,12 email TEXT UNIQUE NOT NULL13 );14 `);1516 // Insert sample data17 await pglite.query(`18 INSERT INTO users (name, email)19 VALUES ('John Doe', 'john@example.com');20 `);2122 // Query the data23 const result = await pglite.query('SELECT * FROM users');24 console.log(result.rows);25 }2627 initDatabase().catch(console.error);
In Node.js/Bun/Deno
1 const { PGlite } = require('@electric-sql/pglite');23 async function main() {4 // Initialize PGlite5 const db = new PGlite();6 await db.connect();78 // Create a sample table9 await db.execute(`10 CREATE TABLE products (11 id SERIAL PRIMARY KEY,12 name TEXT NOT NULL,13 price DECIMAL(10,2)14 );15 `);1617 // Perform batch operations18 await db.transaction(async (client) => {19 await client.execute(`20 INSERT INTO products (name, price) VALUES21 ('Product A', 29.99),22 ('Product B', 49.99),23 ('Product C', 19.99);24 `);25 });26 }2728 main().catch(console.error);
For persistent storage in Node.js:
1 const db = new PGlite("./path/to/pgdata");
Use Cases
- Rapid Prototyping and Testing: Ideal for unit tests or mock databases without the overhead of Docker/Postgres setups.
- Demos and Educational Projects: Showcase database functionality without requiring additional software installations.
- Local-First Apps: Store data locally (e.g., in a browser) and sync it with external databases when online.
- Sandbox Environments: Run isolated SQL scripts or experiments without impacting production systems.
Code Examples
Creating a Table and Querying Data
1 await db.query(`2 CREATE TABLE users (3 id SERIAL PRIMARY KEY,4 name TEXT NOT NULL5 );6 `);78 await db.query("INSERT INTO users (name) VALUES ('Alice'), ('Bob')");910 const { rows } = await db.query("SELECT * FROM users");11 console.log(rows);12 // Output: [{ id: 1, name: "Alice" }, { id: 2, name: "Bob" }]
Performance Considerations
While PGlite provides impressive functionality, it's important to understand its limitations:
- Memory Usage: As the database runs entirely in memory, applications should be mindful of data size and memory consumption.
- Complex Queries: While PGlite supports most PostgreSQL features, very complex queries might perform differently compared to a traditional server setup.
- Data Persistence: Additional implementation is required to persist data between sessions when running in the browser.
Conclusion
PGlite provides a straightforward way to integrate the full power of PostgreSQL into your JavaScript applications without the overhead of traditional database setups. Whether you’re prototyping, running demos, or building local-first apps, PGlite is a lightweight yet robust solution that fits seamlessly into modern development workflows.
Explore the repository and dive into the codebase to learn more about this innovative approach to PostgreSQL in WASM.