Initialization & Users

Last Edit: Mar 03 2020

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.


const client = new StreamChat('YOUR_API_KEY', {
    timeout: 6000,
});
                    

// typically done in your BaseApplication class
StreamChat.init("YOUR_API_KEY", new ApiClientOptions.Builder().Timeout(6000).build(), getApplicationContext());

// set the user to establish the websocket connection
// usually done when you open the chat interface
Client client = StreamChat.getInstance(getApplication());
                    

import StreamChatCore

// In your AppDelegate:

// Setup the Stream Chat Client.
Client.config = .init(apiKey: "YOUR_API_KEY")

// Note: If you want to enable logs for requests and events you can enable them with extra parameter:  `logOptions`.
                    

// Typically done in your Application class
val client = ChatClient.Builder("{{ api_key }}", context).build()

// Static reference to initialised client
val client = ChatClient.instance()
                    

final client = Client(
  "qk4nn7rpcn75",
  logLevel: Level.INFO,
  connectTimeout: Duration(milliseconds: 6000),
  receiveTimeout: Duration(milliseconds: 6000),
);
                    

Setting the User

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


await client.setUser(
    {
        id: 'john',
        name: 'John Doe',
        image: 'https://getstream.io/random_svg/?name=John',
    },
    'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiamxhaGV5In0.OkDbpbujWJ-XIVHaf00Dnqt3v8Yp_nQ6CGzm-Z4QUVc',
);
                    

// this hashmap allows you to add any custom fields you want to store about your user
// the UI components will pick up name and image by default

HashMap<string, object=""> extraData = new HashMap<>();
extraData.put("name", "Bender");
extraData.put("image", "https://bit.ly/321RmWb");

User user = new User(USER_ID, extraData);
client.setUser(user, "FEED_USER_TOKEN", new ClientConnectionCallback() {
    @Override
    public void onSuccess(User user) {
        Log.i(TAG, String.format("Connection established for user %s", user.getName()));
    }

    @Override
    public void onError(String errMsg, int errCode) {
        Log.e(TAG, String.format("Failed to establish websocket connection: %s", errMsg));
    }
});</string,>
                    

// Create a user, when he/she was logged in.
let user = User(id: "bender", name: "Bender", avatarURL: URL(string: "https://bit.ly/321RmWb")!)

// You can setup a user token in 2 ways.

// 1. Setup the current user with a token.
Client.shared.set(user: user, token: token)

// 2. Setup the current user with a token provider.
Client.shared.set(user: user) { tokenProvider in
    // Make a request here to your backend to get a token for the current user.
    tokenProvider(token)
}
                    

val user = User("user-id")
val token = "{{ chat_user_token }}"

// extraData allows you to add any custom fields you want to store about your user
user.extraData["name"] = "Bender"
user.extraData["image"] = "https://bit.ly/321RmWb"


client.setUser(user, token, object : InitConnectionListener() {
    override fun onSuccess(data: ConnectionData) {
        val user = data.user
        val connectionId = data.connectionId
    }

    override fun onError(error: ChatError) {
        error.printStackTrace()
    }
})
                    

final user = User(id: "john", extraData: {
  "name": "John Doe",
  "image": "<a href="https://getstream.io/random_svg/?name=John" target="_self">https://i.imgur.com/fR9Jz14.png</a>",
});

await client.setUser(user, "{{ chat_user_token }}");
                    

Note how we are waiting for the setUser 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.

Set User Parameters

Name Type Description Default Optional
user object The 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
userToken string The user authentication token. See below for details default

User Fields

The id field is the only required field for the user. There are a few other fields you should know about though:

Name Type Description Default Optional
id string The id field is required
name string The name of the user used by our component libraries. This is just a convention and not a required field.
image string The image for this user. This is used by our component libraries but other than that is not required.
invisible boolean Determines if the user should show as offline even when they are online (only visible on the event.me user info).
banned boolean True when the user was banned from all channels
last_active string Reserved field indicating when the user was last active.
online boolean Reserved field indicating if the user is currently online.
role string Reserved field indicating the user's role. Can be either admin, user or guest.
mutes array Reserved field containing a list of mutes by this user (only visible on the event.me user info).
created_at date Reserved field indicating when the user was created.
updated_at date Reserved field indicating when the user was last updated.