Skip to main content

Postgres on Angular with PGlite

· 2 min read
Moazzem Hossen
building edge, yet another Postgres backend

PGlite + Angular Signals offers an intriguing alternative to NgRx-like state management solution, especially for PWAs requiring offline capabilities. When Postgres is already in the backend stack, this combo provides unified queries and seamless sync with remote Postgres.

Getting PGlite to work with Angular took some time, so I thought of documenting a minimal demo.

  1. Create a demo app
npm install -g @angular/cli@latest
NG_PROJECT_NAME=${NG_PROJECT_NAME:-"ng-pglite-demo"}
ng new --inline-style --inline-template --routing --ssr=false --style=scss --zoneless $NG_PROJECT_NAME
cd $NG_PROJECT_NAME
npm install @electric-sql/pglite
  1. Update angular.json (with jq like below) or set the values manually
cp angular.json angular.json.bak

jq --arg project_name "$NG_PROJECT_NAME" \
'(.projects[$project_name].architect.build.configurations.development.externalDependencies += ["util"]) |
(.projects[$project_name].architect.build.configurations.production.externalDependencies += ["util"]) |
(.projects[$project_name].architect.build.options.allowedCommonJsDependencies += ["@electric-sql/pglite"]) |
(.projects[$project_name].architect.build.options.assets += [{"glob": "**/*", "input": "node_modules/@electric-sql/pglite/dist", "output": "/"}]) |
(.projects[$project_name].architect.serve.options.prebundle) = false' \
angular.json > tmp.json && mv tmp.json angular.json
  1. Try PGlite in a service / component eg src/app/app.ts with below content
import { CommonModule } from '@angular/common';
import { Component, signal } from '@angular/core';
import { PGlite } from '@electric-sql/pglite';

@Component({
selector: 'app-root',
imports: [CommonModule],
template: `
<h2>Postgres Version</h2>
@if (version()) {
<span>{{ version() }}</span>
} @else {
<span>Loading...</span>
}
`,
styles: ``
})
export class App {
db = new PGlite();
version = signal<string | null>(null);

async ngOnInit() {
try {
const result = await this.db.query<{ version: string }>("SELECT version()");
this.version.set(result.rows[0].version);
} catch (err) {
console.error("Error initializing database:", err);
}
}
}
  1. Verify
ng serve

Visit http://localhost:4200 and notice the rows of users table are rendered.