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

# Authentication

> Create users and authenticate them securely with the CometChat JavaScript SDK.

## Create User

Before you log in a user, you must add the user to CometChat.

1. **For proof of concept/MVPs**: Create the user using the [CometChat Dashboard](https://app.cometchat.com).
2. **For production apps**: Use the CometChat [Create User API](https://api-explorer.cometchat.com/reference/creates-user) to create the user when your user signs up in your app.

<Note>
  We have setup 5 users for testing having UIDs: `cometchat-uid-1`, `cometchat-uid-2`, `cometchat-uid-3`, `cometchat-uid-4` and `cometchat-uid-5`.
</Note>

Once initialization is successful, you will need to log the user into CometChat using the `login()` method.

We recommend you call the CometChat login method once your user logs into your app. The `login()` method needs to be called only once.

<Warning>
  The CometChat SDK maintains the session of the logged-in user within the SDK. Thus you do not need to call the login method for every session. You can use the CometChat.getLoggedinUser() method to check if there is any existing session in the SDK. This method should return the details of the logged-in user. If this method returns null, it implies there is no session present within the SDK and you need to log the user into CometChat.
</Warning>

## Login using Auth Key

This straightforward authentication method is ideal for proof-of-concept (POC) development or during the early stages of application development. For production environments, however, we strongly recommend using an [AuthToken](#login-using-auth-token) instead of an Auth Key to ensure enhanced security.

<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/javascript/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>
</Tabs>

| Parameters | Description                                      |
| ---------- | ------------------------------------------------ |
| UID        | The UID of the user that you would like to login |
| authKey    | CometChat Auth Key                               |

After the user logs in, their information is returned in the `User` object on `Promise` resolved.

## Login using Auth Token

This advanced authentication procedure does not use the Auth Key directly in your client code thus ensuring safety.

1. [Create a User](https://api-explorer.cometchat.com/reference/creates-user) via the CometChat API when the user signs up in your app.
2. [Create an Auth Token](https://api-explorer.cometchat.com/reference/create-authtoken) via the CometChat API for the new user and save the token in your database.
3. Load the Auth Token in your client and pass it to the `login()` method.

<Tabs>
  <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>

***

## Login Listener

You can listen for login and logout events in real time using `LoginListener`. This is useful for updating UI state or triggering side effects when the auth state changes.

| Callback               | Description                                                                                    |
| ---------------------- | ---------------------------------------------------------------------------------------------- |
| `loginSuccess(event)`  | User logged in successfully. Provides the [`User`](/sdk/reference/entities#user) object.       |
| `loginFailure(event)`  | Login failed. Provides a [`CometChatException`](/sdk/reference/auxiliary#cometchatexception).  |
| `logoutSuccess()`      | User logged out successfully.                                                                  |
| `logoutFailure(event)` | Logout failed. Provides a [`CometChatException`](/sdk/reference/auxiliary#cometchatexception). |

### Add a Listener

<Tabs>
  <Tab title="TypeScript">
    ```typescript theme={null}
    const listenerID: string = "UNIQUE_LISTENER_ID";
    CometChat.addLoginListener(
        listenerID,
        new CometChat.LoginListener({
            loginSuccess: (user: CometChat.User) => {
                console.log("LoginListener :: loginSuccess", user);
            },
            loginFailure: (error: CometChat.CometChatException) => {
                console.log("LoginListener :: loginFailure", error);
            },
            logoutSuccess: () => {
                console.log("LoginListener :: logoutSuccess");
            },
            logoutFailure: (error: CometChat.CometChatException) => {
                console.log("LoginListener :: logoutFailure", error);
            }
        })
    );
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={null}
    let listenerID = "UNIQUE_LISTENER_ID";
    CometChat.addLoginListener(
        listenerID,
        new CometChat.LoginListener({
            loginSuccess: (e) => {
                console.log("LoginListener :: loginSuccess", e);
            },
            loginFailure: (e) => {
                console.log("LoginListener :: loginFailure", e);
            },
            logoutSuccess: () => {
                console.log("LoginListener :: logoutSuccess");
            },
            logoutFailure: (e) => {
                console.log("LoginListener :: logoutFailure", e);
            }
        })
    );
    ```
  </Tab>
</Tabs>

### Remove a Listener

```javascript theme={null}
CometChat.removeLoginListener("UNIQUE_LISTENER_ID");
```

<Warning>
  Always remove login listeners when they're no longer needed (e.g., on
  component unmount or page navigation). Failing to remove listeners can cause
  memory leaks and duplicate event handling.
</Warning>

***

## Next Steps

<CardGroup cols={2}>
  <Card title="Send Messages" icon="paper-plane" href="/sdk/javascript/send-message">
    Send your first text, media, or custom message
  </Card>

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

  <Card title="Connection Status" icon="signal" href="/sdk/javascript/connection-status">
    Monitor the SDK connection state in real time
  </Card>

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