# Initialization & Users

The code below creates a chat client instance for interacting with Stream APIs. A singleton client instance means the Chat client is created once and reused throughout your app, ensuring consistent state, avoiding duplicate connections, and simplifying resource management.

```dart label="Dart"
// client-side you initialize the Chat client with your API key
final client = StreamChatClient(
 '{{ api_key }}',
 logLevel: Level.INFO,
 connectTimeout: Duration(milliseconds: 6000),
 receiveTimeout: Duration(milliseconds: 6000),
);
```

## Connecting Users

Once the client is initialized, your app authenticates the user and establishes a Websocket connection by calling `connectUser`. This function uses your token provider function to request a [token generated on your server](https://getstream.io/docs/platform/authentication/).

The `connectUser` function acts as an upsert for the user object and is a primary method for creating users client-side.

Before attempting subsequent API requests to Stream, it is important that the `connectUser` function fully resolves.

```dart label="Dart"
final user = User(
  id: 'john',
  name: 'John Doe',
  image: 'https://i.imgur.com/fR9Jz14.png',
);

// You can setup a user token in two ways:

// 1. Setup the current user with a JWT token
await client.connectUser(user, '{{ chat_user_token }}');

// 2. Setup the current user with a TokenProvider
// The provider is called on the initial connection and again when a fresh
// token is needed (token expiry, auth error, or a reconnection that cannot
// reuse the cached token), so keep this implementation resilient to a
// missing or slow network.
Future<String> tokenProvider(String userId) async {
  return await yourTokenService.getToken(userId);
}
await client.connectUserWithProvider(user, tokenProvider);
```

### Connect User Parameters

| name      | type            | description                                                                                                                                                                                                                          | default | optional |
| --------- | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | -------- |
| user      | object          | The user object. Must have an id field. **User Ids can only contain characters a-z, 0-9, and special characters @ \_ and -** 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/function | The Token Provider function or authentication token. See [Tokens & Authentication](https://getstream.io/chat/docs/flutter-dart/tokens-and-authentication/) for details                                                                                     | default |          |

>
> **Note:** On Android, the SDK manages the WebSocket connection across the app lifecycle and calls your `TokenProvider` again when a fresh token is needed (token expiry, an authentication error, or a reconnection that cannot reuse the cached token). For the full lifecycle behavior, manual disconnect and reconnect, and how to handle token fetch failures in the background, see [Handling User Connection](https://getstream.io/chat/docs/sdk/android/client/guides/handling-user-connection/).
>

## Disconnecting Users

The client-side SDKs handle WebSocket disconnection logic, but if a manual disconnect is required in your application, there are the following options:

```dart label="Dart"
await client.disconnectUser();
```

## XHR Fallback

Most browsers support WebSocket connections as an efficient mode of real-time data transfer. However, sometimes the connection cannot be established due to network or a corporate firewall. In such cases, the client will establish or switch to XHR fallback mechanisms and gently poll our service to keep the client up-to-date.

The fallback mechanism can be enabled with the `enableWSFallback` setting of the client's WebSocket configuration:

```js label="JavaScript"
const chatClient = StreamChat.getInstance("apiKey");
chatClient.config.set({ client: { wsConnection: { enableWSFallback: true } } });
```

## Privacy Settings

Additionally, when connecting the user, you can include the `privacy_settings` as part of the user object.

```dart label="Dart"
final user = OwnUser(
  id: 'john',
  name: 'John Doe',
  image: 'https://i.imgur.com/fR9Jz14.png',
  privacySettings: PrivacySettings(
    typingIndicators: TypingIndicators(enabled: false),
    readReceipts: ReadReceipts(enabled: false),
  ),
);

await client.connectUser(user, '{{ chat_user_token }}');
```

| name              | type   | description                                                                                                                                                                                                         | default       | optional |
| ----------------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- | -------- |
| typing_indicators | object | if **enabled** is set to **false** , then **typing.start** and **typing.stop** events will be ignored for this user and these events will not be sent to others                                                     | enabled: true | ✓        |
| read_receipts     | object | If **enabled** is set to **false** , then the **read_state** of this user will not be exposed to others. Additionally, **read_state** related events will not be delivered to others when this user reads messages. | enabled: true | ✓        |

---

For the most recent version of this documentation, visit [https://getstream.io/chat/docs/flutter-dart/init-and-users/](https://getstream.io/chat/docs/flutter-dart/init-and-users/).