Presence and private channels

A private channel lets in only the connections your backend vouches for. A presence channel does the same and also knows who is in it: members carry data your server signed, everyone is told when someone joins or leaves, and members can send messages to each other directly.

Three kinds of channel

Name Who can join Member list Client method
anything else Anyone with your app id No listen
private-… Connections with a join token No listenPrivate
presence-… Connections with a join token Yes listenPresence

A private channel suits one user's notifications, such as private-user-7: your backend publishes to it and only that user's tabs get in. Use presence when people should see each other. A private channel named private-encrypted-… is also end-to-end encrypted.

How joining works

  1. The browser connects and the server gives it a connection id, such as c_8f3a1c9e2b7d4a6051e0c3b9.
  2. The client asks your backend for a token for that id and the channel.
  3. Your backend decides whether this user may join, picks their member data, and signs a token.
  4. The client joins with the token. The server checks the signature, the connection, the channel and the expiry, and lets the connection in.

Because the token names the connection and the channel, it is useless anywhere else. Because the member data is signed, a user cannot change their own name or role. On a reconnect the client gets a new id and asks for new tokens by itself.

On the client

app.ts
import { Pikoman } from "@pikoman/ws";

const pikoman = new Pikoman("your-app-id", { auth_url: "/pikoman/auth" });

const room = pikoman.listenPresence("presence-lobby");
const inbox = pikoman.listenPrivate("private-user-7");

room.refused((code) => console.warn("Not let in:", code));

With auth_url set, the client sends POST {auth_url} with {"connection_id": "c_…", "channel": "…"} as JSON and expects {"token": "…"}. A CSRF or bearer token goes in auth_headers:

TypeScript
const pikoman = new Pikoman("your-app-id", {
  auth_url: "/pikoman/auth",
  auth_headers: () => ({ "X-CSRF-TOKEN": csrfToken }), // read at every request
});

If your endpoint needs something else altogether, pass your own authenticator as the second argument. It is any object with an authenticate method that returns the token:

TypeScript
const authenticator = {
  async authenticate(clientId: string, channel: string) {
    const response = await fetch("/api/pikoman-token", {
      method: "POST",
      headers: { "content-type": "application/json", "x-csrf-token": csrfToken },
      body: JSON.stringify({ clientId, channel }),
    });
    const { token } = await response.json();
    return token;
  },
};

const room = pikoman.listenPresence("presence-lobby", authenticator);

The token endpoint

Ready-made endpoints in Node and PHP that read the private key as the dashboard gives it are in the quickstart. What a token contains, and how to make one with a JWT library or in Rust, is in Protocol and tokens.

More than one signing key

An app can have several signing keys, which is how you replace one without refusing anybody: add a new key in the dashboard, switch your token endpoint to it, then delete the old one.

  • A token may name its key in the header: {"alg": "EdDSA", "typ": "JWT", "kid": "s_…"}. The server then checks it with that key only. Set PIKOMAN_SIGNING_KEY_ID next to PIKOMAN_PRIVATE_KEY and put it in kid.
  • A token without kid is checked against each of the app's signing keys, so endpoints written before there were several keep working.

Bots join with an API key

A program with no browser, such as a bot, an MCP server or an LLM agent, can join too, without your token endpoint. Give it an API key with the subscribe right, and it signs its own join token with the key's id in kid. The key's channel kinds, prefixes, addresses and expiry all apply. It may listen (access 0), or also send if the key has client_events (access 3). In a presence channel it is a member like any other, with the member data from its token, and the server names it as a bot next to that data (see who is a bot). A working bot is in Keys and rights.

Who is a bot

Member data is your app's own. Pikoman passes it on exactly as the token has it: it adds nothing, removes nothing, and never reads it to decide anything, so data that says "bot": true makes nobody a bot. Only the server says who is a bot, next to the data, with the id of the API key each one joined with:

  • bot in member_joined, only when the one who joined is a bot.
  • bots with the member list: connection id to key id, left out when there are none.
  • bots in GET /{channel}/clients, the same way.
JSON
{"op":"member_joined","channel":"presence-room","count":2,"id":"c_b07e…","data":{"name":"Order bot"},"bot":"k_3f9a1c0e5b7d2468"}
{"op":"members","channel":"presence-room","members":{"c_a11a…":{"name":"Anna","bot":true},"c_b07e…":{"name":"Order bot"}},"bots":{"c_b07e…":"k_3f9a1c0e5b7d2468"}}

Anna's "bot": true is only her data: she is not a bot. To tell whether a client event came from a bot, look its from up among the bots: start from bots in the member list, add the id when a member_joined has bot, and drop it on member_left.

Access

A token's access number says what the connection may do in the channel. Only the bit worth 2, write, means anything today:

  • 3, a full member. May send to the channel, and in a presence channel gets the full member list on joining.
  • 0, listen only. The default when a token leaves access out. The connection gets events from your backend and from other members, but cannot send, and in a presence channel hears nothing about the other members: no member list, and no word when someone joins or leaves.

In a private channel, member data in the token is ignored.

Who is here

TypeScript
// The full list: on join, and again whenever it changes.
room.members((members) => {
  for (const [id, data] of members) console.log(id, data.name);
});

// One callback per arrival or departure.
room.subscribe((_type, count, id, data) => console.log(`${data.name} joined, ${count} here`));
room.unsubscribe((_type, count, id) => console.log(`${id} left, ${count} here`));

room.getMembers(); // Map of connection id to member data, longest member first
room.getMember(id);
room.me; // your own member data

A member is a connection, not a person: someone with two tabs open appears twice. Put a user id in the member data if you need to group them.

A closed tab leaves at once, and so does a page the visitor navigates away from: the client closes its connection on pagehide (from 1.0.0-rc.2), and connects again by itself if the page comes back from the browser's back/forward cache. Switching tabs changes nothing. A connection that dies without closing, such as a laptop that went to sleep or a phone that lost its network, is dropped by the server after 90 seconds of silence.

Messages between browsers

Members with write access can send events to a presence or private channel without going through your backend. These client events are named client-…, as with Pusher, and their handlers receive the sender's connection id first.

TypeScript
room.on("client-move", (senderId, position) => {
  movePointer(room.getMember(senderId), position);
});

room.send("client-move", { x: 0.31, y: 0.62 }); // to everyone else
room.send("client-message", { text: "hi" }, true); // to everyone, including you

Writing the prefix out, as here, works with every version of the client. From @pikoman/ws 1.0.0-rc.7 send("move", data) sends client-move by itself, onClient("move", fn) listens for it, and on("move", fn) no longer gets members' events, only your backend's.

To one member only, use sendTo (from @pikoman/ws 1.0.0-rc.8): a connection id, or { userId } for every connection whose signed member data has that user_id. Nobody else gets it, and a member who is not in the channel is refused with no_such_member. The receiver's handler gets a last argument, info, when the server has something to say: direct, the sender's userId from its signed member data, and bot when the sender is a bot. The server sets these; a sender cannot.

TypeScript
room.sendTo("c_8f3a1c9e2b7d4a6051e0c3b9", "answer", { ok: true });
room.sendTo({ userId: "42" }, "answer", { ok: true });

room.onClient("answer", (senderId, data, info) => {
  if (info?.direct) console.log("to me alone, from user", info.userId);
});

The server relays client messages as they are. It does not validate the payload, so treat what arrives as untrusted input, the same as anything else a user typed.

What the server turns down, with an error that reaches refused(fn); the connection stays:

  • More than 10 client events in a second from one connection, unless your app has a higher limit: {"op":"error","code":"rate_limited","channel":"presence-lobby"}, and the event is dropped. Throttle streams such as pointer positions to one every 100 ms or so.
  • Data over 12 KiB (12,288 bytes as JSON): data_too_large. The event is dropped, never cut.
  • A name without client-: invalid_event_name.
  • A send without write access: not_allowed.

Server messages still work

You can publish over HTTP to presence and private channels like any other. Those handlers get the payload only, with no sender id, and members cannot fake them: your backend's event names never start with client-, and members' always do, so a handler knows which shape to expect.

Previous: quickstart Next: encrypted channels

We are rebuilding the dashboard

Self-service sign-up is closed while we do. Until the new dashboard is ready we set up apps by hand: write to us with a line about what you are building, and we will set up your app and get back to you.

Write to hello@pikoman.se