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

# Working with Users

> Provision Users via the API, generate short-lived JWTs for embedded components, and attribute messages to users.

## What a User is

A User is a person in your application who sends and receives messages through Surge's embeddable UI components. Users are provisioned via the Surge API and belong to a specific account. They are separate from people who log in to `hq.surge.app`.

If you're building a SaaS platform where your customers interact with Surge-powered messaging, Users are typically your customers' employees, not your customers' own customers.

Users are used in two ways:

1. **Embedded UI**: the inbox and conversation components authenticate as a specific User, showing that user's conversations and sending messages on their behalf
2. **Attribution**: messages and calls can be tied to a User, so you can trace activity back to the individual

Users do not have Surge passwords or sessions. Authentication for embedded components goes through a short-lived JWT that your server generates.

## Provision a User

Create a User via the API before you mount any components for them:

<CodeGroup>
  ```python Python theme={null}
  from surge import Surge

  surge = Surge()

  user = surge.users.create(
      account_id="{account_id}",
      first_name="Jordan",
      last_name="Patel",
      metadata={"internal_user_id": "u_9887"},
  )
  ```

  ```typescript TypeScript theme={null}
  import Surge from "@surgeapi/node";

  const surge = new Surge();

  const user = await surge.users.create("{account_id}", {
    first_name: "Jordan",
    last_name: "Patel",
    metadata: { internal_user_id: "u_9887" },
  });
  ```

  ```ruby Ruby theme={null}
  require "surge_api"

  surge = SurgeAPI::Client.new

  user = surge.users.create(
    "{account_id}",
    first_name: "Jordan",
    last_name: "Patel",
    metadata: { "internal_user_id" => "u_9887" }
  )
  ```

  ```elixir Elixir theme={null}
  client = Surge.Client.new(System.get_env("SURGE_API_KEY"))

  {:ok, user} =
    Surge.Users.create(client, "{account_id}", %{
      first_name: "Jordan",
      last_name: "Patel",
      metadata: %{internal_user_id: "u_9887"}
    })
  ```

  ```bash cURL theme={null}
  curl -X POST https://api.surge.app/accounts/{account_id}/users \
    -H "Authorization: Bearer YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "first_name": "Jordan",
      "last_name": "Patel",
      "metadata": {
        "internal_user_id": "u_9887"
      }
    }'
  ```
</CodeGroup>

```json theme={null}
{
  "id": "usr_01jrzhe8d9enptypyx360pcmxu",
  "first_name": "Jordan",
  "last_name": "Patel",
  "metadata": {
    "internal_user_id": "u_9887"
  }
}
```

Store the returned `id` alongside the user's record in your database. You'll use it to generate component tokens and attribute messages.

## Generate a component token

Your server generates a short-lived JWT for each user session. The JWT scopes the embedded component to that specific user's data.

The simplest path is the token endpoint:

<CodeGroup>
  ```python Python theme={null}
  response = surge.users.create_token(user_id="{user_id}")
  token = response.token
  ```

  ```typescript TypeScript theme={null}
  const response = await surge.users.createToken("{user_id}");
  const token = response.token;
  ```

  ```ruby Ruby theme={null}
  response = surge.users.create_token("{user_id}")
  token = response.token
  ```

  ```elixir Elixir theme={null}
  {:ok, token} = Surge.Users.create_token(client, "{user_id}", %{})
  ```

  ```bash cURL theme={null}
  curl -X POST https://api.surge.app/users/{user_id}/tokens \
    -H "Authorization: Bearer YOUR_API_KEY"
  ```
</CodeGroup>

```json theme={null}
{
  "token": "eyJhbGciOiJFZERTQSIsImtpZCI6InNnbl8wMWouLi4ifQ..."
}
```

Return this token to your frontend and use it to mount the component. Generate a new token on each page load because tokens are short-lived.

## Typical vertical SaaS flow

1. When one of your customer's employees is added to your SaaS product, create a Surge User via `POST /accounts/{account_id}/users`. Store the `id`.
2. When that employee loads a page in your app that includes embedded messaging, your server calls `POST /users/{user_id}/tokens` to get a fresh JWT.
3. Your frontend receives the JWT and mounts the Surge Inbox or Conversation component with it.
4. The component shows only that user's conversations and sends messages attributed to them.

```python theme={null}
# On page load, server-side
@app.get("/api/surge-token")
async def get_surge_token(current_user: User):
    response = surge.users.create_token(user_id=current_user.surge_user_id)
    return {"token": response.token}
```

```html theme={null}
<iframe
  id="surge-inbox"
  title="Surge conversations"
  src="https://embed.surge.app/conversations"
></iframe>

<script type="module">
  const { token } = await fetch("/api/surge-token").then((response) =>
    response.json()
  );

  const userId = "{SURGE_USER_ID}";
  const embedUrl = new URL("https://embed.surge.app/conversations");
  embedUrl.searchParams.set("user_id", userId);
  embedUrl.searchParams.set("token", token);

  document.getElementById("surge-inbox").src =
    embedUrl.toString();
</script>
```

## List and manage Users

<CodeGroup>
  ```python Python theme={null}
  # List users in an account
  for user in surge.users.list(account_id="{account_id}"):
      print(user.id)

  # Update a user
  surge.users.update("{user_id}", first_name="Jordan M.")

  # Delete a user
  surge.users.delete("{user_id}")
  ```

  ```typescript TypeScript theme={null}
  // List users in an account
  for await (const user of await surge.users.list("{account_id}")) {
    console.log(user.id);
  }

  // Update a user
  await surge.users.update("{user_id}", { first_name: "Jordan M." });

  // Delete a user
  await surge.users.delete("{user_id}");
  ```

  ```ruby Ruby theme={null}
  # List users in an account
  page = surge.users.list("{account_id}")
  page.data.each { |u| puts u.id }

  # Update a user
  surge.users.update("{user_id}", first_name: "Jordan M.")

  # Delete a user
  surge.users.delete("{user_id}")
  ```

  ```elixir Elixir theme={null}
  # Surge.Users.list isn't typed in the Elixir SDK yet — use the raw client.
  {:ok, page} =
    Surge.Client.request(client, :get, "/accounts/{account_id}/users")

  Enum.each(page["data"], fn u -> IO.puts(u["id"]) end)

  # Update a user
  {:ok, _} = Surge.Users.update(client, "{user_id}", %{first_name: "Jordan M."})

  # Delete a user
  {:ok, _} = Surge.Users.delete(client, "{user_id}")
  ```

  ```bash cURL theme={null}
  # List users in an account
  curl "https://api.surge.app/accounts/{account_id}/users" \
    -H "Authorization: Bearer YOUR_API_KEY"

  # Update a user
  curl -X PATCH https://api.surge.app/users/{user_id} \
    -H "Authorization: Bearer YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{ "first_name": "Jordan M." }'

  # Delete a user
  curl -X DELETE https://api.surge.app/users/{user_id} \
    -H "Authorization: Bearer YOUR_API_KEY"
  ```
</CodeGroup>

Deleting a User removes their Surge record but does not delete message history.

## Next steps

<CardGroup cols={3}>
  <Card title="Inbox component" icon="inbox" href="./inbox">
    Mount a conversation list for the current User.
  </Card>

  <Card title="Conversation component" icon="comment" href="./conversation">
    Mount a single threaded conversation view.
  </Card>

  <Card title="Unread Count component" icon="bell" href="./unread-count">
    Show a live unread badge in your navigation.
  </Card>
</CardGroup>
