# Join tickets in Node

> A ticket endpoint for your Node backend, with no dependencies: sign a ticket for one user and one room, and hand it to the page.

[Join tickets](https://jsflow.com/docs/guides/join-tickets.md) explains what a ticket is and why. This page is the Node side of it: about twenty lines to sign one, and an endpoint your page calls. Node 18 or newer, and no packages: the signing uses `node:crypto`.

(This is a ticket **backend**. The SDK itself runs in a browser page, not in Node, so a Node process cannot join a room as a peer; it decides who may.)

## Signing a ticket

```js run compare="examples/tickets/node/ticket.mjs" title="ticket.mjs"
import { createHmac } from 'node:crypto';

const b64url = (s) => Buffer.from(s, 'utf8').toString('base64url');

export function mintTicket({
  secretKey, keyId, app, room, sub, region,
  ttlSeconds = 300,
  iat = Math.floor(Date.now() / 1000),
}) {
  const header = { alg: 'HS256', typ: 'JWT', kid: keyId };
  const claims = {
    app, room, sub, iat, exp: iat + ttlSeconds,
    ...(region ? { region } : {}),
  };
  const input = `${b64url(JSON.stringify(header))}.`
    + b64url(JSON.stringify(claims));
  const mac = createHmac('sha256', secretKey)
    .update(input).digest('base64url');
  return `${input}.${mac}`;
}
```

- **`secretKey`** is the app's secret key, `sk_…`, and `keyId` is that key's id, `key_…`; both are in the dashboard when you create the key. The secret key lives on your server only: an environment variable or your secrets store, never in a page or a repository.
- **`sub`** is your user's id. It comes from **your** session, never from the request body: every other peer sees it as that peer's user id (`room.user(peer)`).
- **`ttlSeconds`** is at most 600 (ten minutes); the examples use 300. A ticket can be used again until it expires, so keep it short.
- **`region`** is optional, and only for an app pinned to a region: it makes the first request go straight there. Leave it out unless your app is pinned.

The version in the [jsflow-community repository](https://github.com/precisit/jsflow-community/tree/main/examples/tickets/node) (`examples/tickets/node/ticket.mjs`) adds checks on every argument and is the one with tests behind it, against jsflow's test vectors; a test checks that the code on this page signs the same tickets, byte for byte.

## The endpoint

Sign a ticket when a signed-in user asks to enter a room, after you have decided that they may:

```js title="server.mjs"
import { createServer } from 'node:http';
import { mintTicket } from './ticket.mjs';

const { JSFLOW_SECRET_KEY, JSFLOW_KEY_ID, JSFLOW_APP } = process.env;

// Replace this with your own authentication: the signed-in
// user's id, or null.
const currentUser = (req) => req.headers['x-demo-user'] ?? null;

createServer(async (req, res) => {
  const send = (status, body) => {
    res.writeHead(status, { 'content-type': 'application/json' });
    res.end(JSON.stringify(body));
  };
  if (req.method !== 'POST' || req.url !== '/ticket') {
    return send(404, { err: 'not_found' });
  }
  const sub = currentUser(req);
  if (!sub) return send(401, { err: 'unauthorized' });

  let body = '';
  for await (const chunk of req) body += chunk;
  const { room } = JSON.parse(body);

  // Decide here whether this user may enter this room.
  // The ticket is your yes.
  const ticket = mintTicket({
    secretKey: JSFLOW_SECRET_KEY,
    keyId: JSFLOW_KEY_ID,
    app: JSFLOW_APP,
    room,
    sub,
  });
  send(200, { ticket, expiresAt: Date.now() + 300_000 });
}).listen(8787);
```

The complete file in the repository also limits the body size and answers bad JSON with a 400. Call it from the page with a function, so every `join()` gets a fresh ticket:

```ts check title="client.ts"
import { join } from 'jsflow-sdk';

const room = await join({
  app: 'pk_…',
  room: 'team-7',
  ticket: async () => {
    const res = await fetch('/ticket', {
      method: 'POST',
      headers: { 'content-type': 'application/json' },
      body: JSON.stringify({ room: 'team-7' }),
    });
    if (!res.ok) throw new Error(`ticket: ${res.status}`);
    return (await res.json()).ticket;
  },
});
room.on('state', (s) => console.log(s));
```

## Rotating the secret key

Two secret keys can be active at once. The ticket's `kid` says which one signed it, so create the new key, deploy the new `JSFLOW_SECRET_KEY` and `JSFLOW_KEY_ID`, and revoke the old key once tickets signed with it have expired (ten minutes at most).

## When a join is refused

A ticket that is expired, for another room or app, signed by a revoked key or for a blocked user is refused, and the page's `join()` rejects with a `JoinError` whose `code` says which: `ticket_required`, `ticket_invalid`, `ticket_expired` or `blocked`. See [Troubleshooting](https://jsflow.com/docs/guides/troubleshooting.md).

Source: https://jsflow.com/docs/guides/join-tickets-in-node/
