# Connect your app

URL: https://docs.folkways.io/docs/get-started/connect-your-app

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

<Steps>
  <Step>
    ### Install the SDK in your app [#install-the-sdk-in-your-app]

    ```bash
    npm install @folkwaysio/realtime
    ```

    It runs in browsers, React Native, Node.js 20+, Deno and Bun. See [Installation](/docs/js-sdk/installation).
  </Step>
  <Step>
    ### Connect, subscribe and publish [#connect-subscribe-and-publish]

    ```ts title="app.ts" check=connect
    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.
  </Step>
</Steps>

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 [#if-it-fails]

The error's `codeName` says what went wrong:

| Error | Likely cause |
| --- | --- |
| `AuthInvalid` | The key ID doesn't match a signing key in this segment, or the private key isn't that key's pair |
| `Forbidden` | No topic rule matches `hello/world`, or the token doesn't grant the operation |
| `Suspended` | The segment is turned off, or the workspace's package isn't active |
| `TransportUnavailable` | The Realtime URL is wrong or unreachable |
| Your endpoint's error | The user isn't signed in, or the endpoint isn't reachable from the app |

See [Troubleshooting](/docs/guides/troubleshooting) for more symptoms, and [Error codes](/docs/realtime-api/errors)
for every code.

## Check from a script [#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](/docs/get-started/console-setup#copy-your-connection-values) in `.env`, then run
`node --env-file=.env hello.mjs`.

```js title="hello.mjs" check=first-event
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();
```

```text
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](/docs/js-sdk/installation#nodejs-20).

## Next [#next]

<Cards>
  <Card title="Chat room example" href="/docs/examples/chat-room" description="Messages, read receipts, typing and presence on one topic." />
  <Card title="Topics" href="/docs/concepts/topics" description="Name your topics and decide who may use them." />
  <Card title="Primitives" href="/docs/primitives" description="Choose between Stream, KV, Signal and Presence." />
</Cards>
