/socket.io-postgres-adapter

The Socket.IO Postgres adapter, allowing to broadcast events between several Socket.IO servers

Primary LanguageTypeScriptMIT LicenseMIT

Socket.IO Postgres adapter

The @socket.io/postgres-adapter package allows broadcasting packets between multiple Socket.IO servers.

Diagram of Socket.IO packets forwarded through PostgreSQL

Table of contents

Supported features

Feature socket.io version Support
Socket management 4.0.0 ✅ YES (since version 0.1.0)
Inter-server communication 4.1.0 ✅ YES (since version 0.1.0)
Broadcast with acknowledgements 4.5.0 ✅ YES (since version 0.3.0)
Connection state recovery 4.6.0 ❌ NO

Installation

npm install @socket.io/postgres-adapter

Usage

import { Server } from "socket.io";
import { createAdapter } from "@socket.io/postgres-adapter";
import pg from "pg";

const io = new Server();

const pool = new pg.Pool({
  user: "postgres",
  host: "localhost",
  database: "postgres",
  password: "changeit",
  port: 5432,
});

pool.query(`
  CREATE TABLE IF NOT EXISTS socket_io_attachments (
      id          bigserial UNIQUE,
      created_at  timestamptz DEFAULT NOW(),
      payload     bytea
  );
`);

pool.on("error", (err) => {
  console.error("Postgres error", err);
});

io.adapter(createAdapter(pool));
io.listen(3000);

License

MIT