Postgres LISTEN/NOTIFY Bridge

Goal: Database changes become WebSocket events automatically.

Install

npm install svelte-adapter-uws-extensions pg

Set up the bridge

// src/lib/server/db.js
import { createPgClient, createNotifyBridge } from 'svelte-adapter-uws-extensions/postgres';

export const pg = createPgClient({
  connectionString: process.env.DATABASE_URL
});

export const bridge = createNotifyBridge(pg, {
  channel: 'table_changes'
});

Activate in hooks

// src/hooks.ws.js
import { bridge } from '$lib/server/db';

export function open(ws, { platform }) {
  bridge.activate(platform);
}

Add a Postgres trigger

CREATE OR REPLACE FUNCTION notify_change()
RETURNS trigger AS $$
BEGIN
  PERFORM pg_notify('table_changes', json_build_object(
    'topic', TG_TABLE_NAME,
    'event', lower(TG_OP),
    'data', row_to_json(NEW)
  )::text);
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER orders_changed
  AFTER INSERT OR UPDATE ON orders
  FOR EACH ROW EXECUTE FUNCTION notify_change();

Now every INSERT or UPDATE on the orders table sends a WebSocket event to all subscribers. No polling, no manual publish calls.

When to use this

  • External systems write to the database (admin panels, batch jobs, other services)
  • You want the database to be the single source of truth for events
  • You can’t add ctx.publish() calls to every write path

Was this page helpful?