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

# Users

> Learn how to tell Trophy about the people using your web or mobile app.

## What are users?

Users are the individual people that use your product. You tell Trophy about your users through APIs. Trophy then uses what it knows about each user to power in-app features and personalize [agentic messaging](https://docs.trophy.so/agentic-messaging/overview.md).

Users must be individuals, they cannot be companies or organisations. To create organizational structures or user groupings, consider using a [custom user attribute](#custom-user-attributes).

## Key attributes

Key attributes are properties of users controlled and managed by Trophy and are for things like `id` or `email`, some are required while others are optional.

### Required attributes

Trophy only requires one key attribute, `id`. Every user you tell Trophy about must have an `id`, this is what identifies them as a unique person.

**id** `string` *required*

This is the ID of the user in **your** database.

> [!TIP]
>
> To make things simple, Trophy lets you use your own `id` that you already have
> in your database instead of needing to manage another one just for Trophy.

### Optional attributes

Additionally, you can tell Trophy about any of the following optional key attributes and it will make them available to you across Trophy:

**name** `string`

The user's full name. This is accessible in email templates and other areas
where you may want to address the user by name.

**email** `string`

The user's email address. This address is used to send
[agentic messages](https://docs.trophy.so/agentic-messaging/channels.md) and any
[Emails (Legacy)](https://docs.trophy.so/features/emails.md) to the user.

**tz** `string`

The user's time zone. Must be specified as an [IANA timezone
identifier](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones).
Used for streaks, leaderboard rankings and sending messages to users in
accordance with their local clock.

In JavaScript, you can fetch the users time zone using this snippet:

```js Fetching timezone theme={null}
// e.g. 'Europe/London'
const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
```

**subscribeToEmails** `boolean` (default: true)

If you've configured any Trophy [Emails](https://docs.trophy.so/features/emails.md), then they'll only
be sent to a user when this field is true. Note: If you don't provide an
`email`, attempting to set this field to true will result in an error.

**signUpDate** `string`

The date the user signed up on your platform, as `YYYY-MM-DD`. ISO 8601
date-times are accepted and stored as their UTC calendar day. Must not be
after today in the user's timezone. This field is separate from
`created`, which is the date Trophy first learned about the user.

**deviceTokens** `array\<string\>`

The list of device tokens to associate with the user. Push notifications, both
agentic and [legacy](https://docs.trophy.so/features/push-notifications.md), are only sent to users
with device tokens. See [device tokens](https://docs.trophy.so/agentic-messaging/channels.md#device-tokens).

### Read-only attributes

Trophy also sets the following key attributes on every user. They're returned when you [retrieve a user](#retrieving-user-information) but can't be set when identifying users.

**control** `boolean`

Whether the user is in the control group. Users in the control group receive
no messages from Trophy, and you can use this flag to conditionally enroll
users in in-app features. Learn more about
[experimentation](https://docs.trophy.so/platform/experimentation.md).

**agenticMessagingEnabled** `boolean`

Whether the user receives [agentic messages](https://docs.trophy.so/agentic-messaging/overview.md).
When `true`, the user receives agentic messages instead of
[Emails (Legacy)](https://docs.trophy.so/features/emails.md) and
[Push notifications (Legacy)](https://docs.trophy.so/features/push-notifications.md), never both.
Which users receive agentic messages depends on your
[rollout](https://docs.trophy.so/agentic-messaging/rollout.md). Always `false` for users in the
control group.

## Custom user attributes

![](https://mintcdn.com/trophy/vvlxkggAvglghNGz/assets/features/users/custom_user_attributes.png?fit=max\&auto=format\&n=vvlxkggAvglghNGz\&q=85\&s=d3adf3d6ef5cb4aa59d33ba358283ac0)

Custom user attributes are managed by you and can be anything you like based on your use case.

For example a language learning app might use a custom user attribute for the language a user is learning, or a study platform might use one for the users favourite subject.

Custom user attributes let you tell Trophy about this contextual information and use it to personalize in-app features and messaging.

### Creating attributes

To create a new custom user attribute, head to the [Attributes page](https://app.trophy.so/attributes) under *Data sources* in the Trophy dashboard and click the *Add User Attribute* button.

Give the attribute a name and a unique key. The key is what you'll use to reference the attribute in API calls.

<video autoPlay muted loop playsInline src="https://mintcdn.com/trophy/vvlxkggAvglghNGz/assets/features/users/create_custom_user_attribute.mp4?fit=max&auto=format&n=vvlxkggAvglghNGz&q=85&s=bc66b184d0a8ed7222907d23d394f6ad" />

### Setting attributes

Attributes can be assigned values for specific users using their unique key either inline, as users increment metrics through the [metric increment API](https://docs.trophy.so/api-reference/endpoints/events/submit-a-metric-event.md), or explicitly through the [user identification](https://docs.trophy.so/api-reference/endpoints/users/identify-a-user.md), [create user](https://docs.trophy.so/api-reference/endpoints/users/create-a-user.md), or [update user](https://docs.trophy.so/api-reference/endpoints/users/update-a-user.md) APIs.

> [!WARNING]
>
> Trophy will only set values of attributes that have first been created
> in the dashboard. We do this to help you keep a clean set of attributes and
> prevent accidental overwrites.
>
> If you receive an error similar to the following then you might have miss-spelled the attribute key in the request, or you need to create the attribute first in the Trophy dashboard:
>
> ```json theme={null}
> {
>   "error": "Invalid attribute keys: pln. Please ensure all attribute keys match those set up at https://app.trophy.so/users/attributes."
> }
> ```

Across all APIs, the schema for setting attribute values is consistent. Here's an example of a request payload that sets the value of two custom user attributes `subject` and `plan`:

```json {4-7} theme={null}
{
  "name": "Joe Bloggs",
  "email": "joe.bloggs@example.com",
  "attributes": {
    "subject": "physics",
    "plan": "free"
  }
}
```

### Using attributes

Use custom user attributes across Trophy to personalize in-app features and messaging, aggregate and filter data returned from APIs, and to segment and compare user cohorts in analytics.

#### Feature personalization

Custom user attributes can be used to personalize milestones, customize the way points are earned by different users and more. Follow the links to the relevant pages below to learn more.

> [card] [Personalizing Milestones](https://docs.trophy.so/features/milestones.md#creating-achievements)
>
> Configure milestones that can only be completed by specific users.

> [card] [Personalizing Points](https://docs.trophy.so/features/points.md#points-triggers)
>
> Personalize how different users earn points.

> [card] [Email Segmentation](https://docs.trophy.so/features/emails.md#limiting-emails-to-specific-types-of-users)
>
> Control which users receive legacy emails.

> [card] [Email Personalization](https://docs.trophy.so/features/emails.md#email-variables)
>
> Personalize email copy and subject lines with custom user attributes.

> [card] [Leaderboard Eligibility](https://docs.trophy.so/features/leaderboards.md#eligibility)
>
> Limit leaderboards to specific groups of users.

#### Data aggregation and filtering

You can use custom user attributes to aggregate and filter data returned from some APIs to support a wide range of use cases. In all cases, attributes are included in the `userAttributes` query parameter using a consistent schema:

`?userAttributes=city:london,subscription-plan:pro`

Here's a list of all APIs that support the `userAttributes` query parameter:

* [Points Summary](https://docs.trophy.so/api-reference/endpoints/points/get-points-summary.md)

#### Segmented analytics

Custom user attributes can be used to segment and compare retention and engagement charts between user groups.

This is useful to understand which cohorts are making full use of your in-app features, and which are struggling to engage and therefore require some attention.

<video autoPlay muted loop playsInline src="https://mintcdn.com/trophy/rGjOHIeZYrVU9hOo/assets/features/users/segmenting_analytics.mp4?fit=max&auto=format&n=rGjOHIeZYrVU9hOo&q=85&s=aad156d4e80c96b75a3a76f14c18d18f" />

## Identifying users

When you tell Trophy about a user in your platform, we call this **identification**. There are two ways you can identify users with Trophy, [inline](#inline-identification) and [explicit](#explicit-identification) identification.

> [!TIP]
>
> We recommend getting started with inline identification if you're new to
> Trophy. If you decide you need more control, try explicit identification.

### Inline identification

Inline identification is the easiest way of telling Trophy about your users as it doesn't require any specific user identification code. You simply tell Trophy about users as they go about normal use of your platform.

In practice this means whenever you use the [Metric Event API](https://docs.trophy.so/api-reference/endpoints/events/submit-a-metric-event.md), you pass along full details of the user who triggered the event.

Here's an example where an API call is made to the metric events API, and the details of the user who made the interaction are passed along in the request body:

```bash cURL theme={null}
curl -X POST https://api.trophy.so/v1/metrics/flashcards-flipped/event \
     -H "X-API-KEY: <apiKey>" \
     -H "Idempotency-Key: flashcard-view-42" \
     -H "Content-Type: application/json" \
     -d '{
  "user": {
    "id": "18",
    "email": "user@example.com",
    "tz": "Europe/London"
  },
  "value": 750
}'
```

```typescript Node theme={null}
import type { EventResponse } from "@trophyso/node/api";

const response: EventResponse = await trophy.metrics.event(
  "flashcards-flipped",
  {
    user: {
      id: "18",
      email: "user@example.com",
      tz: "Europe/London",
    },
    value: 750,
    idempotencyKey: "flashcard-view-42",
  }
);
```

```python Python theme={null}
client.metrics.event(
    key="flashcards-flipped",
    user=EventRequestUser(
        id="18",
        email="user@example.com",
        tz="Europe/London",
    ),
    value=750.0,
)
```

```php PHP theme={null}
$user = new EventRequestUser([
    'id' => '18',
    'email' => 'user@example.com'
]);

$request = new MetricsEventRequest([
    'user' => $user,
    'value' => 750
]);

$trophy->metrics->event("flashcards-flipped", $request);
```

```java Java theme={null}
MetricsEventRequest request = MetricsEventRequest.builder()
      .user(
        EventRequestUser.builder()
          .id("18")
          .email("user@example.com")
          .build()
      )
      .value(750)
      .build();

EventResponse response = client.metrics().event("flashcards-flipped", request);
```

```go Go theme={null}
response, err := client.Metrics.Event(
    "flashcards-flipped",
    &api.MetricsEventRequest{
        User: &api.EventRequestUser{
            Id: "18",
            Email: "user@example.com",
        },
        Value: 750,
    },
)
```

```csharp C# theme={null}
var user = new EventRequestUser {
   Id = "18",
   Email = "user@example.com"
};

var request = new MetricsEventRequest {
   User = user,
   Value = 750
};

await trophy.Metrics.EventAsync("flashcards-flipped", request);
```

```ruby Ruby theme={null}
result = client.metrics.event(
  :key => 'flashcards-flipped',
  :user => {
    :id => '18',
    :email => 'user@example.com'
  },
  :value => 750
)
```

In this case, if this is the user's first interaction (i.e. they are a new user) then a new record will be created for them in Trophy automatically.

However if Trophy finds an existing record with the same `id`, then Trophy will update any details of the user that are passed through.

In other words, inline identification is by means of an `UPSERT` operation.

```mermaid theme={null}
flowchart LR
    A@{ shape: sm-circ }
    B@{ shape: diamond, label: "Is new user?" }
    C@{ shape: rounded, label: "Identify new user" }
    D@{ shape: rounded, label: "Update existing user" }
    E@{ shape: rounded, label: "Process event" }
    F@{ shape: framed-circle }
    A-->B
    B-- Yes --->C
    B-- No --->D
    C-->E
    D-->E
    E-->F
```

Identifying users in this way has two key benefits:

* All new users that sign up for your platform and increment a metric are automatically tracked in Trophy without any explicit identification code written by you
* Any changes to existing user properties like name or email address are automatically synced to Trophy the next time the user increments a metric

In this way inline identification allows you to keep your entire userbase in constant sync with Trophy with the least amount of code required by you.

This is why we recommend starting with inline identification first, then exploring explicit identification if you discover you need more control.

### Explicit identification

Explicit identification is when you write code in your application that explicitly tells Trophy about users separate from any metric interactions. This is useful if you want complete control over how and when Trophy learns about your users.

Scenarios where you might want to use explicit identification might be:

* You want to tell Trophy about new users immediately on sign-up, before they increment a metric
* You track a lot of metrics in Trophy, and don't want to repeat inline identification code.
* You want to only tell Trophy about a specific cohort of users, of which you control the conditions around

In this case, you can tell Trophy about new users using the [User Identification API](https://docs.trophy.so/api-reference/endpoints/users/identify-a-user.md).

```bash cURL theme={null}
curl --request PUT \
  --url https://app.trophy.so/api/users/{id} \
  --header 'Content-Type: application/json' \
  --header 'X-API-KEY: <api-key>' \
  --data '{
  "email": "user@example.com",
  "name": "User",
  "tz": "Europe/London",
  "signUpDate": "2020-08-20",
  "subscribeToEmails": true
}'
```

> [!TIP]
>
> Just like in inline identification, explicit identification also works by
> means of an `UPSERT` operation meaning all user attributes are kept in sync
> with Trophy automatically.

## Creating users

To explicitly create a new user in Trophy, use the [Create User API](https://docs.trophy.so/api-reference/endpoints/users/create-a-user.md).

## Keeping users up to date

To tell Trophy about an update to a user in your platform you can use the [Update User API](https://docs.trophy.so/api-reference/endpoints/users/update-a-user.md).

Any properties that you pass to Trophy will be updated to the new values you specify.

> [!TIP]
>
> As [user identification](#identifying-users) keeps user records up to date by
> default, it's usually not necessary to explicitly update users in Trophy every
> time one of their properties changes in your application. However the user
> update API is there if you really need it.

## Setting user preferences

Trophy has APIs to help you power a preference center that your users can use to control and customize how they interact with your in-app features and the messages they receive.

This section walks through all the preferences that you can expose to your users, and their function.

### Notification preferences

The notification preferences in this section apply to template-based [Emails (Legacy)](https://docs.trophy.so/features/emails.md) and [Push notifications (Legacy)](https://docs.trophy.so/features/push-notifications.md).

> [!NOTE]
>
> Users in the agentic messaging cohort control how often they hear from you and on which channels instead. See [user preferences for agentic messaging](https://docs.trophy.so/agentic-messaging/user-preferences.md).

Trophy's [update preferences API](https://docs.trophy.so/api-reference/endpoints/users/update-user-preferences.md) allows you to build a preference center within your application that your users can interact with to control which notifications they receive, and through which channels.

![](https://mintcdn.com/trophy/vvlxkggAvglghNGz/assets/features/users/notification_preferences.png?fit=max\&auto=format\&n=vvlxkggAvglghNGz\&q=85\&s=414283d6d1edd2058f73a4755cd6700d)

The API lets you update a user's notification preferences for different notification types:

* **achievement\_completed**: Notifications sent when a user completes a milestone
* **recap**: Periodic summary notifications about user progress
* **reactivation**: Notifications sent to re-engage inactive users
* **streak\_reminder**: Reminders to help users maintain their streaks

For each notification type, you can specify which channels the user should receive notifications on: `email`, `push`, or both. To disable a notification type entirely, pass an empty array.

For example, the following code snippet updates a user's notification preferences in Trophy:

```bash cURL theme={null}
curl --request PATCH \
  --url https://api.trophy.so/v1/users/user-123/preferences \
  --header 'Content-Type: application/json' \
  --header 'X-API-KEY: <api-key>' \
  --data '{
  "notifications": {
    "recap": ["email"],
    "streak_reminder": []
  }
}'
```

```typescript Node theme={null}
const response = await trophy.users.updatePreferences("user-123", {
  notifications: {
    recap: ["email"],
    streak_reminder: []
  }
});
```

```python Python theme={null}
response = client.users.update_preferences(
  id="user-123",
  notifications={
    "recap": ["email"],
    "streak_reminder": []
  }
)
```

```php PHP theme={null}
$response = $trophy->users()->updatePreferences("user-123", [
  "notifications" => [
    "recap" => ["email"],
    "streak_reminder" => []
  ]
]);
```

```java Java theme={null}
UpdateUserPreferencesRequest request = UpdateUserPreferencesRequest.builder()
  .notifications(NotificationPreferences.builder()
    .recap(Arrays.asList("email"))
    .streakReminder(Collections.emptyList())
    .build())
  .build();
UserPreferencesResponse response = client.users().updatePreferences("user-123", request);
```

```go Go theme={null}
response, err := client.Users.UpdatePreferences("user-123", &UpdateUserPreferencesRequest{
  Notifications: &NotificationPreferences{
    Recap: []string{"email"},
    StreakReminder: []string{},
  },
})
```

```csharp C# theme={null}
var response = await trophy.Users.UpdatePreferencesAsync("user-123", new UpdateUserPreferencesRequest
{
  Notifications = new NotificationPreferences
  {
    Recap = new[] { "email" },
    StreakReminder = Array.Empty<string>()
  }
});
```

```ruby Ruby theme={null}
response = client.users.update_preferences(
  id: "user-123",
  notifications: {
    recap: ["email"],
    streak_reminder: []
  }
)
```

To build a preference center UI in your application, you'll first need to fetch the user's current preferences using the [get preferences API](https://docs.trophy.so/api-reference/endpoints/users/get-user-preferences.md).

This will return the user's current notification settings, which you can then display in your UI and allow users to modify.

```bash cURL theme={null}
curl --request GET \
  --url https://api.trophy.so/v1/users/user-123/preferences \
  --header 'X-API-KEY: <api-key>'
```

```typescript Node theme={null}
const response = await trophy.users.getPreferences("user-123");
```

```python Python theme={null}
response = client.users.get_preferences(id="user-123")
```

```php PHP theme={null}
$response = $trophy->users()->getPreferences("user-123");
```

```java Java theme={null}
UserPreferencesResponse response = client.users().getPreferences("user-123");
```

```go Go theme={null}
response, err := client.Users.GetPreferences("user-123")
```

```csharp C# theme={null}
var response = await trophy.Users.GetPreferencesAsync("user-123");
```

```ruby Ruby theme={null}
response = client.users.get_preferences(id: "user-123")
```

The API returns a response containing the user's current notification preferences for each notification type:

```json Response {3} theme={null}
{
  "notifications": {
    "achievement_completed": ["email", "push"],
    "recap": ["email"],
    "reactivation": ["push"],
    "streak_reminder": ["email", "push"]
  }
}
```

You can use this response to:

* **Populate form controls**: Pre-select checkboxes or toggles in your preference center UI based on the current values
* **Show current state**: Display which notifications are enabled and through which channels
* **Handle missing preferences**: If a notification type is not present in the response, it means the user hasn't set preferences for it yet, and you can default to your application's default settings

Once you've fetched and displayed the preferences, users can make changes in your UI, and you can use the [update preferences API](https://docs.trophy.so/api-reference/endpoints/users/update-user-preferences.md) to save their selections back to Trophy.

### Streak preferences

Trophy supports user preferences for streaks, allowing users to customize the conditions they must meet to extend their streak, including which days of the week count toward it.

> [!NOTE]
>
> In order to use streak preferences, you must have [streak personalization](https://docs.trophy.so/features/streaks.md#streak-personalization) enabled.

Once streak personalization is enabled, the [update preferences API](https://docs.trophy.so/api-reference/endpoints/users/update-user-preferences.md) will allow you to override default streak settings for a specific user.

The following streak settings can be overridden by user preferences:

* `enabled`: Whether streaks are calculated for this user. When `false`, the user's streak is always `0` and streak webhooks and notifications are not sent.
* `metrics`: An array of [metrics](https://docs.trophy.so/data-sources/metrics.md) with custom thresholds required to extend the streak.
* `evaluationMode`: Determines how metrics combine to extend the streak. Can be `ALL` or `OR`.
* `daysOff`: An array of weekday numbers (`0` = Sunday through `6` = Saturday) that override the organization [days off](https://docs.trophy.so/features/streaks.md#days-off). The user will not lose their streak if they are inactive on these days.

```json Streak preferences theme={null}
{
  "streak": {
    "enabled": true,
    "evaluationMode": "OR",
    "daysOff": [1, 3, 5],
    "metrics": [
      { "key": "words-written", "threshold": 500 }
    ]
  }
}
```

Once streak preferences are set, the [get preferences API](https://docs.trophy.so/api-reference/endpoints/users/get-user-preferences.md) will return the user's personalized streak settings.

## Retrieving user information

To fetch the details of a user that you've already identified with Trophy, use the [Get User API](https://docs.trophy.so/api-reference/endpoints/users/get-a-single-user.md).

This will return the full details of the user, including the [read-only attributes](#read-only-attributes) `control` and `agenticMessagingEnabled`. Use `control` to conditionally enroll users in in-app features, and `agenticMessagingEnabled` to check whether the user receives agentic messages.

```json Response {3-4} theme={null}
{
  "id": "user-id",
  "control": false,
  "agenticMessagingEnabled": false,
  "created": "2021-01-01T00:00:00Z",
  "email": "user@example.com",
  "name": "User",
  "signUpDate": "2020-08-20",
  "subscribeToEmails": true,
  "tz": "Europe/London",
  "updated": "2021-01-01T00:00:00Z"
}
```

## User analytics

### Basic analytics

By default Trophy includes high-level user analytics including on the [Users page](https://app.trophy.so/users) including:

* The total number of users that you've told Trophy about
* The number of users that are active on a daily basis
* The number of users that are active on a monthly basis

![](https://mintcdn.com/trophy/rGjOHIeZYrVU9hOo/assets/features/users/user_analytics.png?fit=max\&auto=format\&n=rGjOHIeZYrVU9hOo\&q=85\&s=1ce5c77360e2e921eddf244e1a04c8b3)

On this page you can also search through every user that Trophy has recorded, which can be useful for debugging.

### Top users

Additionally, on the [Dashboard](https://app.trophy.so), Trophy shows a *Top Users* list with the set of users who have made the most progress against your platform's metrics.

These are your most engaged users, so it's useful to know who they are!

## Frequently asked questions

> [accordion] How many users can I tell Trophy about?
>
> As many as you want! Trophy only charges each month for *active* users, which are the users that interact with your product at least once in a given month.
>
> This is great because it means if a user churns, you won't pay for them in subsequent months.
>
> You can view the total number of users you'll be charged for each month within Trophy on the sidebar:
>
> ![](https://mintcdn.com/trophy/vvlxkggAvglghNGz/assets/features/users/usage_block.png?fit=max\&auto=format\&n=vvlxkggAvglghNGz\&q=85\&s=b23c4403f2eb88b8d9dca5534f39345b)
>
> You can estimate your usage costs on our [Pricing page](https://trophy.so/pricing).

## Get support

Want to get in touch with the Trophy team? Reach out to us via [email](mailto:support@trophy.so). We're here to help!


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.