Setting up PGlite in Deno

2 min read

353 words

I recently tried PGlite because I saw it trending on Hacker News. The idea is cool, having a built-in Postgres database that can even run in the client's browser brings a lot of possibilities. Seeing WASM (Web Assembly) get more use cases is also exciting to see.

Since I've been a Deno user for a while now, I was wondering if I could easily get it to run there too, since the official docs don't mention Deno in the installation process. However, since Deno 1.46 we now have the ability to run it without runtime restrictions.

Deno relies on the node/npm compatibility layer to run PGlite. Therefore, we're able to just install the package hosted on npm and start using it like on those other runtimes like NodeJS or Bun.

Either you run deno add npm:@electric-sql/pglite, which puts it in your deno.json inside the imports field like:

{
  "imports": {
    "pglite": "npm:@electric-sql/pglite"
  }
}

Or put it in your file as a direct import like this and just start using it

import { PGlite } from "npm:@electric-sql/pglite

const db = new PGlite();

From there it's perfectly described in the docs, we can just start querying and populating our database like we're used to with "remote" databases.

Taken from the [make a query] docs (https://pglite.dev/docs/#making-a-query):

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 table', true);
  INSERT INTO todo (task, done) VALUES ('Insert some data', true);
  INSERT INTO todo (task) VALUES ('Update a task;)
`);

I hope this short post helps you set up PGlite in Deno and we will see official support in the docs really soon.

Thanks for reading, have a nice day 👋🏼

Niklas