Initialization & Users

Last Edit: Feb 02 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 BaseApplication class
StreamChat.init(
    "YOUR_API_KEY", ApiClientOptions.Builder().Timeout(6000).build(),
    applicationContext
)

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

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)
}
                    

// 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
val extraData = HashMap<string, any="">()
extraData.put("name", "Bender")
extraData.put("image", "https://bit.ly/321RmWb")
val user = User("USER_ID", extraData)
client.setUser(user, "FEED_USER_TOKEN", object : ClientConnectionCallback {
    override fun onSuccess(user: User) {
        Log.i(TAG,String.format("Connection established for user %s", user.name) )
    }

    override fun onError(errMsg: String, errCode: Int) {
        Log.e(TAG,
            String.format("Failed to establish websocket connection: message %s",
                errMsg
            )
        )
    }
})</string,>
                    

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.

Tokens

Tokens are used to authenticate the user. Typically, you send this token from your backend to the client-side when a user registers or logs in.

You can generate tokens server side with the following syntax:


const client = new StreamChat('', '{{ chat_api_secret }}');
const token = client.createToken('john');
                    

# pip install stream-chat

import stream_chat

chat_client = stream_chat.StreamChat(api_key="STREAM_KEY", api_secret="STREAM_SECRET")
token = chat_client.create_token('john')
                    

# gem install stream-chat-ruby

require 'stream-chat'

client = StreamChat::Client.new(api_key='STREAM_KEY', api_secret='STREAM_SECRET')
client.create_token('john')
                    

// composer require get-stream/stream-chat

$client = new GetStream\StreamChat\Client("STREAM_API_KEY", "STREAM_API_SECRET");
$token = $client->createToken("john");
                    

// at the moment we don't have a Java client for server side usage
                    

// go get github.com/GetStream/stream-chat-go

client, _ := stream.NewClient(APIKey, []byte(APISecret))
token := client.CreateToken("john", null)
                    

// at the moment we don't have a Swift client for server side usage
                    

// nuget install stream-chat-net

using StreamChat;

var client = new Client("API KEY", "API SECRET");
var token = client.CreateUserToken("john");
                    

// user tokens must be generated server-side, check other languages for examples
                    

By default, user tokens are valid indefinitely. You can set an expiration to tokens by passing it as the second parameter. The expiration should contain the number of seconds since the epoch.


// creates a token that expires in 1 hour using moment.js
const timestamp = moment().add('1h').format('X');
const token1 = client.createToken('john', timestamp);

// the same can be done with plain javascript
const token2 = client.createToken('john', Math.floor(Date.now() / 1000) + (60 * 60));
                    

# creates a token valid for 1 hour
token = chat_client.create_token(
    'john',
    exp=datetime.datetime.utcnow() + datetime.timedelta(hours=1)
)
                    

# creates a token valid for 1 hour
client.create_token('john', exp=Time.now.to_i + 3600)
                    

// creates a token valid for 1 hour
$expiration = (new DateTime())->getTimestamp() + 3600;
$token = $client->createToken("john", $expiration);
                    

// at the moment we don't have a Java SDK for server side integrations
                    

// creates a token valid for 1 hour
token := client.CreateToken("john", time.Now().UTC().Add(time.Hour))
                    

// at the moment we don't have a Swift client for server side usage
                    

// creates a token valid for 1 hour
var token = client.CreateUserToken("john", DateTime.Now.AddHours(1));
                    

// user tokens must be generated server-side, check other languages for examples
                    

Development Tokens

For development applications, it is possible to disable token authentication and use client-side generated tokens. Disabling auth checks is not suitable for a production application and should only be done for proofs-of-concept and applications in the early development stage. To enable development tokens, you need to change your application configuration.


await client.setUser(
    {
        id: 'john',
        name: 'John Doe',
        image: 'https://getstream.io/random_svg/?name=John',
    },
   client.devToken('john'),
);
                    

User user = new User(USER_ID, extraData);
client.setUser(user, client.devToken(USER_ID), 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));
    }
});
                    

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

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

val user = User("USER_ID", extraData)
client.setUser(user, client.devToken(USER_ID), object : ClientConnectionCallback {
    override fun onSuccess(user: User) {
        Log.i(TAG,String.format("Connection established for user %s", user.name) )
    }

    override fun onError(errMsg: String, errCode: Int) {
        Log.e(TAG,
            String.format("Failed to establish websocket connection: %s", errMsg
            )
        )
    }
})
                    

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,
  client.devToken("john"),
);
                    
The above code used the setUser call. The setUser call is the most convenient option when your app has authenticated users. Alternatively, you can use setGuestUser if you want to allow users to chat with a guest account or the setAnonymousUser if you want to allow anonymous users to watch the chat.

Guest Users

Guest sessions can be created client-side and do not require any server-side authentication.

Guest users have a limited set of permissions. You can read more about how to configure permissions here. You can create a guest user session by using setGuestUser instead of setUser.


await client.setGuestUser({ id: 'tommaso' });
                    

// Not supported yet
                    

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

// Setup the current user and guest token.
Client.shared.set(user: user, token: .guest)
                    

// Not supported yet
                    

await client.setGuestUser(user);
                    
The user object schema is the same as the one described in the Setting the user portion of the docs.

Anonymous Users

If a user is not logged in, you can call the setAnonymousUser method. While you’re anonymous, you can’t do much, but for the livestream channel type, you’re still allowed to read the chat conversation.


await client.setAnonymousUser();
                    

// not supported yet
                    

// not supported yet
                    

// not supported yet
                    

await client.setAnonymousUser();
                    

Logging Out

To disconnect a user (say that you’re for instance logging out and logging in as someone new) you can call the disconnect method and repeat the setUser call as someone else:


client.disconnect();
client.setUser(
    {
        id: 'jack',
        name: 'Jack Doe',
    },
    'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiamxhaGV5In0.OkDbpbujWJ-XIVHaf00Dnqt3v8Yp_nQ6CGzm-Z4QUVc',
);
                    

client.disconnect();
                    

Client.shared.disconnect()
                    

client.disconnect(
                    

await client.disconnect();

final otherUser = User(id: "jack", extraData: {
  "name": "Jack Doe",
});

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