folkwaysDocs
JavaScript SDK

Issue tokens from your backend

Use @folkwaysio/realtime/server to sign tokens for your users and publish events from your backend.

@folkwaysio/realtime/server is the backend half of the SDK. It signs tokens with your segment's signing key and publishes events over HTTP. It runs on Node.js 20+, Deno, Bun and edge runtimes, and refuses to run in a browser.

Create the server client

realtime.ts
TypeScript
import { Folkways } from '@folkwaysio/realtime/server';

export const folkways = new Folkways.Rest({
  url: process.env.FOLKWAYS_URL!,              // the Realtime URL, e.g. https://realtime.folkways.net
  segment: process.env.FOLKWAYS_SEGMENT_ID!,   // the segment ID (a UUID)
  signingKey: {
    kid: process.env.FOLKWAYS_KEY_ID!,         // the key's ID from the Signing keys tab
    privateKey: process.env.FOLKWAYS_PRIVATE_KEY!,
  },
});

privateKey is the private key of the signing key named by kid, Ed25519 or P-256 (detected automatically), in whichever form you have it:

  • a PEM: -----BEGIN PRIVATE KEY----- (what the Console gives you) or -----BEGIN EC PRIVATE KEY-----;
  • the same PEM on one line with its newlines written as \n, as many secret stores keep it;
  • the PEM's base64 body without its -----BEGIN lines;
  • a private JWK, as an object or a JSON string.

A shared secret, a public key, an encrypted key or an OpenSSH private key throws InvalidArgument with a message saying what to do instead.

Keep these values in your backend's secrets, never in your app or your repository. If a private key leaks, add a new key and delete the old one: that ends every connection still using it.

Where the private key comes from

Read it from one of two places, whichever your host supports. The example token server reads exactly these:

VariableHoldsUse it when
FOLKWAYS_PRIVATE_KEY_FILEThe path of the key fileThe key is a file: on your laptop, a VM, or a secret mounted as a file (Kubernetes, Docker secrets)
FOLKWAYS_PRIVATE_KEYThe key itselfYour host injects secrets as environment variables (Vercel, Render, Fly.io, Heroku)
TypeScript
import { readFileSync } from 'node:fs';

const privateKey = process.env.FOLKWAYS_PRIVATE_KEY_FILE
  ? readFileSync(process.env.FOLKWAYS_PRIVATE_KEY_FILE, 'utf8')
  : process.env.FOLKWAYS_PRIVATE_KEY!;
Shell
# .env: set one of the two
FOLKWAYS_PRIVATE_KEY_FILE=./secrets/backend-2026-10.pem
# FOLKWAYS_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\nMC4CAQAwBQYDK2VwBCIEI...\n-----END PRIVATE KEY-----"

privateKey takes the one-line form as it is, with its \ns.

Sign a token

TypeScript
const { token, expiresAt } = await folkways.createToken({
  identity: 'user:42',
  capabilities: [
    { topics: 'chat/>', ops: ['subscribe', 'publish'] },
    { topics: 'typing/>', ops: ['subscribe', 'signal'] },
  ],
});
OptionDefaultMeaning
identityrequiredWho the token is for, e.g. user:42. At most 256 bytes; must not start with anon:
kind'user''user', 'agent', 'service' or 'anonymous' (no identity; for read-only visitors)
capabilities[]Topic patterns and the operations allowed on them. With none, the token can only connect
ttlMs600000 (10 min)Lifetime. At most 15 minutes

Signing happens in your process: createToken() makes no network call, so you can call it on every request. It resolves with { token, jti, expiresAt, identity, kind, capabilities }. Keep jti if you may need to revoke the token.

Add the token endpoint

Your app's authUrl points at this endpoint. Put it behind your normal login, so only signed-in users get a token, and grant each user only the topics they need.

TypeScript
app.post('/api/realtime-token', requireLogin, async (req, res) => {
  const { token } = await folkways.createToken({
    identity: `user:${req.user.id}`,
    capabilities: [{ topics: `chat/team-${req.user.teamId}/>`, ops: ['subscribe', 'publish'] }],
  });
  res.json({ token });
});

The SDK calls the endpoint with POST, a JSON body { "reason": "initial" | "expiring" | "rejected" } and your page's cookies (same origin). Answer with { "token": "…" } as JSON, or the token as plain text. Any status other than 2xx counts as "not signed in".

Not on Node.js?

Any JWT library works. Sign with the segment's key and put the segment ID in seg, the identity in sub, permissions in cap and the key ID in the kid header. See What a token contains. The Console's Connect tab has ready-made examples for Python and Go.

Publish from your backend

Send Stream or KV events from your server, for example a notice after a payment or an updated score:

TypeScript
const receipt = await folkways.publish('chat/lobby', 'notice', { text: 'Payment received' });

await folkways.publish('scores/match-7', 'score', { home: 2, away: 1 }, { delivery: 'kv', key: 'match' });

folkways.publish(topic, event, data, options?) takes the same options as a client publish (delivery, key, ttlMs, remove, headers, contentType, idempotencyKey), except that signals can't be sent from a server. It resolves with the service's receipt.

The server publishes as the identity server (change it with the identity option) with its own service token, which it signs and refreshes itself. That token may publish on every topic by default; narrow it with capabilities. The topic's rule must still allow publish.

To retry safely after a timeout, pass your own idempotencyKey (a UUID): the service deduplicates a key only within its retained window within the retained deduplication window (up to ten minutes, subject to capacity).

Failures are RealtimeErrors, as in the client. isRealtimeError and Code are exported by both entry points:

TypeScript
import { Code, isRealtimeError } from '@folkwaysio/realtime/server';

try {
  await folkways.publish('chat/lobby', 'notice', { text: 'Payment received' });
} catch (err) {
  if (isRealtimeError(err) && err.code === Code.Forbidden) console.error('no topic rule allows publish here');
  else throw err;
}

See the full list of Rest options and methods.

More from the backend

Rest signs its own service token for each call and refreshes it as needed. Scope it with capabilities to what your backend does:

FeatureRest methodThe service token needs
Personal topicspublish('$user/…', …)publish on $user/> or the user's topic
Private topicsmembers.add, set, remove, clear, listpublish on the topic
Direct messagesdm.openpublish on the rooms and on $user/>
Kick and revokekick, revokepublish on $user/{identity}, or on $user/> to revoke

Never hand a service token to an app.

On this page