Subscribe

Subscribing requires a WebSocket connection and subscribe permission on the channel. Use the Language control to switch JavaScript vs React.

REST cannot open a realtime subscription — publish with REST, receive with Socket.

Basic subscribe

import { QPub } from "@qpub/sdk";

const socket = new QPub.Socket({
  apiKey: process.env.QPUB_API_KEY,
});

socket.connection.on("connected", async () => {
  const channel = socket.channels.get("notifications");
  await channel.subscribe((message) => {
    console.log(message.data);
  });
});

subscribe returns a Promise that resolves when the server acknowledges the subscription.

Do not put a production API key secret in a public browser app. Use token auth instead.

Event filter (SDK)

The client still subscribes to the whole channel on the server. The SDK delivers only matching event values to this handler.

await channel.subscribe(
  (message) => console.log(message.data),
  { event: "order.created" }
);

Unsubscribe

await channel.unsubscribe();

Production clients

Prefer a scoped JWT or token request so the browser never holds the API key secret:

const socket = new QPub.Socket({
  tokenRequest, // from your backend
});

See Token Auth.

Protocol

Under the hood the client sends action 4 (subscribe) and receives 5 (subscribed) / 10 (message). See Socket Protocol.