Stream API and client integration

How do the Chat Client, Server, & Stream API communicate with each other?

This article will cover how the Stream Chat Client, Server, and Stream API all communicate with each other. If you have any further questions, please reach out to support at https://getstream.io/contact/support/.

The Stream Chat client runs on a user’s local device, it is also what opens up a websocket/concurrent connection. The server is spun up on the Stream customer’s end. The Stream API is self-explanatory and interacts with both the client and server.

The following code example will show you how a user generates tokens from their server and then connects to the Stream API. The below diagram gives a visual representation of this process.

1. Server-side

Once you’ve created your App, you can access your App Secret and Key in the Stream Dashboard. These credentials enable server-side access. Note: With server-side access, a trusted user can bypass all client-side permissions, so it’s important to never expose the application secret client-side.

Now, we want our chat client to connect to the Stream API, but first, we need to generate a token (JWT). Tokens are generated server-side. Beyond generating and returning tokens, server-side Stream code may also include creating channels, promoting users to admins, or taking moderation measures such as banning or removing users from the app.

The below code shows how to create a token using the JS SDK:

const chatClient = new StreamChat(appKEY, secret);
const user_id = "bob";
const token = chatClient.createToken(user_id);

The below code shows how to use a basic method for generating a token from a client-side POST request:

const chatClient = new StreamChat(appKEY, secret);

server.post(“/token”, async (req, res) => {
 const { user_id } = req.body;
 try {
  const token = await chatClient.createToken(user_id.toString());
  res.status(200).json({
   payload: token,
  });
 } catch (error) {
  console.log(error);
  res.sendStatus(400);
 }
});

2. Client-side

Once the client has a token, it can connect directly to the Stream API with the connectUser() method. Here are some important best practices on how to use this method.

const set = await chatClient.connectUser({ id: userID }, token);

3. User Authentication & Stream API

Once the user has been authenticated with the connectUser() method, they have access to certain Stream data (e.g. channels, messages, etc.) based on permissions and may continue interacting with our API via the client.

Review

Above, we instantiated the chat client, created the token server-side, and then the user would be authenticated, so they can connect the client to the Stream API. Now the client will continue to interact with the Stream API until it’s disconnected.

© Getstream.io, Inc. All Rights Reserved.