> ## Documentation Index
> Fetch the complete documentation index at: https://www.cometchat.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# User Sync

> How to sync users with CometChat for voice and video calling.

Users must exist in CometChat before they can make or receive calls. This page explains how to create and authenticate users for the Calls SDK.

## Why User Sync?

CometChat needs to know about your users to:

* **Route calls** — Connect callers to the right recipients
* **Identify participants** — Display names and avatars in calls
* **Track history** — Associate call logs with specific users
* **Manage permissions** — Control who can call whom

## Creating Users

Choose the method that best fits your workflow:

<CardGroup cols={3}>
  <Card title="Dashboard" icon="browser" href="https://app.cometchat.com/">
    Add users manually via the CometChat Dashboard. Ideal for quick testing or small teams.
  </Card>

  <Card title="SDK" icon="code" href="/sdk/javascript/user-management">
    Create users programmatically via SDK methods. Perfect for auto-provisioning during sign-up.
  </Card>

  <Card title="REST API" icon="server" href="/rest-api/users/create">
    Create users using the REST API. Best for batch imports or backend workflows.
  </Card>
</CardGroup>

## User Requirements

### Required Fields

| Field | Type   | Description                                                                               |
| :---- | :----- | :---------------------------------------------------------------------------------------- |
| `uid` | String | Unique user identifier. Alphanumeric, max 100 characters. Must be unique across your app. |

### Optional Fields

| Field      | Type   | Description                                       |
| :--------- | :----- | :------------------------------------------------ |
| `name`     | String | Display name shown in calls and participant lists |
| `avatar`   | String | URL to profile image                              |
| `metadata` | Object | Custom JSON data for your application             |
| `role`     | String | User role (default, admin, etc.)                  |
| `tags`     | Array  | Tags for categorization and filtering             |

### Example User Object

```json theme={null}
{
  "uid": "user_123",
  "name": "John Doe",
  "avatar": "https://example.com/avatars/john.png",
  "metadata": {
    "department": "Engineering",
    "location": "San Francisco"
  }
}
```

## Authentication Flow

<Steps>
  <Step title="Create User (One-time)">
    Create the user in CometChat when they sign up for your app. This only needs to happen once per user.

    **Server-side (recommended):**

    ```bash theme={null}
    curl -X POST "https://api-{region}.cometchat.io/v3/users" \
      -H "apiKey: YOUR_API_KEY" \
      -H "Content-Type: application/json" \
      -d '{"uid": "user_123", "name": "John Doe"}'
    ```
  </Step>

  <Step title="Generate Auth Token">
    Generate an authentication token for the user on your server. This token is used to log in the user on the client.

    **Server-side:**

    ```bash theme={null}
    curl -X POST "https://api-{region}.cometchat.io/v3/users/{uid}/auth_tokens" \
      -H "apiKey: YOUR_API_KEY" \
      -H "Content-Type: application/json"
    ```

    **Response:**

    ```json theme={null}
    {
      "data": {
        "uid": "user_123",
        "authToken": "user_123_abc123xyz..."
      }
    }
    ```
  </Step>

  <Step title="Login User (Client-side)">
    Use the auth token to log in the user via the SDK. This establishes a session for making calls.

    **JavaScript:**

    ```javascript theme={null}
    CometChatCalls.login(authToken).then(
      user => console.log("Login successful:", user),
      error => console.log("Login failed:", error)
    );
    ```
  </Step>

  <Step title="Ready for Calls">
    Once logged in, the user can initiate and receive calls. The SDK handles all session management automatically.
  </Step>
</Steps>

## Authentication Methods

### Auth Token (Recommended for Production)

Generate tokens server-side using the REST API. This is the secure method for production apps.

**Pros:**

* Secure — API key never exposed to clients
* Controlled — You decide when tokens are issued
* Auditable — Token generation can be logged

**Flow:**

1. User logs into your app
2. Your server generates a CometChat auth token
3. Token is sent to the client
4. Client uses token to log into CometChat

### Auth Key (Development Only)

Use the Auth Key directly in client code for quick testing. **Never use in production.**

**JavaScript:**

```javascript theme={null}
CometChatCalls.login(uid, authKey).then(
  user => console.log("Login successful:", user),
  error => console.log("Login failed:", error)
);
```

<Warning>
  **Security Warning**: Never expose your Auth Key in production client code. Auth Keys have full access to create users and perform admin operations. Always use auth tokens generated server-side for production apps.
</Warning>

## Sync Strategies

### Just-in-Time Provisioning

Create CometChat users when they first need calling functionality:

```javascript theme={null}
// When user initiates their first call
async function ensureUserExists(user) {
  try {
    // Try to get auth token (user exists)
    return await getAuthToken(user.id);
  } catch (error) {
    // User doesn't exist, create them first
    await createCometChatUser(user);
    return await getAuthToken(user.id);
  }
}
```

**Best for:** Apps where not all users need calling

### Batch Import

Import existing users via REST API when integrating CometChat:

```bash theme={null}
# Create multiple users
curl -X POST "https://api-{region}.cometchat.io/v3/users" \
  -H "apiKey: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '[
    {"uid": "user_1", "name": "Alice"},
    {"uid": "user_2", "name": "Bob"},
    {"uid": "user_3", "name": "Charlie"}
  ]'
```

**Best for:** Migrating existing user bases

### Webhook Sync

Use webhooks to keep CometChat users in sync with your database:

1. User signs up → Create CometChat user
2. User updates profile → Update CometChat user
3. User deletes account → Delete CometChat user

**Best for:** Apps with frequent user changes

## User Lifecycle

### Creating Users

Users can be created via:

* REST API (server-side)
* SDK `createUser` method
* Dashboard (manual)

### Updating Users

Update user details when they change in your app:

```bash theme={null}
curl -X PUT "https://api-{region}.cometchat.io/v3/users/{uid}" \
  -H "apiKey: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"name": "John Smith", "avatar": "https://new-avatar.png"}'
```

### Deleting Users

Remove users when they leave your platform:

```bash theme={null}
curl -X DELETE "https://api-{region}.cometchat.io/v3/users/{uid}" \
  -H "apiKey: YOUR_API_KEY"
```

<Info>
  **Soft Delete**: By default, deleted users are soft-deleted and can be restored. Use `permanent=true` query parameter for permanent deletion.
</Info>

## Best Practices

### Do

* Generate auth tokens server-side
* Use consistent UIDs across your app
* Keep user data in sync
* Handle token expiration gracefully

### Don't

* Expose API keys in client code
* Use Auth Key in production
* Create duplicate users
* Store auth tokens long-term

## Next Steps

<CardGroup cols={2}>
  <Card title="Compatibility" icon="check-double" href="/calls/platform/compatibility">
    Check platform and browser support
  </Card>

  <Card title="REST API Reference" icon="book" href="/rest-api/users/create">
    Full API documentation for user management
  </Card>
</CardGroup>
