Realtime API
The Realtime API provides access a continuous, up-to-date flow of your TalkJS data without the need to send repeated requests or open a chat UI.
Preview: The Realtime API is safe to use in production, but it is still a work in progress. If we make changes to these methods in the future, we will continue to support the current version forever. However this backwards compatibility will be undocumented and not exposed in TypeScript type definitions.
Refs
These reference a specific resource in TalkJS, letting you get or set data on that resource.
Refs don't contain any actual data themselves, they just point to a TalkJS resource.
You can get the actual data (a snapshot) by calling .get()
on a ref.
References the user with a given user ID.
Used in all Realtime API operations affecting that user, such as fetching or updating user data, or adding a user to a conversation. Created via Session.user.
createIfNotExists | Creates a user with this ID, or does nothing if a user with this ID already exists. |
get | Fetches a snapshot of the user. |
set | Sets properties of this user. The user is created if a user with this ID doesn't already exist. |
subscribe | Subscribe to this user's state. |
The ID of the referenced user.
Immutable: if you want to reference a different user, get a new UserRef instead.
userRef.createIfNotExists(params): Promise<void>
Creates a user with this ID, or does nothing if a user with this ID already exists.
If the user already exists, this operation is still considered successful and the promise will still resolve. This operation fails if client-side user syncing is disabled.
Parameters
Returns
A promise that resolves when the operation completes.
userRef.get(): Promise<UserSnapshot | null>
Fetches a snapshot of the user.
This contains all of a user's public information. Fetching a user snapshot doesn't require any permissions. You can read the public information of any user. Private information, such as email addresses and phone numbers, aren't included in the response.
Supports Automatic Batching and Cached Fetch
Returns
A snapshot of the user's public attributes, or null if the user doesn't exist.
userRef.set(params): Promise<void>
Sets properties of this user. The user is created if a user with this ID doesn't already exist.
name
is required when creating a user. This operation fails if you don't provide a name
and the user does not exist yet. This operation also fails if client-side user syncing is disabled.
Parameters
Returns
A promise that resolves when the operation completes.
userRef.subscribe(onSnapshot): UserSubscription
Subscribe to this user's state.
Whenever the user's attributes change, onSnapshot
will fire and Subscription.latestSnapshot
will be updated.
Supports Subscription Sharing and Debounced Unsubscribe
Parameters
Returns
A subscription to the user
References the conversation with a given conversation ID, from the perspective of the current user.
Used in all Realtime API operations affecting that conversation, such as fetching or updating conversation attributes. Created via Session.conversation.
createIfNotExists | Creates this conversation if it does not already exist. Adds you as a participant in this conversation, if you are not already a participant. |
get | Fetches a snapshot of the conversation. |
participant | Get a reference to a participant in this conversation |
set | Sets properties of this conversation and your participation in it. |
The ID of the referenced conversation.
Immutable: if you want to reference a different conversation, get a new ConversationRef instead.
conversationRef.createIfNotExists(params): Promise<void>
Creates this conversation if it does not already exist. Adds you as a participant in this conversation, if you are not already a participant.
If the conversation already exists or you are already a participant, this operation is still considered successful and the promise will still resolve. This operation fails if client-side conversation syncing is disabled.
Parameters
Returns
A promise that resolves when the operation completes.
conversationRef.get(): Promise<ConversationSnapshot | null>
Fetches a snapshot of the conversation.
This contains all of the information related to the conversation and the current user's participation in the conversation. You must be a participant in the conversation.
Does not support Automatic Batching yet. Sequential calls will be sent as multiple requests.
Returns
A snapshot of the current user's view of the conversation, or null if the current user is not a participant (including if the conversation doesn't exist).
conversationRef.participant(user): ParticipantRef
Get a reference to a participant in this conversation
Parameters
the user's ID or a reference to the user
Returns
conversationRef.set(params): Promise<void>
Sets properties of this conversation and your participation in it.
The conversation is created if a conversation with this ID doesn't already exist. You are added as a participant if you are not already a participant in the conversation.
Parameters
Returns
A promise that resolves when the operation completes.
References a given user's participation in a conversation.
Used in all Realtime API operations affecting that participant, such as joining/leaving a conversation, or setting their access. Created via ConversationRef.participant.
createIfNotExists | Adds the user as a participant, or does nothing if they are already a participant. |
delete | Removes the user as a participant, or does nothing if they are already not a participant. |
edit | Edits properties of a pre-existing participant. If the user is not already a participant in the conversation, the promise will reject. |
get | Fetches a snapshot of the participant. |
set | Sets properties of this participant. If the user is not already a participant in the conversation, they will be added. |
The ID of the conversation the user is participating in.
Immutable: if you want to reference the user in a different conversation, get a new ParticipantRef instead.
The ID of the user who is participating.
Immutable: if you want to reference a different participant, get a new ParticipantRef instead.
participantRef.createIfNotExists(params): Promise<void>
Adds the user as a participant, or does nothing if they are already a participant.
If the participant already exists, this operation is still considered successful and the promise will still resolve. This operation fails if client-side conversation syncing is disabled.
Supports Automatic Batching
Parameters
Returns
A promise that resolves when the operation completes.
participantRef.delete(): Promise<void>
Removes the user as a participant, or does nothing if they are already not a participant.
If the user is already not a participant this operation is still considered successful and the promise will still resolve. This operation fails if client-side conversation syncing is disabled.
Returns
A promise that resolves when the operation completes.
participantRef.edit(params): Promise<void>
Edits properties of a pre-existing participant. If the user is not already a participant in the conversation, the promise will reject.
This operation fails if client-side conversation syncing is disabled.
Supports Automatic Batching
Parameters
Returns
A promise that resolves when the operation completes.
participantRef.get(): Promise<ParticipantSnapshot | null>
Fetches a snapshot of the participant.
This contains all of the participant's public information. You must be a participant in the conversation to fetch information about other participants.
Returns
A snapshot of the participant's attributes, or null if the user is not a participant.
participantRef.set(params): Promise<void>
Sets properties of this participant. If the user is not already a participant in the conversation, they will be added.
This operation fails if client-side conversation syncing is disabled.
Supports Automatic Batching
Parameters
Returns
A promise that resolves when the operation completes.
Snapshots
When you fetch data for a ref, you get a snapshot. Snapshots contains all the relevant information about a resource, at a specific point in time. If the data changes on the database, old snapshots will not be automatically updated.
A snapshot of a user's attributes at a given moment in time.
Users also have private information, such as email addresses and phone numbers, but these are only exposed on the REST API.
Custom metadata you have set on the user
The unique ID that is used to identify the user in TalkJS
An IETF language tag. For more information, see: Localization.
When locale
is null, the app's default locale will be used
The user's name, which is displayed on the TalkJS UI
An optional URL to a photo that is displayed as the user's avatar
TalkJS supports multiple sets of settings for users, called "roles". Roles allow you to change the behavior of TalkJS for different users. You have full control over which user gets which configuration.
The default message a person sees when starting a chat with this user
A snapshot of a conversation's attributes at a given moment in time.
Also includes information about the current user's view of that conversation, such as whether or not notifications are enabled.
The current user's permission level in this conversation.
The date that the conversation was created, as a unix timestamp in milliseconds.
Custom metadata you have set on the conversation
The ID of the conversation
Whether the conversation should be considered unread.
This can be true even when unreadMessageCount
is zero, if the user has manually marked the conversation as unread.
The date that the current user joined the conversation, as a unix timestamp in milliseconds.
The date of the conversation's most recent message, as a unix timestamp in milliseconds.
If no messages have been sent, this will be the date that the conversation was created instead. To show a chronological list of recent conversations, sort by this property.
The current user's notification settings for this conversation.
false
means no notifications, true
means notifications for all messages, and "MentionsOnly"
means that the user will only be notified when they are mentioned with an @
.
Contains the URL of a photo was set using ConversationBuilder.subject.
Contains the conversation subject if it was set using ConversationBuilder.subject.
The number of messages in this conversation that the current user hasn't read.
One or more welcome messages that will display to the user as a SystemMessage
A snapshot of a participant's attributes at a given moment in time.
The level of access this participant has in the conversation.
When the participant will be notified about new messages in this conversation.
false
means no notifications, true
means notifications for all messages, and "MentionsOnly"
means that the user will only be notified when they are mentioned with an @
.
The user who this Participant Snapshot is referring to
Other Interfaces
These interfaces are used when sending requests.
Parameters you can pass when creating a user.
The user's name which is displayed on the TalkJS UI
Custom metadata you have set on the user. Default = no custom metadata
An array of email addresses associated with the user. Default = no email addresses
An IETF language tag. See the localization documentation Default = the locale selected on the dashboard
An array of phone numbers associated with the user. Default = no phone numbers
An optional URL to a photo that is displayed as the user's avatar. Default = no photo
An object of push registration tokens to use when notifying this user.
Keys in the object have the format 'provider:token_id'
, where provider
is either "fcm"
for Android (Firebase Cloud Messaging), or "apns"
for iOS (Apple Push Notification Service).
Default = no push registration tokens
TalkJS supports multiple sets of settings, called "roles". These allow you to change the behavior of TalkJS for different users. You have full control over which user gets which configuration. Default = the default
role
The default message a person sees when starting a chat with this user. Default = no welcome message
Parameters you can pass when updating a user.
Properties that are undefined
will not be changed. To clear / reset a property to the default, pass null
.
Custom metadata you have set on the user. This value acts as a patch. Remove specific properties by setting them to null
. Default = no custom metadata
An array of email addresses associated with the user. Default = no email addresses
An IETF language tag. See the localization documentation Default = the locale selected on the dashboard
The user's name which will be displayed on the TalkJS UI
An array of phone numbers associated with the user. Default = no phone numbers
An optional URL to a photo which will be displayed as the user's avatar. Default = no photo
An object of push registration tokens to use when notifying this user.
Keys in the object have the format 'provider:token_id'
, where provider
is either "fcm"
for Android (Firebase Cloud Messaging), or "apns"
for iOS (Apple Push Notification Service).
The value for each key can either be true
to register the device for push notifications, or null
to unregister that device.
Setting pushTokens to null unregisters all the previously registered devices.
Default = no push tokens
TalkJS supports multiple sets of settings, called "roles". These allow you to change the behavior of TalkJS for different users. You have full control over which user gets which configuration. Default = the default
role
The default message a person sees when starting a chat with this user. Default = no welcome message
Parameters you can pass when creating a conversation.
Properties that are undefined
will be set to the default.
Your access to the conversation. Default = "ReadWrite" access.
Custom metadata you have set on the conversation. This value acts as a patch. Remove specific properties by setting them to null
. Default = no custom metadata
Your notification settings. Default = true
The URL for the conversation photo to display in the chat header. Default = no photo, show a placeholder image.
The conversation subject to display in the chat header. Default = no subject, list participant names instead.
System messages which are sent at the beginning of a conversation. Default = no messages.
Parameters you can pass when updating a conversation.
Properties that are undefined
will not be changed. To clear / reset a property to the default, pass null
.
Your access to the conversation. Default = "ReadWrite" access.
Custom metadata you have set on the conversation. This value acts as a patch. Remove specific properties by setting them to null
. Default = no custom metadata
Your notification settings. Default = true
The URL for the conversation photo to display in the chat header. Default = no photo, show a placeholder image.
The conversation subject to display in the chat header. Default = no subject, list participant names instead.
System messages which are sent at the beginning of a conversation. Default = no messages.
Parameters you can pass when creating a participant (adding a user to a conversation).
The level of access the participant should have in the conversation. Default = "ReadWrite" access.
When the participant should be notified about new messages in this conversation. Default = true
false
means no notifications, true
means notifications for all messages, and "MentionsOnly"
means that the user will only be notified when they are mentioned with an @
.
Parameters you can pass when updating a participant.
Properties that are undefined
will not be changed. To clear / reset a property to the default, pass null
.
The level of access the participant should have in the conversation. Default = "ReadWrite" access.
When the participant should be notified about new messages in this conversation. Default = `true access.
false
means no notifications, true
means notifications for all messages, and "MentionsOnly"
means that the user will only be notified when they are mentioned with an @
.
Subscriptions
When you subscribe to a resource, you get a subscription. Subscription objects store the current state of your subscription, and allow you to unsubscribe.
A subscription to a specific user
unsubscribe | Unsubscribe from this resource and stop receiving updates. |
Resolves when the subscription starts receiving updates from the server.
The current state of the subscription
An object with the following fields:
type
is one of "pending", "active", "unsubscribed", or "error".
latestSnapshot
is only set when type
is "active". It contains the most recently received snapshot for this subscription.
error
is only set when type
is "error". It is the JS Error
object for the error that caused the subscription to be terminated.
Resolves when the subscription permanently stops receiving updates from the server.
This is either because we manually unsubscribed or because the subscription encountered an unrecoverable error.
userSubscription.unsubscribe()
Unsubscribe from this resource and stop receiving updates.
If the subscription is already in the "unsubscribed" or "error" state, this is a no-op.
Returns
Performance
The Realtime API has various optimisations to allow you to use it in a simple way, while still getting maximum performance. Our design philosophy is that the "naive solution" should also be best-practice.
There is no getMany
or subscribeMany
method.
Instead, we automatically combine sequential calls into one request.
So when you want to fetch 1000 users at once, you can do:
1for (let i = 0; i < 1000; i++) {2 session.user(`user ${i}`).subscribe(...);3}
At the end of the synchronous code block, we will send one request asking for the data of all 1000 users. Each of the 1000 promises then gets resolved with its individual data.
There is no subscription.addSnapshotListener
method, where you can attach a new listener to a pre-existing subscription.
So when you want to attach 5 different listeners to a user, you can do:
1for (let i = 0; i < 5; i++) {2 session.currentUser.subscribe(() => console.log(i))3}
This will result in only one subscription on the backend, with your 5 listeners attached to it. We won't officially unsubscribe until all 5 of your subscriptions have unsubscribed.
When you unsubscribe from a subscription, we wait a little bit before officially unsubscribing. This means that if you unsubscribe and then immediately resubscribe, it happens instantly without sending any requests to the backend. For example, if you are subscribed to a user and want to change the callback to something else:
1const subscription = session.currentUser.subscribe(...);23// Later4subscription.unsubscribe();5const subscription2 = session.currentUser.subscribe(...);
This will not trigger any call to the backend, because internally we are still subscribed to currentUser
when you resubscribe.
This is important because staying subscribed is generally much more efficient than subscribing in the first place.
The amount of time the client will stay subscribed is different for each resource.
Simpler resources that change less often (like users) stay subscribed for longer, because being subscribed to something that rarely changes is almost free.
When you fetch a resource that you are subscribed to, we already know the current state without having to ask the backend. This means that the method becomes synchronous and essentially free. For example:
1session.currentUser.subscribe();23// Later4await session.currentUser.get();
This get
call will not trigger any request to the backend and will return the data instantly.
If you know you are going to get
some data repeatedly, consider subscribing to improve performance.