> ## Documentation Index
> Fetch the complete documentation index at: https://cometchat-22654f5b-docs-audit-mechanical-fixes.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# CometChatProvider

> The root provider that initializes the CometChat SDK, manages authentication, and composes all internal contexts for the React UI Kit.

## Overview

Every CometChat component must be rendered inside a provider tree that supplies theme, locale, plugin registry, and real-time events. The UI Kit offers two ways to set this up:

| Approach                            | Best for                                                  | Init & login                                               | Provider setup                                                                                |
| ----------------------------------- | --------------------------------------------------------- | ---------------------------------------------------------- | --------------------------------------------------------------------------------------------- |
| **CometChatProvider** (recommended) | Most apps                                                 | Automatic — just pass credentials                          | Single component wraps everything                                                             |
| **Individual providers**            | Advanced control (custom login flows, multiple instances) | Manual — call `CometChatUIKit.init()` + `login()` yourself | Compose `ThemeProvider`, `LocaleProvider`, `EventsProvider`, `PluginRegistryContext` manually |

***

## Approach 1: CometChatProvider (Recommended)

`CometChatProvider` is a single component that handles SDK initialization, user login, plugin registration, theming, localization, and real-time events — all declaratively via props.

```tsx theme={null}
import { CometChatProvider, CometChatConversations } from "@cometchat/chat-uikit-react";
import "@cometchat/chat-uikit-react/styles";

function App() {
  return (
    <CometChatProvider
      appId="YOUR_APP_ID"
      region="us"
      authKey="YOUR_AUTH_KEY"
      uid="cometchat-uid-1"
    >
      <CometChatConversations />
    </CometChatProvider>
  );
}
```

That's it. No `CometChatUIKit.init()`, no `UIKitSettingsBuilder`, no manual login. The provider handles the full lifecycle:

1. Builds `UIKitSettings` from your props
2. Calls `CometChatUIKit.init(settings)` internally
3. Logs in the user (via `uid` + `authKey`, or `authToken`)
4. Sets up the plugin registry (default plugins included automatically)
5. Provides theme, locale, and event contexts to all child components

### Props

| Prop             | Type                             | Required | Default   | Description                                                                                                              |
| ---------------- | -------------------------------- | -------- | --------- | ------------------------------------------------------------------------------------------------------------------------ |
| `appId`          | `string`                         | Yes\*    | —         | CometChat app ID from the dashboard                                                                                      |
| `region`         | `string`                         | Yes\*    | —         | App region (`"us"`, `"eu"`, `"in"`)                                                                                      |
| `authToken`      | `string`                         | —        | —         | Auth token for production login (server-generated)                                                                       |
| `uid`            | `string`                         | —        | —         | User UID for development login (used with `authKey`)                                                                     |
| `authKey`        | `string`                         | —        | —         | Auth key for development login (used with `uid`)                                                                         |
| `settings`       | `UIKitSettings`                  | —        | —         | Pre-built settings object for full control. When provided, `appId`/`region`/`callingEnabled`/`plugins` props are ignored |
| `callingEnabled` | `boolean`                        | No       | `false`   | Enable voice/video calling (requires `@cometchat/calls-sdk-javascript`)                                                  |
| `plugins`        | `CometChatMessagePlugin[]`       | No       | —         | Additional plugins beyond the defaults                                                                                   |
| `theme`          | `"light" \| "dark"`              | No       | `"light"` | Active theme                                                                                                             |
| `locale`         | `string`                         | No       | `"en-us"` | Language code for i18n                                                                                                   |
| `config`         | `CometChatGlobalConfig`          | No       | `{}`      | Global flags (`hideReceipts`, `hideUserStatus`, etc.)                                                                    |
| `onError`        | `(error: Error) => void`         | No       | —         | Called on init or login failure                                                                                          |
| `onLoginSuccess` | `(user: CometChat.User) => void` | No       | —         | Called when login succeeds                                                                                               |

\*Required unless `settings` is provided.

### Authentication

Provide one of:

* `authToken` — for production (generated server-side via REST API)
* `uid` + `authKey` — for development/testing only

```tsx theme={null}
{/* Production */}
<CometChatProvider appId="..." region="us" authToken={serverGeneratedToken}>

{/* Development */}
<CometChatProvider appId="..." region="us" authKey="..." uid="cometchat-uid-1">
```

### Advanced: Pre-built Settings

For full control over SDK configuration (presence subscription mode, custom hosts, storage mode), pass a `UIKitSettings` object:

```tsx theme={null}
import { CometChatProvider, UIKitSettingsBuilder } from "@cometchat/chat-uikit-react";

const settings = new UIKitSettingsBuilder()
  .setAppId("YOUR_APP_ID")
  .setRegion("us")
  .setAuthKey("YOUR_AUTH_KEY")
  .subscribePresenceForRoles(["admin", "support"])
  .setCallingEnabled(true)
  .setAutoEstablishSocketConnection(true)
  .build();

function App() {
  return (
    <CometChatProvider settings={settings} uid="cometchat-uid-1">
      <MyChatApp />
    </CometChatProvider>
  );
}
```

### With Calling Enabled

```tsx theme={null}
<CometChatProvider
  appId="YOUR_APP_ID"
  region="us"
  authKey="YOUR_AUTH_KEY"
  uid="cometchat-uid-1"
  callingEnabled={true}
>
  <MyChatApp />
</CometChatProvider>
```

### With Custom Theme and Locale

```tsx theme={null}
<CometChatProvider
  appId="YOUR_APP_ID"
  region="eu"
  authKey="YOUR_AUTH_KEY"
  uid="cometchat-uid-1"
  theme="dark"
  locale="fr"
>
  <MyChatApp />
</CometChatProvider>
```

### With Additional Plugins

Default plugins (text, image, file, audio, video) are always included. Pass additional plugins via the `plugins` prop:

```tsx theme={null}
import { CometChatProvider } from "@cometchat/chat-uikit-react";
import { CometChatAIPlugin } from "@cometchat/chat-uikit-react/plugins/ai";

<CometChatProvider
  appId="YOUR_APP_ID"
  region="us"
  authKey="YOUR_AUTH_KEY"
  uid="cometchat-uid-1"
  plugins={[CometChatAIPlugin]}
>
  <MyChatApp />
</CometChatProvider>
```

### Accessing the Logged-In User

Inside your components (children of `CometChatProvider`), access the logged-in user via the `useLoggedInUser()` hook or `CometChatUIKit.getLoggedInUser()`:

```tsx theme={null}
import { useLoggedInUser } from "@cometchat/chat-uikit-react";

function MyComponent() {
  const loggedInUser = useLoggedInUser();

  if (!loggedInUser) return <div>Logging in...</div>;

  return <div>Welcome, {loggedInUser.getName()}</div>;
}
```

***

## Approach 2: Individual Providers (Advanced)

For apps that need custom login flows, multiple CometChat instances, or fine-grained control over the provider tree, you can initialize manually and compose providers yourself.

### Step 1: Initialize and Login

Call `CometChatUIKit.init()` and `CometChatUIKit.login()` before rendering:

```tsx title="src/main.tsx" theme={null}
import ReactDOM from "react-dom/client";
import { CometChatUIKit, UIKitSettingsBuilder } from "@cometchat/chat-uikit-react";
import App from "./App";

const settings = new UIKitSettingsBuilder()
  .setAppId("YOUR_APP_ID")
  .setRegion("us")
  .setAuthKey("YOUR_AUTH_KEY")
  .subscribePresenceForAllUsers()
  .setCallingEnabled(true)
  .build();

CometChatUIKit.init(settings).then(async () => {
  // Login — use loginWithAuthToken() in production
  await CometChatUIKit.login("cometchat-uid-1");
  ReactDOM.createRoot(document.getElementById("root")!).render(<App />);
});
```

### Step 2: Compose Providers

After init and login, wrap your app with the individual providers:

```tsx title="src/App.tsx" theme={null}
import {
  CometChatThemeProvider,
  CometChatEventsProvider,
  LocaleProvider,
  CometChatPluginRegistryContext,
  CometChatPluginRegistry,
  defaultPlugins,
} from "@cometchat/chat-uikit-react";
import "@cometchat/chat-uikit-react/styles";

const pluginRegistry = new CometChatPluginRegistry(defaultPlugins);

function App() {
  return (
    <CometChatThemeProvider theme="light">
      <CometChatEventsProvider>
        <CometChatPluginRegistryContext.Provider value={pluginRegistry}>
          <LocaleProvider locale="en-us">
            <MyChatApp />
          </LocaleProvider>
        </CometChatPluginRegistryContext.Provider>
      </CometChatEventsProvider>
    </CometChatThemeProvider>
  );
}
```

### When to Use This Approach

* **Custom login flows** — your app has its own auth system and you need to control when login happens
* **Multiple chat instances** — you need separate plugin registries or themes for different parts of the app
* **Gradual migration** — you're migrating from v6 and want to keep the imperative init pattern temporarily
* **Server-side rendering** — you need to defer initialization to a specific lifecycle point

<Note>
  Even with individual providers, `CometChatUIKit.init()` must be called before rendering any CometChat components. The individual providers do not handle initialization — they only provide React context.
</Note>

***

## Internal Architecture

`CometChatProvider` composes these internal providers in order:

```
CometChatProvider
  └─ PluginRegistryContext     — plugin registry from CometChatUIKit
     └─ GlobalConfigProvider   — hideReceipts, hideUserStatus, etc.
        └─ ThemeProvider        — data-theme attribute + CSS variables
           └─ LocaleProvider   — i18n translations
              └─ EventsProvider — SDK listeners + UI events (mounted after login)
                 └─ {children}
```

The `EventsProvider` only mounts after login succeeds. Before that, children render without real-time event subscriptions (which is correct since there's no authenticated session to listen on).

***

## Next.js App Router

`CometChatProvider` uses browser APIs internally, so it must be placed inside a Client Component:

```tsx title="app/providers.tsx" theme={null}
"use client";

import { CometChatProvider } from "@cometchat/chat-uikit-react";
import "@cometchat/chat-uikit-react/styles";

export function ChatProviders({ children }: { children: React.ReactNode }) {
  return (
    <CometChatProvider
      appId={process.env.NEXT_PUBLIC_COMETCHAT_APP_ID!}
      region={process.env.NEXT_PUBLIC_COMETCHAT_REGION!}
      authToken={getAuthToken()}
      callingEnabled
    >
      {children}
    </CometChatProvider>
  );
}
```

***

## Migration from v6

In v6, initialization was always imperative:

```tsx title="v6 (before)" theme={null}
import { CometChatUIKit, UIKitSettingsBuilder } from "@cometchat/chat-uikit-react";

const settings = new UIKitSettingsBuilder()
  .setAppId("APP_ID")
  .setRegion("REGION")
  .setAuthKey("AUTH_KEY")
  .build();

await CometChatUIKit.init(settings);
await CometChatUIKit.login("USER_ID");
```

```tsx title="v7 (after)" theme={null}
<CometChatProvider appId="APP_ID" region="REGION" authKey="AUTH_KEY" uid="USER_ID">
  <App />
</CometChatProvider>
```

Key differences:

* No manual `init()` or `login()` calls needed
* No `UIKitSettingsBuilder` required for basic usage
* Default plugins are included automatically
* Theme and locale are props, not separate configuration steps
* Real-time events are managed internally (no RxJS, no manual listener setup)
