BT

Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ

Topics

Choose your language

InfoQ Homepage News Running PostgreSQL in the Browser with WebAssembly

Running PostgreSQL in the Browser with WebAssembly

With the recently released PGlite, a Wasm build of Postgres that is packaged into a TypeScript client library, developers can run Postgres queries in the browser with no extra dependencies. PGlite is used for reactive, real-time, local-first apps.

Developers could already run SQLite in the browser with WebAssembly. However, running PostgreSQL in the browser previously required spanning a virtual machine and there was no way to persist data. With PGlite, developers can run PostgreSQL queries in a JavaScript environment and persist data to storage in the file system (Node/Bun) or indexedDB (browser).

PGlite was created to support use cases associated with reactive, real-time, local-first applications. ElectricSQL, which self-describes as a local-first software platform for modern apps with instant reactivity, real-time multi-user collaboration, and conflict-free offline support, uses PGlite to sync on demand with a server. They explain:

Local-first is a new development paradigm where your app code talks directly to an embedded local database and data syncs in the background via active-active database replication. […] ElectricSQL gives you instant local-first for your Postgres. Think of it like “Hasura for local-first”.

PGlite includes parameterized SQL queries, an interactive transaction API, pl/pgsql support, web worker execution, and more. PGlite is 2.6MB gzipped. PGlite can be used in memory in the browser as follows:

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

Developers can also persist the database to indexedDB:

const db = new PGlite("idb://my-pgdata");

One Reddit developer emphasized testing as an additional use case for PGlite.

Code testing is a big one for me. I’m currently using in-memory SQLite for tests and I’m often running into differences between SQLite and Postgres (default values, JSON handling, etc). This could allow me to use the real thing without running a full Docker instance.

Another developer said:

No one using Postgres in the cloud is going to use this as an alternative, but there are at least two use cases where this could be very useful:

  • You want your app to be local first (snappy, great offline support, etc) but sync data to a server. This is the ElectricSQL use case.

  • You want a serious data store in-browser. SQLite via Wasm already fits this use case, but it’s nice to have options.

PGlite is open-source software under the Apache 2.0 license. It is being developed at ElectricSQL in collaboration with Neon. PGlite is still in the early stages and plans to support pgvector in future releases.

About the Author

BT