Users

The Stream user object is central to every product and appears in many API responses, effectively following the user throughout the platform. Only an id is required to create a user but you can store additional custom data. We recommend only storing what is necessary, such as a username and image URL.

The operations performed on users, such as updating and deleting, have an effect on all products (chat, video and feeds).

Creating users

When creating users, there are a few important things to keep in mind:

  • The id field is mandatory, in most cases you want this to be the same ID you use on your database.
  • The role field is optional, by default it is set to user but you can specify any existing role.
  • Custom data can be added to users in the custom field.
  • name and image are optional and handled by all SDKs automatically to render users.
  • The language field (ISO 639-1) is optional but recommended when using activity and comment translation in Feeds. It helps the API determine the source language when translating content authored by that user.

Users are also created on the fly when they connect from a client-side SDK, with the user role. However, it is also common to add your users to Stream before going live and keep properties of your user base in sync. For this you'll want to use the upsertUsers function server-side and send users in bulk.

The upsertUser method creates or updates a user, replacing its existing data with the new payload (see below for partial updates). To create or update users in batches of up to 100, use the upsertUsers or partialUpdateUsers APIs, which accept an array of user objects.

const updateResponse = await serverClient.upsertUser({
  id: userID,
  role: "admin",
  book: "dune",
});

And for a batch of users, simply add additional entries (up to 100) into the array you pass to upsertUsers:

const updateResponse = await serverClient.upsertUsers([
  { id: userID1, role: "admin", book: "dune" },
  { id: userID2, role: "user", book: "1984" },
  { id: userID3, role: "admin", book: "Fahrenheit 451" },
]);
// each user object is updated accordingly

If any user in a batch of users contains an error, the entire batch will fail, and the first error encountered will be returned.

Partial updates

If you need to update a subset of properties for a user(s), you can use a partial update method. Both set and unset parameters can be provided to add, modify, or remove attributes to or from the target user(s). The set and unset parameters can be used separately or combined.

// partial update for a single user setting and unsetting multiple fields
const update = {
  id: "userID",
  set: {
    role: "admin",
    field: {
      text: "value",
    },
    "field2.subfield": "test",
  },
  unset: ["field.unset"],
};

const response = await client.partialUpdateUser(update);

// partial update for multiple users
const updates = [
  {
    id: "userID",
    set: {
      field: "value",
    },
  },
  {
    id: "userID2",
    unset: ["field.value"],
  },
];

const response = await client.partialUpdateUsers(updates);

Partial updates support batch requests, similar to the upsertUser endpoint.

Unique usernames

Clients can set a username, by setting the name custom field. The field is optional and by default has no uniqueness constraints applied to it, however this is configurable by setting the enforce_unique_username to either app or team.

When checking for uniqueness, the name is normalized, by removing any white-space or other special characters, and finally transforming it to lowercase. So "John Doe" is considered a duplicate of "john doe", "john.doe", etc.

With the setting at app, creating or updating a user fails if the username already exists anywhere in the app. With team, it only fails if the username exists within the same team.

// Enable uniqueness constraints on App level
await client.updateAppSettings({
  enforce_unique_usernames: "app",
});

// Enable uniqueness constraints on Team level
await client.updateAppSettings({
  enforce_unique_usernames: "team",
});

Enabling this setting will only enforce the constraint going forward and will not try to validate existing usernames.

Built-in fields for users

UserResponse

NameTypeDescriptionConstraints
avg_response_timeinteger--
ban_expiresnumberDate when ban expires-
bannedbooleanWhether a user is banned or notRequired
blocked_user_idsstring[]-Required
created_atnumberDate/time of creationRequired
customobjectCustom data for this objectRequired
deactivated_atnumberDate of deactivation-
deleted_atnumberDate/time of deletion-
devicesDeviceResponse[]List of devices user is using-
idstringUnique user identifierRequired
imagestring--
invisibleboolean-Required
languagestringPreferred language of a userRequired
last_activenumberDate of last activity-
namestringOptional name of user-
onlinebooleanWhether a user online or notRequired
privacy_settingsPrivacySettingsResponseUser privacy settings-
push_notificationsPushNotificationSettingsResponseUser push notification settings-
revoke_tokens_issued_beforenumberRevocation date for tokens-
rolestringDetermines the set of user permissionsRequired
shadow_bannedbooleanWhether a user is shadow bannedRequired
teamsstring[]List of teams user is a part ofRequired
teams_roleobject--
updated_atnumberDate/time of the last updateRequired

Guest and anonymous users

Stream lets you give unauthenticated users access to a limited subset of features. Guest and anonymous users are ideal when users need to see content before authenticating, such as watching a livestream or browsing public feeds, or where the friction of creating an account is unnecessary.

Configuration for the guest and anonymous roles can be managed in the dashboard.

Guest users

Guest users are temporary user accounts with a name and image. Guest sessions can be created client-side and do not require server-side authentication. Guest users are not available to applications using multi-tenancy (teams).

Guest users are counted towards your MAU usage. Creation of guest users can be disabled for your application in the dashboard.

To create a guest user from your server and obtain a token for the client:

const response = await client.createGuest({
  user: { id: "tommaso", name: "Tommaso" },
});
// Return response.user and response.access_token to your client

The user object schema is the same as the one described in the Built-in fields for users section above.

Feeds client SDKs can also create guest sessions directly, without a server call:

import { useCreateFeedsClient } from "@stream-io/feeds-react-sdk";

const client = useCreateFeedsClient({
  apiKey,
  userData: { id: "tommaso" },
  tokenOrProvider: "guest",
});

Anonymous users

Anonymous users are not authenticated and have limited capabilities by default: they can read content where permissions allow, such as a public livestream or feed, but they are not allowed to perform any write operations. Anonymous users can be connected using client-side SDKs.

Anonymous users are not counted toward your MAU and can't establish a WebSocket connection.

Feeds client SDKs connect anonymous users like this:

import { useCreateFeedsClient } from "@stream-io/feeds-react-sdk";

const client = useCreateFeedsClient({
  apiKey,
  tokenOrProvider: "anonymous",
});

Querying users

You can query and filter users using the queryUsers endpoint. This allows you to search for users based on various criteria such as custom fields, roles, and other user properties.

const response = await client.queryUsers({
  payload: {
    filter_conditions: {
      role: "admin",
    },
    sort: [{ field: "created_at", direction: -1 }],
    limit: 10,
    offset: 0,
  },
});

console.log(response.users);

All filters use a Mongoose-style syntax; however, we do not run MongoDB on the backend, so only a subset of Mongoose queries are supported. The supported filters are described below.

Filter examples

You can use various filter operators to query users:

// Query users by custom field
const response = await client.queryUsers({
  payload: {
    filter_conditions: {
      "custom.color": "red",
    },
  },
});

// Query users with multiple conditions
const response2 = await client.queryUsers({
  payload: {
    filter_conditions: {
      role: { $in: ["admin", "moderator"] },
      "custom.plan": "premium",
    },
  },
});

Supported Filters

NameTypeDescriptionAllowed Operators
idstringID of the user$eq, $ne, $in, $nin, $gt, $gte, $lt, $lte, $autocomplete
rolestringRole of the user$eq, $gt, $gte, $lt, $lte, $in
bannedbooleanWhether the user is banned$eq, $ne
shadow_bannedbooleanWhether the user is shadow banned$eq, $ne
created_atstring, must be formatted as an RFC3339 timestampTime when the user was created$eq, $gt, $gte, $lt, $lte, $in
updated_atstring, must be formatted as an RFC3339 timestampTime when the user was updated$eq, $gt, $gte, $lt, $lte, $in
last_activestring, must be formatted as an RFC3339 timestampTime when the user was last active$eq, $gt, $gte, $lt, $lte, $in, $exists
teamsstringTeams the user belongs to$eq, $contains, $in
namestringName of the user$eq, $in, $autocomplete
usernamestringUsername of the user$eq, $autocomplete
custom propertiesstring, boolean, intCustom user properties$eq

Query Users Performance

Query Users runs on an indexed user database. To keep response times predictable for apps of every size, filters that cannot use an index are rejected with a 400 error.

Custom fields only support exact matches. Custom properties are stored in a JSON column, and the index on that column only supports exact-match lookups. Range operators such as $gt, $gte, $lt, and $lte (as well as $in, $exists, and $contains) on a custom field cannot use the index and would require scanning every user in your app, so they are not allowed. If you need range queries on a field, consider using one of the built-in indexed fields (such as created_at, updated_at, or last_active), or query your own database instead.

Not-equal operators are only allowed on id and boolean fields. The $ne, $nin, and $nor operators are only supported on the id field (and $ne on boolean fields such as banned). On other fields these negative filters prevent the database query planner from using an index: instead of seeking directly to matching rows, it has to walk through everything that does not match, which can result in slow queries and timeouts.

You can usually rewrite a negative filter as a positive one. For example, instead of role: { $ne: "admin" }, query for the roles you do want: role: { $eq: "user" } or role: { $in: ["user", "moderator"] }. Positive filters are index-backed and fast.

Supported Sort

You can sort results by specifying a field and direction (1 for ascending, -1 for descending).

NameDescription
idUser ID
created_atTime when the user was created
updated_atTime when the user was updated
last_activeTime when the user was last active
roleRole of the user

Supported Options

The options for the queryUsers method are primarily used for pagination.

NameTypeDescriptionDefaultOptional
limitintegerNumber of users to return30
offsetintegerOffset for pagination0
id_gtstringID-based pagination. Return IDs greater than this ID. If this is not empty, the default sort order will be [{id: -1}].-
id_gtestringID-based pagination. Return IDs greater than or equal to this ID. If this is not empty, the default sort order will be [{id: -1}].-
id_ltstringID-based pagination. Return IDs less than this ID. If this is not empty, the default sort order will be [{id: -1}].-
id_ltestringID-based pagination. Return IDs less than or equal to this ID. If this is not empty, the default sort order will be [{id: -1}].-
include_deactivated_usersbooleanInclude deactivated users in the response-

The maximum offset value is 1000.

Querying with Autocomplete

You can use the $autocomplete operator to search for users by name or ID with partial matching.

const response = await client.queryUsers({
  payload: {
    filter_conditions: {
      name: { $autocomplete: "ro" },
    },
  },
});

Querying Inactive Users

You can use the last_active field with the $exists operator to find users who have never connected. Use $exists: false for users who have never been active, or $exists: true for users who have connected at least once.

const response = await client.queryUsers({
  payload: {
    filter_conditions: {
      id: { $in: [activeUser, neverActiveUser] },
      last_active: { $exists: false },
    },
  },
});

Deactivating and deleting users

Depending on your use case, you can choose to delete users or deactivate them. There are some differences between these two approaches.

Deactivating users:

  • the user will not be allowed to perform API requests / connect
  • user data is retained on Stream's side and returned from API
  • deactivated users can be re-activated

Deleting users:

  • the user will no longer be able to perform API requests / connect
  • the user is deleted and, by default, not returned from API
  • all data from the user is marked as deleted
  • by default, the data is retained and "soft" deleted; you can optionally request hard deletion
  • deletion is not reversible

Both bulk deletion and bulk deactivation are performed asynchronously by the Stream API. A task ID is returned and you can use that to check the status of its processing.

Deactivating users

client.deactivateUser({
  user_id: '<id>',
});

// reactivate
client.reactivateUsers({
  user_ids: ['<id>'],
});

// deactivating users in bulk is performed asynchronously
const deactivateResponse = client.deactivateUsers({
  user_ids: ['<id1>', '<id2>'...],
});

Deactivating users in bulk can take some time. Monitor the returned task ID as described in Async operations.

In Chat, deactivation and reactivation accept additional parameters: mark_messages_deleted on deactivate soft-deletes all messages the user sent, restore_messages on reactivate restores them, and created_by_id records which user performed the operation.

const deactivate = await client.deactivateUser(userID, {
  mark_messages_deleted: true,
  created_by_id: "joe",
});

const reactivate = await client.reactivateUser(userID, {
  restore_messages: true,
  name: "I am back",
  created_by_id: "joe",
});

Deleting users

client.deleteUsers({ user_ids: ["<id>"] });

//restore
client.restoreUsers({ user_ids: ["<id>"] });

You can delete up to 100 users per call. The user parameter controls what happens to the user object itself:

NameTypeDescriptionDefaultOptional
userenum (soft, pruning, hard)Soft: marks user as deleted and retains all user data. Pruning: marks user as deleted and nullifies user information. Hard: deletes user completely.soft

Each product adds parameters that control what happens to the user's product data.

Chat parameters

NameTypeDescriptionDefaultOptional
conversationsenum (soft, hard)Soft: marks all conversation channels as deleted (same effect as Delete Channels with 'hard' option disabled). Hard: deletes channel and all its data completely including messages (same effect as Delete Channels with 'hard' option enabled).-
messagesenum (soft, pruning, hard)Soft: marks all user messages as deleted without removing any related message data. Pruning: marks all user messages as deleted, nullifies message information and removes some message data such as reactions and flags. Hard: deletes messages completely with all related information.-
new_channel_owner_idstringChannels owned by hard-deleted users will be transferred to this userID.-

Hard-deleting the user itself requires the hard option for messages and conversations as well.

When deleting a user, if you wish to transfer ownership of their channels to another user, provide that user's ID in the new_channel_owner_id field. Otherwise, the channel owner will be updated to a system generated ID like delete-user-8219f6578a7395g.

Video parameters

NameTypeDescriptionDefaultOptional
callsenum (soft, hard)Soft: marks calls and related data as deleted. Hard: deletes calls and related data completely. This applies only to 1:1 calls, not group calls.-

Exporting or deleting user data to meet compliance requests is covered on GDPR and privacy.

Restoring deleted users

If users are soft deleted, they can be restored using the server-side client. However, only the user's metadata is restored; product data such as memberships, messages and reactions is not restored.

You can restore up to 100 users per call:

await client.restoreUsers(["userID1", "userID2"]);