folkwaysDocs
Get started

Connect your app

Install the SDK in your app, connect with your token endpoint, then subscribe and publish your first event.

Install the SDK in your app

Shell
npm install @folkwaysio/realtime

It runs in browsers, React Native, Node.js 20+, Deno and Bun. See Installation.

Connect, subscribe and publish

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

const client = new Folkways.Realtime({
  url: 'https://realtime.folkways.net', // the Realtime URL from the segment's Connect tab
  authUrl: '/api/realtime-token',        // your endpoint from the previous step
});
const session = await client.connect();
console.log('connected as', session.identity);

const hello = client.topic<{ message: { text: string } }>('hello/world');

const subscription = hello.subscribe((msg) => {
  console.log(`${msg.publisher}: ${msg.data.text}`);
});
await subscription.ready;

await hello.publish('message', { text: 'Hello, Folkways!' });

Open the app in two browsers, signed in as different users: a message sent from one appears in both.

The SDK asks your endpoint for a token, connects over a WebSocket (or HTTP where WebSockets are blocked), refreshes the token before it expires, and reconnects and resubscribes after network drops.

If it fails

The error's codeName says what went wrong:

ErrorLikely cause
AuthInvalidThe key ID doesn't match a signing key in this segment, or the private key isn't that key's pair
ForbiddenNo topic rule matches hello/world, or the token doesn't grant the operation
SuspendedThe segment is turned off, or the workspace's package isn't active
TransportUnavailableThe Realtime URL is wrong or unreachable
Your endpoint's errorThe user isn't signed in, or the endpoint isn't reachable from the app

See Troubleshooting for more symptoms, and Error codes for every code.

Check from a script

To test your segment before your app is ready, this Node.js 22+ script plays both parts: it signs a token the way your backend does, then connects with it. Put the values from the Connect tab in .env, then run node --env-file=.env hello.mjs.

hello.mjs
JavaScript
import { readFileSync } from 'node:fs';
import { Folkways } from '@folkwaysio/realtime';
import { Folkways as Server } from '@folkwaysio/realtime/server';

const env = (name) => {
  const value = process.env[name];
  if (!value) throw new Error(`Set ${name} in .env`);
  return value;
};
const url = env('FOLKWAYS_URL');

// Your backend's part: sign a token for one user. This makes no network call.
const backend = new Server.Rest({
  url,
  segment: env('FOLKWAYS_SEGMENT_ID'),
  signingKey: { kid: env('FOLKWAYS_KEY_ID'), privateKey: readFileSync(env('FOLKWAYS_PRIVATE_KEY_FILE'), 'utf8') },
});
const getToken = async () => {
  const { token } = await backend.createToken({
    identity: 'user:hello',
    capabilities: [{ topics: 'hello/>', ops: ['subscribe', 'publish'] }],
  });
  return token;
};

// Your app's part: connect with the token, subscribe, publish.
const client = new Folkways.Realtime({ url, token: getToken });
const session = await client.connect();
console.log('connected as', session.identity, 'over', session.transport);

const topic = client.topic('hello/world');
let resolveReceived;
const received = new Promise((resolve) => { resolveReceived = resolve; });
const subscription = topic.subscribe((message) => resolveReceived(message));
await subscription.ready; // subscribed: new events reach us from here on

await topic.publish('message', { text: 'Hello, Folkways!' });

const message = await received;
console.log(`${message.publisher} said:`, message.data);
await client.close();
Output
connected as user:hello over websocket
user:hello said: { text: 'Hello, Folkways!' }

On Node.js 20, which has no global WebSocket, pass one from the ws package; see Installation.

Next

On this page