JavaScript Development Space

PGlite: Run PostgreSQL in Browser & Node.js - No Server Required

Add to your RSS feed17 January 20254 min read
PGlite: Run PostgreSQL in Browser & Node.js - No Server Required

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

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:

npm install @electric-sql/pglite
js
1 import { PGlite } from "@electric-sql/pglite";
2
3 async function initDatabase() {
4 // Create a new PGlite instance
5 const pglite = new PGlite();
6
7 // Initialize the database
8 await pglite.query(`
9 CREATE TABLE users (
10 id SERIAL PRIMARY KEY,
11 name TEXT NOT NULL,
12 email TEXT UNIQUE NOT NULL
13 );
14 `);
15
16 // Insert sample data
17 await pglite.query(`
18 INSERT INTO users (name, email)
19 VALUES ('John Doe', 'john@example.com');
20 `);
21
22 // Query the data
23 const result = await pglite.query('SELECT * FROM users');
24 console.log(result.rows);
25 }
26
27 initDatabase().catch(console.error);

In Node.js/Bun/Deno

js
1 const { PGlite } = require('@electric-sql/pglite');
2
3 async function main() {
4 // Initialize PGlite
5 const db = new PGlite();
6 await db.connect();
7
8 // Create a sample table
9 await db.execute(`
10 CREATE TABLE products (
11 id SERIAL PRIMARY KEY,
12 name TEXT NOT NULL,
13 price DECIMAL(10,2)
14 );
15 `);
16
17 // Perform batch operations
18 await db.transaction(async (client) => {
19 await client.execute(`
20 INSERT INTO products (name, price) VALUES
21 ('Product A', 29.99),
22 ('Product B', 49.99),
23 ('Product C', 19.99);
24 `);
25 });
26 }
27
28 main().catch(console.error);

For persistent storage in Node.js:

js
1 const db = new PGlite("./path/to/pgdata");

Use Cases

  1. Rapid Prototyping and Testing: Ideal for unit tests or mock databases without the overhead of Docker/Postgres setups.
  2. Demos and Educational Projects: Showcase database functionality without requiring additional software installations.
  3. Local-First Apps: Store data locally (e.g., in a browser) and sync it with external databases when online.
  4. Sandbox Environments: Run isolated SQL scripts or experiments without impacting production systems.

Code Examples

Creating a Table and Querying Data

js
1 await db.query(`
2 CREATE TABLE users (
3 id SERIAL PRIMARY KEY,
4 name TEXT NOT NULL
5 );
6 `);
7
8 await db.query("INSERT INTO users (name) VALUES ('Alice'), ('Bob')");
9
10 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.

JavaScript Development Space

© 2025 JavaScript Development Space - Master JS and NodeJS. All rights reserved.