# Backend

For the average Stream integration, the development work focuses on code that executes in the client. The React, React Native, Swift, Kotlin or Flutter SDKs connect to the chat API directly from the client. However, some tasks must be executed from the server for safety, and the backend has full access to the chat API.

## Start here

- [Authentication and tokens](https://getstream.io/docs/platform/authentication/): Token signing, expiry and revocation in detail.
- [App settings](https://getstream.io/chat/docs/node/app-setting-overview/): App-level configuration that should only be changed from the backend.
- [Client-side overview](https://getstream.io/chat/docs/node/client-side/): Connecting users, presence and everything else that runs in your app.

>
> **Tip:** This SDK is the server half of your integration. Your users connect from your app with a client SDK, and anything that needs a connected user or a live WebSocket belongs there: client initialization, guest and anonymous sessions, typing indicators and presence. See the [client-side overview](https://getstream.io/chat/docs/node/client-side/) for what lives there. Token signing stays on this side, because it needs your API secret.
>

Two tasks must run on the server:

- [Generating user tokens](https://getstream.io/chat/docs/node/#generating-user-tokens)

- [Syncing users](https://getstream.io/chat/docs/node/#syncing-users)

Other features _can_ be managed from client-side code in specific cases, but manage them from the server unless your use case requires otherwise:

- [Syncing channels](https://getstream.io/chat/docs/node/#syncing-channels)

- [Adding and removing members and moderators](https://getstream.io/chat/docs/node/)

- [Sending messages](https://getstream.io/chat/docs/node/)

## How the pieces fit together

This SDK calls the Stream API from your backend, authenticated with your API secret. Your users connect from your app with a client SDK, using a token your backend signs.

```mermaid
flowchart LR
  app[Your app] <-->|WebSocket| api[Stream API]
  backend[Your backend] -->|REST| api
  backend -. user token .-> app
```

## Stream CLI and Agent Skills

Manage Stream from your terminal with the [Stream CLI](https://getstream.io/cli/docs/), including scripting and AI-agent workflows. Install the CLI and the default [Agent Skills](https://getstream.io/agent-skills/docs/):

```bash
curl -fsSL https://getstream.io/cli.sh | bash
getstream skills
```

Then ask your agent in plain English, for example:

```text
/stream List recent channels in my app.
```

See the [CLI docs](https://getstream.io/cli/docs/) and [Agent Skills docs](https://getstream.io/agent-skills/docs/) for more.

This quick start covers the basics of a backend integration. If we don't have an SDK for your favorite language be sure to review the [REST documentation](https://getstream.github.io/protocol/).

### Installation

Install the `@stream-io/node-sdk` package:

```bash label="Node.js"
npm install @stream-io/node-sdk
# or
yarn add @stream-io/node-sdk
```

```bash label="Node.js (stream-chat@9)"
npm install stream-chat@9
# or
yarn add stream-chat@9
```

>
> **Note:** Up to stream-chat@9 the package was suitable for both client-side and server-side usage. Starting from v10, use [`@stream-io/node-sdk`](https://www.npmjs.com/package/@stream-io/node-sdk) for server-side operations. If you need to connect a user from a Node.js integration, you can still use `stream-chat`, but only client-side operations will be available. See the [v10 migration guide](https://github.com/GetStream/stream-chat-js/blob/release-v10/ai-docs/v10-breaking-changes.md) for the breaking changes and mapping to `@stream-io/node-sdk`. The stream-chat@9 snippets stay in these docs for a limited time, but no new features are added to v9.
>

### Generating user tokens

The backend creates a token for a user. You hand that token to the client side during login or registration. This token allows the client side to connect to the chat API for that user. Stream's permission system does the heavy work of determining which actions are valid for the user, so the backend just needs enough logic to provide a token to give the client side access to a specific user.

The following code shows how to instantiate a client and create a token for a user on the server:

```js label="Node.js"
// npm install @stream-io/node-sdk
import { StreamClient } from "@stream-io/node-sdk";
// or: const { StreamClient } = require("@stream-io/node-sdk");

// instantiate your stream client using the API key and secret
// the secret is only used server side and gives you full access to the API
const client = new StreamClient("{{ api_key }}", "{{ api_secret }}");

// generate a token for the user with id 'john'
const token = client.generateUserToken({ user_id: "john" });
// next, hand this token to the client in your login or registration response
```

```js label="Node.js (stream-chat@9)"
// yarn add stream-chat
import { StreamChat } from "stream-chat";
// if you're using common js
const StreamChat = require("stream-chat").StreamChat;

// instantiate your stream client using the API key and secret
// the secret is only used server side and gives you full access to the API
const serverClient = StreamChat.getInstance(
  "{{ api_key }}",
  "{{ api_secret }}",
);
// you can still use new StreamChat('api_key', 'api_secret');

// generate a token for the user with id 'john'
const token = serverClient.createToken("john");
// next, hand this token to the client in your in your login or registration response
```

You can also generate tokens that expire after a certain time. The [tokens & authentication section](https://getstream.io/docs/platform/authentication/) explains this in detail.

### Syncing users

When a user starts a chat conversation with another user both users need to be present in Stream's user storage. So you'll want to make sure that users are synced in advance. The update users endpoint allows you to update 100 users at once, an example is shown below:

```js label="Node.js"
const response = await client.upsertUsers([
  {
    id: userID,
    role: "admin",
    custom: { mycustomfield: "123" },
  },
]);
```

```js label="Node.js (stream-chat@9)"
const response = await client.upsertUsers([
  {
    id: userID,
    role: "admin",
    mycustomfield: "123",
  },
]);
```

```bash label="Bash"
curl --location --request POST 'https://chat.stream-io-api.com/users?api_key={api_key}' \
--header 'Accept: application/json' \
--header 'Stream-Auth-Type: jwt' \
--header 'Authorization: {{ YOUR TOKEN HERE }}' \
--header 'Content-Type: application/json' \
--data-raw '{
 "users": { "Lakshmi": { "id" : "Lakshmi", "name": "Seethalakshmi" }}
}'
```

Note that user roles can only be changed server side. The role you assign to a user impacts their permissions and which actions they can take on a channel.

### Syncing channels

You can create channels client side, but for many applications you'll want to restrict the creation of channels to the backend. Especially if a chat is related to a certain object in your database. One example is building a livestream chat like Twitch. You'll want to create a channel for each Stream and set the channel creator to the owner of the Stream. The example below shows how to create a channel and update it:

```js label="Node.js"
const channel = client.chat.channel("messaging", "kung-fu");

// create the channel and set created_by to user id 4645
await channel.getOrCreate({ data: { created_by_id: "4645" } });

const update = await channel.update({
  data: {
    custom: {
      name: "myspecialchannel",
      image: "imageurl",
      mycustomfield: "123",
    },
  },
});
```

```js label="Node.js (stream-chat@9)"
const channel = client.channel(type, id, {
  created_by_id: "4645",
});
await channel.create();
// create the channel and set created_by to user id 4645
const update = await channel.update({
  name: "myspecialchannel",
  image: "imageurl",
  mycustomfield: "123",
});
```

```bash label="Bash"
Channel Creation

curl --location --request POST 'https://chat-proxy-singapore.stream-io-api.com/channels/{channel_type}/{cid}/query?api_key={api_key}' \
--header 'Stream-Auth-Type: jwt' \
--header 'Authorization: {{ YOUR TOKEN HERE }}' \
--header 'Content-Type: application/json' \
--data-raw '{
"data": {
"created_by_id" : "Lakshmi",
"members" : [ { "user_id" : "Bree" }, { "user_id" : "Chree"} ]
}
}'

Update Channel 

curl --location --request POST 'https://chat-proxy-singapore.stream-io-api.com/channels/{channel_type}/{cid}?api_key=(api_key}' \
--header 'Stream-Auth-Type: jwt' \--header 'Authorization: {{ YOUR TOKEN HERE }}' \
--header 'Content-Type: application/json' \
--data-raw '{
"name": "Group channel",
"color": "green",
"message": { "user" : { "id" : "Lakshmi" },
"text" : "Channel color changed by Lakshmi"
}}'
```

You can also add a message on the channel when updating it. It's quite common for chat apps to show messages like: "Jack invited John to the channel", or "Kate changed the color of the channel to green".

### Adding members or moderators

The backend SDKs also make it easy to add or remove members from a channel. The example below shows how to add and remove members:

```js label="Node.js"
await channel.update({
  add_members: [{ user_id: "thierry" }, { user_id: "josh" }],
});
await channel.update({ remove_members: ["tommaso"] });

await channel.update({ add_moderators: ["thierry"] });
await channel.update({ demote_moderators: ["thierry"] });
```

```js label="Node.js (stream-chat@9)"
await channel.addMembers(["thierry", "josh"]);
await channel.removeMembers(["tommaso"]);

await channel.addModerators(["thierry"]);
await channel.demoteModerators(["thierry"]);
```

```bash label="Bash"
curl --location --request POST 'https://chat-proxy-singapore.stream-io-api.com/channels/{channel_type}/{cid}?api_key={api_key}' \
--header 'Accept: application/json' \
--header 'Stream-Auth-Type: jwt' \
--header 'Authorization: {{ YOUR TOKEN HERE }}' \
--header 'Content-Type: application/json' \
--data-raw '{
 "add_members" : ["Seetha", "Viswa"]
}'
```

### Sending messages

It's quite common that certain actions in your application trigger a message to be sent. If a new user joins an app some chat apps will notify you that your contact joined the app. The example below shows how to send a message from the backend. It's the same syntax as you use client side, but specifying which user is sending the message is required:

```js label="Node.js"
const { message } = await channel.sendMessage({
  message: {
    text: "@Josh I told them I was pesca-pescatarian. Which is one who eats solely fish who eat other fish.",
    user_id: "john",
    mentioned_users: ["josh"],
    attachments: [
      {
        type: "image",
        asset_url: "https://bit.ly/2K74TaG",
        thumb_url: "https://bit.ly/2Uumxti",
        custom: { myCustomField: 123 },
      },
    ],
    custom: { anotherCustomField: 234 },
  },
});
```

```js label="Node.js (stream-chat@9)"
const toBeSent = {
  text: "@Josh I told them I was pesca-pescatarian. Which is one who eats solely fish who eat other fish.",
  attachments: [
    {
      type: "image",
      asset_url: "https://bit.ly/2K74TaG",
      thumb_url: "https://bit.ly/2Uumxti",
      myCustomField: 123,
    },
  ],
  mentioned_users: [josh.id],
  anotherCustomField: 234,
};
const message = await channel.sendMessage({ ...toBeSent, user_id: "john" });
message = {
  text: "@Josh I told them I was pesca-pescatarian. Which is one who eats solely fish who eat other fish.",
  attachments: [
    {
      type: "image",
      asset_url: "https://bit.ly/2K74TaG",
      thumb_url: "https://bit.ly/2Uumxti",
      myCustomField: 123,
    },
  ],
  mentioned_users: [josh["id"]],
  anotherCustomField: 234,
};
```

```bash label="Bash"
curl --location --request POST 'https://chat-proxy-singapore.stream-io-api.com/channels/{channel_type}/{cid}/message?api_key={api_key}' \
--header 'Stream-Auth-Type: jwt' \
--header 'Authorization: {{ YOUR TOKEN HERE }}' \
--header 'Content-Type: application/json' \
--data-raw '{
 "message" :
 {
   "text" : "Hello World",
   "user" : { "id" : "Lakshmi" }
  }
}'
```

### Changing application settings

Some application settings should only be changed using the back end for security reasons:

- [Webhook Configuration](https://getstream.io/docs/platform/webhooks/)

- [SQS Configuration](https://getstream.io/docs/platform/webhooks/#sqs)

### API changes

A **breaking change** is a change that may require you to make changes to your application in order to avoid disruption to your integration. Stream will never introduce a breaking change without notifying its customers and giving them plenty of time to make the appropriate changes on their end. The following are a few examples of changes we consider breaking:

- Changes to existing permission definitions.

- Removal of an allowed parameter, request field or response field.

- Addition of a required parameter or request field without default values.

- Changes to the intended functionality of an endpoint. _For example, if a DELETE request previously used to soft delete the resource but now hard deletes the resource._

- Introduction of a new validation.

A **non-breaking change** is a change that you can adapt to at your own discretion and pace without disruption. Ensure that your application is designed to be able to handle the following types of non-breaking changes without prior notice from Stream:

- Addition of new endpoints.

- Addition of new methods to existing endpoints.

- Addition of new fields in the following scenarios:

- New fields in responses.

- New optional request fields or parameters.

- New required request fields that have default values.

- Addition of a new value returned for an existing text field.

- Changes to the order of fields returned within a response.

- Addition of an optional request header.

- Removal of redundant request header.

- Changes to the length of data returned within a field.

- Changes to the overall response size.

- Changes to error messages. We do not recommend parsing error messages to perform business logic. Instead, you should only rely on HTTP response codes and [error codes](https://getstream.io/docs/platform/api-error-codes/).

- Fixes to HTTP response codes and error codes from incorrect code to correct code.

- Prefix your custom data properties, we could introduce new features that might clash with custom property names you are using, by prefixing them you avoid this problem.

## What's next

Once your first message is through, these are good places to go deeper:

- [Creating channels](https://getstream.io/chat/docs/node/creating-channels/): Channel types, custom data and everything else about setting up conversations.
- [Sending messages](https://getstream.io/chat/docs/node/send-message/): Attachments, custom fields and the rest of the message API.
- [Webhooks](https://getstream.io/docs/platform/webhooks/): React to chat events from your own backend.

## FAQ

**Which webhook events does chat send?**

The [event catalogue](https://getstream.io/chat/docs/node/webhook-events/) lists every webhook event and most payloads.

**Can I check messages before they're delivered?**

Yes, with the [before message send webhook](https://getstream.io/chat/docs/node/before-message-send-webhook/).

**Does this SDK cover other Stream products?**

Yes. Each [backend SDK](https://getstream.io/docs/platform/backend-sdks/) covers every product; build one client and reuse it.

**Are server-sent messages moderated?**

Not by default. Set `force_moderation` to `true` when sending. The flag is server-side only and ignored when sent from a client-side SDK. See [chat moderation](https://getstream.io/moderation/docs/node/integrations/stream-chat/#server-side-integration).

---

For the most recent version of this documentation, visit [https://getstream.io/chat/docs/node/](https://getstream.io/chat/docs/node/).