TalkSession
This is the entry point to the standalone JavaScript Data API. Use TalkSession if you have installed the JavaScript Data API as a separate npm package, @talkjs/core.
If you use the JavaScript Data API as part of the Classic JavaScript SDK, use Session instead. You can still access the data API through methods like Session.conversation.
The getTalkSession function returns a TalkSession object for a given app ID and user ID:
1import { getTalkSession } from '@talkjs/core';23const session = getTalkSession({4 appId: '<APP_ID>',5 userId: '<USER_ID>',6});
The following options are available when calling getTalkSession:
| Name | Type | Description |
|---|---|---|
| appId Required | string | Your app's unique TalkJS ID. Get it from the Settings page of the dashboard. |
| userId Required | string | The id of the user you want to connect and act as. Any messages you send will be sent as this user. |
Calling getTalkSession multiple times with the same appId and userId will reuse the initial TalkSession object each time, rather than creating a new session.
The following deprecated options are supported for backwards-compatibility but have been replaced and are not recommended for new integrations.
| Name | Type | Description |
|---|---|---|
| token Deprecated | string | Deprecated: Call TalkSession.setToken instead. A token to authenticate the session with. Ignored if a TalkSession object already exists for this appId + userId. |
| tokenFetcher Deprecated | () => Promise<string> | Deprecated: Set TalkSession.onNeedToken instead. A callback that fetches a new token from your backend and returns it. If this callback throws an error or returns a rejected promise, the session will terminate. Your callback should retry failed requests. Ignored if a TalkSession object already exists for this appId + userId. |
The session returned by getTalkSession.
| setToken | Set the auth token to be used on this session. |
| user | Get a reference to a user. |
| conversation | Get a reference to a conversation. |
| subscribeConversations | Subscribes to your most recently active conversations. |
| onError | Attaches a listener for fatal errors. |
| uploadFile | Upload a generic file without any additional metadata. |
| uploadImage | Upload an image with image-specific metadata. |
| uploadVideo | Upload a video with video-specific metadata. |
| uploadAudio | Upload an audio file with audio-specific metadata. |
| uploadVoice | Upload a voice recording with voice-specific metadata. |
| Field | Type | Description |
|---|---|---|
| currentUser | UserRef | A read-only reference to the user whose ID you passed to getTalkSession. |
| onNeedToken (Mutable) | () => void | A function that runs when a new authentication token is needed, including the first time you request data, and whenever the existing token is about to expire. Set onNeedToken if you use authentication with refreshable tokens.This function should call setToken with a new token. Ensure that the callback retries automatically when experiencing temporary issues such as network problems. |
talkSession.setToken(token): void
Set the auth token to be used on this session (and all other sessions with the same appId and userId).
This will immediately reauthenticate the websocket connection to TalkJS, overwriting any previous tokens on the session.
This does not affect any in-progress requests. As long as the new token is valid, your subscriptions will stay active with no gaps or missing data during reauthentication.
Parameters
The new auth token to use.
Returns
void
Usage
Example 1 Non-refreshable authentication
1const session = getTalkSession({2 appId: '<APP_ID>',3 userId: '<USER_ID>',4});5session.setToken('...');
Example 2 Refreshable authentication
1const session = getTalkSession({2 appId: '<APP_ID>',3 userId: '<USER_ID>',4});5session.onNeedToken = async () => {6 const token = await fetchToken();7 session.setToken(token);8};
talkSession.user(id): UserRef
Get a reference to a user.
The returned UserRef is part of the Data API, which is included in the Chat SDK. This is the entry-point for all Data API operations that affect a user globally, such as editing their name. You can use references to get, edit, and subscribe to your data.
Parameters
The ID of the user that you want to reference
Returns
A UserRef for the user with that ID
Usage
1const userRef = session.user("test");2userRef.createIfNotExists({ name: "Alice" });
talkSession.conversation(id): ConversationRef
Get a reference to a conversation.
The returned ConversationRef is part of the Data API, which is included in the Chat SDK. You can use references to get, edit, and subscribe to your data.
Parameters
The ID of the conversation that you want to reference
Returns
A ConversationRef for the conversation with that ID
Usage
1session.conversation("test").createIfNotExists();
1session.conversation("test").set({ subject: "Power tools" });
1session.conversation("test").set({ notify: false });
talkSession.subscribeConversations(onSnapshot): ConversationListSubscription
Subscribes to your most recently active conversations.
While the subscription is active, onSnapshot will be called whenever the conversation snapshots change. This includes when you join or leave a conversation, when the conversation attributes change, and when you load more conversations. It also includes when nested data changes, such as when snapshot[0].lastMessage.referencedMessage.sender.name changes. Be careful when doing heavy computation inside onSnapshot, and consider caching the result. onSnapshot is called extremely often. loadedAll is true when snapshot contains all your conversations, and false if you could load more.
The snapshot list is ordered chronologically with the most recently active conversations at the start. The last activity of a conversation is either when the last message was sent or when you joined, whichever is later. In other words, it's the max of lastMessage.createdAt and joinedAt. If you join a new conversation, or you receive a message in a conversation, that conversation will appear at the start of the list.
The snapshot is an empty list if the current user does not exist yet.
Initially, you will be subscribed to the 20 most recently active conversations and any conversations that have activity after you subscribe. Call loadMore to load additional older conversations. This will trigger onSnapshot.
Tip: ConversationSnapshot has a lastMessage property. Whenever you are sent a message, that message will be at snapshot[0].lastMessage. If you just want to react to newly received messages, you can use this instead of calling ConversationRef.subscribeMessages. This is much easier and more efficient.
Remember to call .unsubscribe on the subscription once you are done with it.
Parameters
Returns
talkSession.onError(handler): Subscription
Attaches a listener which gets called when the TalkSession encounters an unrecoverable error.
For example, if the session cannot authenticate, or if you specify an incorrect app ID.
If the session has already terminated, the handler will be called immediately.
Parameters
A callback that runs whenever the session terminates due to an error.
Returns
A subscription object. Call Subscription.unsubscribe() to detach the listener.
talkSession.uploadFile(data, metadata): Promise<FileToken>
Upload a generic file without any additional metadata.
This function does not send any message, it only uploads the file and returns a file token. To send the file in a message, pass the file token in a SendFileBlock when calling ConversationRef.send.
See the documentation for more information about sending files in messages.
If the file is a video, image, audio file, or voice recording, use one of the other functions like uploadImage instead.
Parameters
The binary file data. Usually a File.
Information about the file
Returns
A file token that can be used to send the file in a message.
talkSession.uploadImage(data, metadata): Promise<FileToken>
Upload an image with image-specific metadata.
This is a variant of uploadFile used for images.
Parameters
The binary image data. Usually a File.
Information about the image.
interface ImageFileMetadata
Returns
A file token that can be used to send the image in a message.
talkSession.uploadVideo(data, metadata): Promise<FileToken>
Upload a video with video-specific metadata.
This is a variant of uploadFile used for videos.
Parameters
The binary video data. Usually a File.
Information about the video.
interface VideoFileMetadata
Returns
A file token that can be used to send the video in a message.
talkSession.uploadAudio(data, metadata): Promise<FileToken>
Upload an audio file with audio-specific metadata.
This is a variant of uploadFile used for audio files.
Parameters
The binary audio data. Usually a File.
Information about the audio file.
interface AudioFileMetadata
Returns
A file token that can be used to send the audio file in a message.
talkSession.uploadVoice(data, metadata): Promise<FileToken>
Upload a voice recording with voice-specific metadata.
This is a variant of uploadFile used for voice recordings.
Parameters
The binary audio data. Usually a File.
Information about the voice recording.
interface VoiceRecordingFileMetadata
Returns
A file token that can be used to send the audio file in a message.
When you initially call getTalkSession, it will not open a connection to TalkJS immediately.
Instead, the session will wait for you to request some data, before connecting.
Then, during periods of inactivity, the session will automatically disconnect temporarily.
Make sure to unsubscribe any subscriptions when they are no longer needed. An active subscription will prevent the session from disconnecting, and will force the session to hold onto cached data unnecessarily.