# Issue tokens from your backend

URL: https://docs.folkways.io/docs/js-sdk/server

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 [#create-the-server-client]

```ts title="realtime.ts"
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.

<Callout type="warn">
  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.
</Callout>

### Where the private key comes from [#where-the-private-key-comes-from]

Read it from one of two places, whichever your host supports. The
[example token server](https://github.com/Folkways/folkways-js/tree/main/apps/token-server) reads exactly these:

| Variable | Holds | Use it when |
| --- | --- | --- |
| `FOLKWAYS_PRIVATE_KEY_FILE` | The **path** of the key file | The key is a file: on your laptop, a VM, or a secret mounted as a file (Kubernetes, Docker secrets) |
| `FOLKWAYS_PRIVATE_KEY` | The **key itself** | Your host injects secrets as environment variables (Vercel, Render, Fly.io, Heroku) |

```ts
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!;
```

```bash
# .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 `\n`s.

## Sign a token [#sign-a-token]

```ts
const { token, expiresAt } = await folkways.createToken({
  identity: 'user:42',
  capabilities: [
    { topics: 'chat/>', ops: ['subscribe', 'publish'] },
    { topics: 'typing/>', ops: ['subscribe', 'signal'] },
  ],
});
```

| Option | Default | Meaning |
| --- | --- | --- |
| `identity` | required | Who 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 |
| `ttlMs` | `600000` (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](/docs/js-sdk/kick-and-revoke) the token.

## Add the token endpoint [#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.

<Tabs items={['Express', 'Next.js', 'Hono']}>
  <Tab value="Express">
    ```ts
    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 });
    });
    ```
  </Tab>
  <Tab value="Next.js">
    ```ts title="app/api/realtime-token/route.ts"
    import { folkways } from '@/lib/realtime';
    import { getCurrentUser } from '@/lib/auth';

    export async function POST() {
      const user = await getCurrentUser();
      if (!user) return new Response('Not signed in', { status: 401 });
      const { token } = await folkways.createToken({
        identity: `user:${user.id}`,
        capabilities: [{ topics: 'chat/>', ops: ['subscribe', 'publish'] }],
      });
      return Response.json({ token });
    }
    ```
  </Tab>
  <Tab value="Hono">
    ```ts
    app.post('/api/realtime-token', requireLogin, async (c) => {
      const user = c.get('user');
      const { token } = await folkways.createToken({
        identity: `user:${user.id}`,
        capabilities: [{ topics: 'chat/>', ops: ['subscribe', 'publish'] }],
      });
      return c.json({ token });
    });
    ```
  </Tab>
</Tabs>

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".

<Callout title="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](/docs/js-sdk/authentication#what-a-token-contains).
  The Console's **Connect** tab has ready-made examples for Python and Go.
</Callout>

## Publish from your backend [#publish-from-your-backend]

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

```ts
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](/docs/js-sdk/reference/topics#publishreceipt).

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 `RealtimeError`s, as in the client. `isRealtimeError` and `Code` are exported by both entry points:

```ts
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](/docs/js-sdk/reference/server).

## More from the backend [#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:

| Feature | `Rest` method | The service token needs |
| --- | --- | --- |
| [Personal topics](/docs/js-sdk/personal-topics) | `publish('$user/…', …)` | `publish` on `$user/>` or the user's topic |
| [Private topics](/docs/js-sdk/private-topics) | `members.add`, `set`, `remove`, `clear`, `list` | `publish` on the topic |
| [Direct messages](/docs/js-sdk/direct-messages) | `dm.open` | `publish` on the rooms and on `$user/>` |
| [Kick and revoke](/docs/js-sdk/kick-and-revoke) | `kick`, `revoke` | `publish` on `$user/{identity}`, or on `$user/>` to revoke |

Never hand a service token to an app.
