Client and User

The recommended way of connecting your chat application to the Stream Chat API is through the use of useCreateChatClient hook.

Client Instance

You can create an instance with the new keyword or through the use of static method getInstance - the latter will create and store your instance and subsequent getInstance calls will return what has been stored.

import { Chat } from "stream-chat-react";
import { StreamChat } from "stream-chat";

const client = new StreamChat(apiKey);

// or

const client = StreamChat.getInstance(apiKey);

Connecting and Disconnecting a User

To authenticate a user you’ll need a token. Typically, you send this token from your backend to your frontend when the user logs in. See the Tokens & Authentication documentation to learn more about creating tokens. For our purposes here, we will assume you have created and retrieved a token.

To connect a user, call the connectUser method on your client instance with the user object and token provided as arguments. Connect the user directly after instantiating the client to establish a websocket connection with the Stream Chat API. Once the connection has been opened, your client instance will begin receiving events from the API.

const connectionPromise = client.connectUser(
  {
    id: "dave-matthews",
    name: "Dave Matthews",
  },
  token,
);

To dispose of the active connection (upon component cleanup, for example) you’d call disconnectUser method. It’s generally recommended to wait for the connection promise to resolve before disconnecting.

await connectionPromise;
client.disconnectUser();
© Getstream.io, Inc. All Rights Reserved.