What is PGlite?
PGlite is a WASM Postgres that can run directly in the browser, or in Node.js for instance, without the need to install any other dependencies.
There is currently no built-in support for connecting to a PGlite instance outside the process that starts it. This means it’s not possible to run PGlite and connect via an external process using a database URL for example.
Supabase have a library called pg-gateway which implements the Postgres wire protocol, meaning it can act as a TCP proxy in front of a PGlite instance. Something to investigate in the future perhaps.
Brief demo
Look at the following terminal session to see how easy it is to install and launch an instance with data persisted to the local filesystem.
# install pglite
$ npm install @electric-sql/pglite
added 1 package, and audited 256 packages in 2s
54 packages are looking for funding
run `npm fund` for details
2 vulnerabilities (1 moderate, 1 high)
To address all issues, run:
npm audit fix
Run `npm audit` for details.
# run node REPL
$ node
Welcome to Node.js v22.5.1.
Type ".help" for more information.
> const { PGlite } = await import("@electric-sql/pglite");
undefined
# create the database and persist to the pgdata directory
> const db = new PGlite('./pgdata')
undefined
# create a table and insert data
> await db.exec(`
... CREATE TABLE IF NOT EXISTS todo (
... id SERIAL PRIMARY KEY,
... task TEXT,
... done BOOLEAN DEFAULT false
... );
... INSERT INTO todo (task, done) VALUES ('Install PGlite from NPM', true);
... INSERT INTO todo (task, done) VALUES ('Load PGlite', true);
... INSERT INTO todo (task, done) VALUES ('Create a table', true);
... INSERT INTO todo (task, done) VALUES ('Insert some data', true);
... INSERT INTO todo (task) VALUES ('Update a task');
... `)
[
{ rows: [], fields: [] },
{ rows: [], fields: [] },
{ rows: [], fields: [] },
{ rows: [], fields: [] },
{ rows: [], fields: [] },
{ rows: [], fields: [], affectedRows: 5 }
]
# retrieve one record
> const ret = await db.query(`
... SELECT * from todo WHERE id = 1;
... `)
undefined
> console.log(ret.rows)
[ { id: 1, task: 'Install PGlite from NPM', done: true } ]
undefined
> .exit
# restart the REPL to prove the data is persisted
$ node
Welcome to Node.js v22.5.1.
Type ".help" for more information.
> const { PGlite } = await import("@electric-sql/pglite");
undefined
# create an instance using the existing data
> const db = new PGlite('./pgdata')
undefined
# select all rows
> const ret = await db.query('SELECT * from todo');
undefined
> console.log(ret.rows)
[
{ id: 1, task: 'Install PGlite from NPM', done: true },
{ id: 2, task: 'Load PGlite', done: true },
{ id: 3, task: 'Create a table', done: true },
{ id: 4, task: 'Insert some data', done: true },
{ id: 5, task: 'Update a task', done: false }
]
undefined
>
Is it used in the real-world?
Yeah, Supabase launched postgres.new which uses PGlite under the hood. A quick review of this will follow soon.