Quickstart

Connect a browser, listen on a channel, and publish to it from your backend. It takes about five minutes.

1. Create an app

Sign in to the dashboard with GitHub and create an app. Your browser makes its keys and sends us only the public halves: we never see your private keys. You get three values, and a .env file with all of them:

  • PIKOMAN_APP, the app id. It is public and goes in your frontend code.
  • PIKOMAN_API_KEY, an API key (sk_…). It signs your backend's requests, such as publishing, and stays on your server. It has only the rights you give it, and is shown only once.
  • PIKOMAN_PRIVATE_KEY, the private key. It signs join tokens for presence and private channels, and stays on your server. It is shown only once.

2. Install the client

terminal
npm install @pikoman/ws@next

@next is the 1.0 release candidate, which speaks protocol 2.0 and connects to wss://next.pikoman.se by itself. Plain @pikoman/ws is still the old 0.2 client for protocol 1.x until 1.0.0 is released, and it does not work with a dashboard app. The package ships TypeScript types and opens one WebSocket that all your channels share.

3. Connect and listen

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

const pikoman = new Pikoman("your-app-id");

const channel = pikoman.listen("main-channel");

channel.on("latest-notification", (data) => {
  console.log(data.message);
});

listen can be called before the connection is open; the client joins the channel as soon as it can. Calling it again with the same name returns the same channel. Anyone with your app id can listen on a public channel, so for anything private read step 5.

4. Publish from your backend

Send a POST to /{channel}/{event}. The body is the payload: JSON arrives in the browser as an object, anything else as a string. Every request carries a token signed with your API key and made for that one request, so the key itself is never sent. To try it now, open your app in the dashboard, and under Make a token for one request choose POST, the path /main-channel/latest-notification and the body {"message": "hello world"}. You get this command with the token in it:

terminal
curl -X POST https://next-api.pikoman.se/main-channel/latest-notification \
  -H "Authorization: Bearer eyJhbGciOiJFZERTQSIs…" \
  -H "Content-Type: application/json" \
  --data-raw '{"message": "hello world"}'

The response tells you how many connections received it:

JSON
{ "clients": 1 }

That is the whole loop. In your backend, make a token for each request in code: it takes one short file in Node, PHP or Python. The notifications demo runs exactly this, and HTTP API has the rest of the API.

5. Presence and private channels: a token endpoint

Channels named presence-… (with a member list) and private-… only let a connection in with a join token from your backend. Tell the client where to ask:

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

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

For each join the client sends POST {auth_url} with the JSON body {"connection_id": "c_…", "channel": "…"} and expects {"token": "…"}, as pusher-js does with its auth endpoint. Headers your backend needs, such as a CSRF token, go in auth_headers. Your endpoint decides whether this user may join that channel, and what the others see about them. In Node, with nothing to install:

pikoman-auth.mjs
import { createServer } from "node:http";
import { createPrivateKey, sign } from "node:crypto";

// The dashboard gives the key as one line of base64 (PKCS#8 DER). A PEM works too.
const keyText = process.env.PIKOMAN_PRIVATE_KEY.trim();
const privateKey = keyText.startsWith("-----")
  ? createPrivateKey(keyText)
  : createPrivateKey({ key: Buffer.from(keyText, "base64"), format: "der", type: "pkcs8" });

const part = (value) => Buffer.from(JSON.stringify(value)).toString("base64url");

/** A join token: an EdDSA JWT for one connection and one channel. */
export function pikomanToken({ clientId, channel, access = 3, data = {} }) {
  const signed = part({ alg: "EdDSA", typ: "JWT" }) + "." + part({
    connection: clientId,
    channel,
    access,
    data,
    exp: Math.floor(Date.now() / 1000) + 300,
  });
  return `${signed}.${sign(null, Buffer.from(signed), privateKey).toString("base64url")}`;
}

// The client posts {"connection_id": "...", "channel": "..."} and wants {"token": "..."}.
createServer(async (req, res) => {
  let body = "";
  for await (const chunk of req) if ((body += chunk).length > 1024) break;
  let ask = {};
  try { ask = JSON.parse(body); } catch {}
  const { connection_id, channel } = ask;
  const user = await currentUser(req); // your own login check
  if (req.method !== "POST" || req.url !== "/pikoman/auth" || typeof connection_id !== "string"
      || typeof channel !== "string" || !user || !mayJoin(user, channel)) {
    res.writeHead(403).end();
    return;
  }
  const token = pikomanToken({ clientId: connection_id, channel, data: { name: user.name } });
  // no-store: a token is for this visitor and this connection only, never for a cache.
  res.writeHead(200, { "content-type": "application/json", "cache-control": "no-store" });
  res.end(JSON.stringify({ token }));
}).listen(3001);

In PHP 7.0 or later. Sodium is built in from PHP 7.2; on older versions, install paragonie/sodium_compat, which provides the same functions.

auth.php
<?php
// POST auth.php with {"connection_id": "...", "channel": "..."} answers {"token": "..."}.

function base64url(string $bytes): string
{
    return rtrim(strtr(base64_encode($bytes), '+/', '-_'), '=');
}

/** A join token: an EdDSA JWT for one connection and one channel. */
function pikoman_token(string $clientId, string $channel, array $data, int $access = 3): string
{
    // The key as the dashboard gives it: base64 of PKCS#8, 16 bytes of header and a 32-byte seed.
    $der = base64_decode(preg_replace('/-----[^-]+-----|\s+/', '', getenv('PIKOMAN_PRIVATE_KEY')));
    $secretKey = sodium_crypto_sign_secretkey(sodium_crypto_sign_seed_keypair(substr($der, 16, 32)));

    $signed = base64url(json_encode(['alg' => 'EdDSA', 'typ' => 'JWT'])) . '.' . base64url(json_encode([
        'connection' => $clientId,
        'channel'    => $channel,
        'access'     => $access,
        'data'       => (object) $data,
        'exp'        => time() + 300,
    ]));
    return $signed . '.' . base64url(sodium_crypto_sign_detached($signed, $secretKey));
}

$user = current_user(); // your own login check
$ask = json_decode(file_get_contents('php://input'), true);
$connectionId = $ask['connection_id'] ?? null;
$channel = $ask['channel'] ?? null;
if (!$user || !is_string($connectionId) || !is_string($channel) || !may_join($user, $channel)) {
    http_response_code(403);
    exit;
}
header('Content-Type: application/json');
header('Cache-Control: no-store'); // the token is for this visitor only, never for a cache
echo json_encode(['token' => pikoman_token($connectionId, $channel, ['name' => $user['name']])]);

The private key belongs on your server, next to your other secrets. Never put it in frontend code or in a VITE_ or similar variable that ends up in the bundle.

access: 3 makes a full member, who may send to the channel and sees who else is in it. What the token holds, and how to sign one in other languages, is in Protocol and tokens; what members can do is in Presence and private channels.

Connection state

The client reconnects by itself after a drop, after a random wait of up to a second that grows to up to 30 seconds while attempts fail, and joins every channel again, with new tokens. It sends a ping after 6.5 seconds of silence and treats 18.5 seconds without any message as a lost connection.

TypeScript
pikoman.online(() => setBanner(null));
pikoman.offline(() => setBanner("Reconnecting…"));

pikoman.isConnected(); // true once the server has assigned a connection id
pikoman.getClientId(); // that id, such as "c_8f3a1c9e2b7d4a6051e0c3b9"

A reconnect is a new connection with a new id. Messages published while a client was away are not replayed, so fetch the current state from your own API after online fires if you need it. The poll demo shows the pattern.

One client address may hold a tenth of your app's connections: 10 on Free, 100 on Pro. A connection past that is refused with 429 (Too many connections to this app from this address) and the client tries again later. Many users behind one office or school network can reach it before your plan's limit; write to hello@pikoman.se and we set a higher limit for your app.

Stop listening

TypeScript
channel.off("latest-notification", handler); // remove one handler

pikoman.leaveChannel("main-channel"); // leave the channel and drop its handlers

Client reference

new Pikoman(appId, options?)
Member What it does
options.auth_url Your token endpoint, asked with a POST. Only needed for presence and private channels.
options.auth_headers Headers sent with every token request (a CSRF token, a bearer token), or a function that returns them, called at each request.
options.ws_address WebSocket endpoint. Defaults to wss://next.pikoman.se; leave it unset.
listen(name) Join a public channel. Returns a Channel. Throws for names starting with presence- or private-.
listenPresence(name, authenticator?) Join a presence- channel with a token. Returns a PresenceChannel.
listenPrivate(name, authenticator?) Join a private- channel with a token. Returns a PrivateChannel.
leaveChannel(name) Leave a channel and drop its handlers.
online(fn), offline(fn) Called when the connection is established or lost.
isConnected(), getClientId() Whether the server has assigned a connection id, and that id.
close() From 1.0.0-rc.7: close the connection for good. It does not reconnect, and its timers and page listeners stop, so a single-page app can drop a client it no longer needs.
channel.on(event, fn) Handle one event: fn(data) for events from your backend. Events from other members are named client-…: on("client-typing", fn) gets fn(senderId, data).
channel.off(event, fn) Remove a handler added with on.
channel.serverMessage(fn) Every event from your backend, whatever its name: fn(data, event).
channel.refused(fn) The server turned down the join, or a send: fn(code), such as "join_refused", "rate_limited" or "data_too_large".
channel.send(event, data, toAll?) Presence and private only, with write access: send a client event to the other members. Name it client-…, such as send("client-typing", data); from 1.0.0-rc.7 send("typing", data) puts the prefix in front itself. toAll also delivers it to you. The data may be at most 12 KiB as JSON.
channel.onClient(name, fn), offClient(name, fn) From 1.0.0-rc.7, presence and private only: one client event from other members, by its name with or without client-. onClient("typing", fn) is on("client-typing", fn) and gets fn(senderId, data). In rc.7 on("typing", fn) no longer gets members' events, only your backend's.
channel.clientMessage(fn) Presence and private only: every event from other members, fn(senderId, event, data), with the event's client- name.
channel.members(fn) Presence only: the member list, a Map of connection id to member data, on join and on every change.
channel.getMembers(), getMember(id), me Presence only: the current list, one member's data, and your own.
channel.subscribe(fn), unsubscribe(fn) Presence only: one call per arrival, fn(type, count, id, data), or departure, fn(type, count, id).

Which channel has what

Method Public (listen) Private (listenPrivate) Presence (listenPresence)
on, off, serverMessage, refused Yes Yes Yes
send, clientMessage, onClient No Yes Yes
Who sent a client event (no client events) Connection id Connection id and member data
members, getMembers, getMember, me No No Yes
subscribe, unsubscribe No No Yes

Client events always carry the sender's connection id, set by the server. In a private channel that is all you get; map ids to users in your token endpoint if you need to. Presence adds the member data from each join token, so every id comes with a name.

A working example

pikomanse/example is a small SolidJS app with live cursors, emoji reactions and a list of who is online, in the presence channel presence-lobby. Its server.mjs is the token server; start it with PIKOMAN_PRIVATE_KEY set. Publish to the event announcement on main-channel and every open page shows a banner, here with a token from pikoman-token.mjs made for this one request:

terminal
BODY='{"message": "Deploy finished"}'
TOKEN=$(node pikoman-token.mjs POST /main-channel/announcement "$BODY")
curl -X POST https://next-api.pikoman.se/main-channel/announcement \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" -d "$BODY"

Next: presence and private 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