Initialization & Users

LAST EDIT Apr 13 2021

The code below creates a chat client instance for browser/mobile usage. Additional options, such as API base URL and request timeouts, can be provided to the client.Setting.

1
2
3
4
5
6
import { StreamChat } from 'stream-chat'; 
 
// client-side you initialize the Chat client with your API key 
const client = new StreamChat('YOUR_API_KEY', { 
    timeout: 6000, 
});
1
2
3
4
5
// Typically done in your Application class using your API Key 
ChatClient client = new ChatClient.Builder("YOUR_API_KEY", context).build(); 
 
// Static reference to initialised client 
ChatClient staticClientRef = ChatClient.instance();
1
2
3
4
5
6
7
8
9
/// 1: Create a static token provider. Use it for testing purposes. 
let token = Token("CHAT_USER_TOKEN") 
let tokenProvider = TokenProvider.static(token) 
 
/// 2: Create a `ChatClientConfig` with the API key. 
let config = ChatClientConfig(apiKeyString: "YOUR_API_KEY") 
 
/// 3: Create a `ChatClient` instance with the config and the token provider. 
chatClient = ChatClient(config: config, tokenProvider: tokenProvider)
1
2
3
4
5
// Typically done in your Application class using your API Key 
val client = ChatClient.Builder("YOUR_API_KEY", context).build() 
 
// Static reference to initialised client 
val staticClientRef = ChatClient.instance()
1
2
3
4
5
6
7
// client-side you initialize the Chat client with your API key 
final client = Client( 
  "YOUR_API_KEY", 
  logLevel: Level.INFO, 
  connectTimeout: Duration(milliseconds: 6000), 
  receiveTimeout: Duration(milliseconds: 6000), 
);

Connecting the User

Copied!

Once initialized, you must specify the current user with connectUser:

1
2
3
4
5
6
7
8
await client.connectUser( 
    { 
        id: 'john', 
        name: 'John Doe', 
        image: 'https://getstream.io/random_svg/?name=John', 
    }, 
    'CHAT_USER_TOKEN', 
);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
User user = new User(); 
user.setId("bender"); 
 
HashMap<String, Object> extraData = new HashMap<>(); 
extraData.put("name", "Bender"); 
extraData.put("image", "https://bit.ly/321RmWb"); 
user.setExtraData(extraData); 
 
// You can setup a user token in two ways: 
 
// 1. Setup the current user with a JWT token 
String token = "CHAT_USER_TOKEN"; 
client.connectUser(user, token).enqueue(result -> { 
    if (result.isSuccess()) { 
        // Logged in 
        User userRes = result.data().getUser(); 
        String connectionId = result.data().getConnectionId(); 
    } else { 
        // Handle result.error() 
    } 
}); 
 
// 2. Setup the current user with a TokenProvider 
TokenProvider tokenProvider = new TokenProvider() { 
    @NotNull 
    @Override 
    public String loadToken() { 
        return yourTokenService.getToken(user); 
    } 
}; 
client.connectUser(user, tokenProvider).enqueue(result -> {/* ... */});
1
2
3
4
5
6
7
8
9
10
import UIKit 
import StreamChat 
 
// This call is only needed if you've disconnected before. 
chatClient.connectionController().connect { error in 
    if let error = error { 
        // handle possible errors 
        print(error) 
    } 
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
val user = User( 
    id = "bender", 
    extraData = mutableMapOf( 
        "name" to "Bender", 
        "image" to "https://bit.ly/321RmWb", 
    ), 
) 
 
// You can setup a user token in two ways: 
 
// 1. Setup the current user with a JWT token 
val token = "CHAT_USER_TOKEN" 
client.connectUser(user, token).enqueue { result -> 
    if (result.isSuccess) { 
        // Logged in 
        val user: User = result.data().user 
        val connectionId: String = result.data().connectionId 
    } else { 
        // Handle result.error() 
    } 
} 
 
// 2. Setup the current user with a TokenProvider 
val tokenProvider = object : TokenProvider { 
    // Make a request to your backend to generate a valid token for the user 
    override fun loadToken(): String = yourTokenService.getToken(user) 
} 
client.connectUser(user, tokenProvider).enqueue { /* ... */ }
1
2
3
4
5
6
final user = User(id: "john", extraData: { 
  "name": "John Doe", 
  "image": "[object Object]", 
}); 
 
await client.setUser(user, "CHAT_USER_TOKEN");

Note how we are waiting for the connectUser API call to be completed before moving forward. You should always make sure to have the user set before making any more calls. All SDKs make this very easy and wait or queue requests until then.

Connect User Parameters

Copied!
nametypedescriptiondefaultoptional
userobjectThe user object. Must have id field. It can have as many custom fields as you want, as long as the total size of the object is less than 5KB
userTokenstringThe user authentication token. See Tokens & Authentication for details default

WebSocket Connections

Copied!

The connectUser (or SDK equivalent) function performs several operations when used. Please note that this method should never be used server-side.

  1. Creates a new user if the user_id is not already registered with the application, incrementing the monthly active users

  2. Updates the user in the application (will add/modify existing fields but will not overwrite/delete previously set fields unless the key is used)

  3. Opens a WebSocket connection and increments the Concurrent Connections for the application

The React, React-native, iOS, Android, and Flutter SDK's handle WebSocket disconnection logic, but if a manual disconnect is required in your application, then there are the following options

1
await chatClient.disconnectUser();
1
ChatClient.instance().disconnect();
1
ChatClient.instance().disconnect()
1
2
3
import StreamChat 
 
chatClient.connectionController().disconnect()
1
client.disconnect()