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

# Authentication

> Create users, log in with Auth Key or Auth Token, check login status, and log out using the CometChat React Native SDK.

<Accordion title="AI Integration Quick Reference">
  ```javascript theme={null}
  // Check existing session
  const user = await CometChat.getLoggedinUser();

  // Login with Auth Key (development only)
  CometChat.login("cometchat-uid-1", "AUTH_KEY").then(user => console.log("Logged in:", user));

  // Login with Auth Token (production)
  CometChat.login("AUTH_TOKEN").then(user => console.log("Logged in:", user));

  // Logout
  CometChat.logout().then(() => console.log("Logged out"));
  ```

  **Create users via:** [Dashboard](https://app.cometchat.com) (testing) | [REST API](https://api-explorer.cometchat.com/reference/creates-user) (production)
  **Test UIDs:** `cometchat-uid-1` through `cometchat-uid-5`
</Accordion>

After [initializing](/sdk/react-native/setup-sdk) the SDK, the next step is to authenticate your user. CometChat provides two login methods — Auth Key for quick development, and Auth Token for production — both accessed through the `login()` method.

### How It Works

```mermaid theme={null}
sequenceDiagram
    participant User
    participant YourApp as Your App
    participant YourServer as Your Server
    participant CometChat as CometChat

    User->>YourApp: Signs up / Logs in
    YourApp->>YourServer: Authenticate user
    YourServer->>CometChat: Create user (REST API, first time only)
    CometChat-->>YourServer: User created
    YourServer->>CometChat: Create Auth Token (REST API)
    CometChat-->>YourServer: Auth Token
    YourServer-->>YourApp: Return Auth Token
    YourApp->>CometChat: CometChat.login(authToken)
    CometChat-->>YourApp: User object (logged in)
```

## Before You Log In

### Create a User

A user must exist in CometChat before they can log in.

* **During development:** Create users from the [CometChat Dashboard](https://app.cometchat.com). Five test users are already available with UIDs `cometchat-uid-1` through `cometchat-uid-5`.
* **In production:** Call the [Create User REST API](https://api-explorer.cometchat.com/reference/creates-user) when a user signs up in your app.

You can also create users from the client side using `createUser()` (development only):

<Tabs>
  <Tab title="TypeScript">
    ```typescript theme={null}
    let authKey: string = "AUTH_KEY";
    let uid: string = "user1";
    let name: string = "Kevin";

    let user: CometChat.User = new CometChat.User(uid);
    user.setName(name);

    CometChat.createUser(user, authKey).then(
      (user: CometChat.User) => {
        console.log("User created:", user);
      },
      (error: CometChat.CometChatException) => {
        console.log("Error:", error);
      }
    );
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={null}
    let authKey = "AUTH_KEY";
    let uid = "user1";
    let name = "Kevin";

    let user = new CometChat.User(uid);
    user.setName(name);

    CometChat.createUser(user, authKey).then(
      (user) => {
        console.log("User created:", user);
      },
      (error) => {
        console.log("Error:", error);
      }
    );
    ```
  </Tab>
</Tabs>

<Warning>
  `createUser()` with Auth Key is for development only. In production, create users server-side via the [REST API](https://api-explorer.cometchat.com/reference/creates-user). See [User Management](/sdk/react-native/user-management) for full details.
</Warning>

### Check for an Existing Session

The SDK persists the logged-in user's session locally. Before calling `login()`, always check whether a session already exists — this avoids unnecessary login calls and keeps your app responsive.

```javascript theme={null}
const user = await CometChat.getLoggedinUser();
if (user) {
  // User is already logged in — proceed to your app
}
```

If `getLoggedinUser()` returns `null`, no active session exists and you need to call `login()`.

## Login with Auth Key

Auth Key login is the simplest way to get started. Pass a UID and your Auth Key directly from the client.

<Warning>
  Auth Keys are meant for development and testing only. For production, use [Auth Token login](#login-with-auth-token) instead. Never ship Auth Keys in client-side code.
</Warning>

<Tabs>
  <Tab title="TypeScript">
    ```typescript theme={null}
    const UID: string = "cometchat-uid-1";
    const authKey: string = "AUTH_KEY";

    CometChat.getLoggedinUser().then(
      (user: CometChat.User) => {
        if (!user) {
          CometChat.login(UID, authKey).then(
            (user: CometChat.User) => {
              console.log("Login Successful:", { user });
            },
            (error: CometChat.CometChatException) => {
              console.log("Login failed with exception:", { error });
            }
          );
        }
      },
      (error: CometChat.CometChatException) => {
        console.log("Some Error Occurred", { error });
      }
    );
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={null}
    const UID = "cometchat-uid-1";
    const authKey = "AUTH_KEY";

    CometChat.getLoggedinUser().then(
      (user) => {
        if (!user) {
          CometChat.login(UID, authKey).then(
            (user) => {
              console.log("Login Successful:", { user });
            },
            (error) => {
              console.log("Login failed with exception:", { error });
            }
          );
        }
      },
      (error) => {
        console.log("Some Error Occurred", { error });
      }
    );
    ```

    Alternatively, you can use the `async/await` syntax:

    ```javascript theme={null}
    const UID = "cometchat-uid-1";
    const authKey = "AUTH_KEY";

    try {
      const loggedInUser = await CometChat.getLoggedinUser();
      if (!loggedInUser) {
        const user = await CometChat.login(UID, authKey);
        console.log("Login Successful:", { user });
      }
    } catch (error) {
      console.log("Login failed with exception:", { error });
    }
    ```
  </Tab>
</Tabs>

| Parameter | Description                   |
| --------- | ----------------------------- |
| UID       | The UID of the user to log in |
| authKey   | Your CometChat Auth Key       |

On success, the `Promise` resolves with a [`User`](/sdk/reference/entities#user) object containing the logged-in user's details.

## Login with Auth Token

Auth Token login keeps your Auth Key off the client entirely. Your server generates a token via the REST API and passes it to the client.

1. [Create the user](https://api-explorer.cometchat.com/reference/creates-user) via the REST API when they sign up (first time only).
2. [Generate an Auth Token](https://api-explorer.cometchat.com/reference/create-authtoken) on your server and return it to the client.
3. Pass the token to `login()`.

<Tabs>
  <Tab title="TypeScript">
    ```typescript theme={null}
    const authToken: string = "AUTH_TOKEN";

    CometChat.getLoggedinUser().then(
      (user: CometChat.User) => {
        if (!user) {
          CometChat.login(authToken).then(
            (user: CometChat.User) => {
              console.log("Login Successful:", { user });
            },
            (error: CometChat.CometChatException) => {
              console.log("Login failed with exception:", { error });
            }
          );
        }
      },
      (error: CometChat.CometChatException) => {
        console.log("Some Error Occurred", { error });
      }
    );
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={null}
    const authToken = "AUTH_TOKEN";

    CometChat.getLoggedinUser().then(
      (user) => {
        if (!user) {
          CometChat.login(authToken).then(
            (user) => {
              console.log("Login Successful:", { user });
            },
            (error) => {
              console.log("Login failed with exception:", { error });
            }
          );
        }
      },
      (error) => {
        console.log("Some Error Occurred", { error });
      }
    );
    ```

    Alternatively, you can use the `async/await` syntax:

    ```javascript theme={null}
    const authToken = "AUTH_TOKEN";

    try {
      const loggedInUser = await CometChat.getLoggedinUser();
      if (!loggedInUser) {
        const user = await CometChat.login(authToken);
        console.log("Login Successful:", { user });
      }
    } catch (error) {
      console.log("Login failed with exception:", { error });
    }
    ```
  </Tab>
</Tabs>

| Parameter | Description                                      |
| --------- | ------------------------------------------------ |
| authToken | Auth Token generated on your server for the user |

On success, the `Promise` resolves with a [`User`](/sdk/reference/entities#user) object containing the logged-in user's details.

## Logout

Call `logout()` when your user logs out of your app. This clears the local session.

<Tabs>
  <Tab title="TypeScript">
    ```typescript theme={null}
    CometChat.logout().then(
      (loggedOut: Object) => {
        console.log("Logout completed successfully");
      },
      (error: CometChat.CometChatException) => {
        console.log("Logout failed with exception:", { error });
      }
    );
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={null}
    CometChat.logout().then(
      () => {
        console.log("Logout completed successfully");
      },
      (error) => {
        console.log("Logout failed with exception:", { error });
      }
    );
    ```

    Alternatively, you can use the `async/await` syntax:

    ```javascript theme={null}
    try {
      await CometChat.logout();
      console.log("Logout completed successfully");
    } catch (error) {
      console.log("Logout failed with exception:", { error });
    }
    ```
  </Tab>
</Tabs>

***

## Next Steps

<CardGroup cols={2}>
  <Card title="Login Listener" icon="bell" href="/sdk/react-native/login-listener">
    Listen for real-time login and logout events
  </Card>

  <Card title="Send Messages" icon="paper-plane" href="/sdk/react-native/send-message">
    Send your first text, media, or custom message
  </Card>

  <Card title="User Management" icon="users-gear" href="/sdk/react-native/user-management">
    Create, update, and delete users programmatically
  </Card>

  <Card title="All Real-Time Listeners" icon="tower-broadcast" href="/sdk/react-native/real-time-listeners">
    Complete reference for all SDK event listeners
  </Card>
</CardGroup>
