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 | string | Your app's unique TalkJS ID. Get it from the Settings page of the dashboard. |
| userId | 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 |
|---|---|---|
string | Deprecated: Use TalkSession.setToken instead. A token to authenticate the session with. Ignored if a TalkSession object already exists for this appId + userId. | |
() => Promise<string> | Deprecated: Use 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. |
| Field | Type | Description |
|---|---|---|
| currentUser | UserRef | A read-only reference to the user whose ID you passed to getTalkSession. |
| onNeedToken | () => 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. |
The TalkSession object has the following methods:
1setToken(token: string): 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.
Example Non-refreshable authentication
1const session = getTalkSession({2 appId: '<APP_ID>',3 userId: '<USER_ID>',4});5session.setToken('...');
Example 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};
1user(id: string): UserRef;
Returns a reference to the user with the specified ID.
This is the entry-point for all operations that affect a user globally, such as editing their name.
For operations related to a user's participation in a conversation, do: session.conversation(<convId>).participant(<userId>).
Example Initialising a user
1const userRef = session.user('<USER_ID>');2userRef.createIfNotExists({ name: 'Alice' });
Example Subscribing to changes
1const userRef = session.user('<USER_ID>');2const sub = userRef.subscribe((snapshot) => console.log(snapshot));3await sub.connected;45// Changing the user's name emits a snapshot and triggers the `console.log`6await userRef.set({ name: 'Bob' });
1conversation(id: string): ConversationRef;
Returns a reference to the conversation with the specified ID.
This is the entry-point for all conversation-related operations. This includes operations affecting conversation attributes, but also anything related to messages and participants.
Example Ensure that the conversation exists and you are a participant
1session.conversation('<CONV_ID>').createIfNotExists();
Example Set the conversation's subject
1session.conversation('<CONV_ID>').set({ subject: 'Power tools' });
Example Send a message
1session.conversation('<CONV_ID>').send('Hello');
1subscribeConversations(2 snapshot: ConversationSnapshot[], loadedAll: boolean) => void3): ConversationListSubscription;
Subscribes to your most recently active conversations.
The subscription is 'windowed'. Initially, this window contains the 20 most recent conversations.
Conversations are ordered by last activity. The last activity of a conversation is either joinedAt or lastMessage.createdAt, whichever is higher.
If an older conversation receives a new message, or you are added to a conversation, it will appear at the start of the list.
Call loadMore to load additional older conversations.
Whenever Subscription.state.type is "active" and something changes in your conversations, onSnapshot will fire and Subscription.state.latestSnapshot will be updated.
loadedAll is true when the snapshot contains all your conversations.
If the current user does not exist yet, the snapshot will be an empty list.
Returns a ConversationListSubscription.
1onError(handler: (error: Error) => void): 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.
A subscription object. Call Subscription.unsubscribe() to detach the listener.
1uploadFile(data: Blob, metadata: GenericFileMetadata): Promise<FileToken>;
Uploads 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 you call 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.
| Name | Type | Description |
|---|---|---|
| data | Blob | The binary file data. Usually a File. |
| metadata | GenericFileMetadata | Information about the file, see below. |
| Property | Type | Description |
|---|---|---|
| filename | string | The name of the file, including the extension. |
A promise that resolves to a FileToken that can be used to send the file in a message.
1uploadImage(data: Blob, metadata: ImageFileMetadata): Promise<FileToken>;
Uploads an image with image-specific metadata. This is a variant of uploadFile used for images.
| Name | Type | Description |
|---|---|---|
| data | Blob | The binary file data. Usually a File. |
| metadata | ImageFileMetadata | Information about the image, see below. |
| Property | Type | Description |
|---|---|---|
| filename | string | The name of the file, including the extension. |
| width | number | The width of the image in pixels, if known. |
| height | number | The height of the image in pixels, if known. |
A promise that resolves to a FileToken that can be used to send the file in a message.
1uploadVideo(data: Blob, metadata: VideoFileMetadata): Promise<FileToken>;
Uploads a video with video-specific metadata. This is a variant of uploadFile used for videos.
| Name | Type | Description |
|---|---|---|
| data | Blob | The binary file data. Usually a File. |
| metadata | VideoFileMetadata | Information about the video, see below. |
| Property | Type | Description |
|---|---|---|
| filename | string | The name of the file, including the extension. |
| width | number | The width of the video in pixels, if known. |
| height | number | The height of the video in pixels, if known. |
| duration | number | The duration of the video in seconds, if known. |
A promise that resolves to a FileToken that can be used to send the file in a message.
1uploadAudio(data: Blob, metadata: AudioFileMetadata): Promise<FileToken>;
Uploads an audio file with audio-specific metadata. This is a variant of uploadFile used for audio files.
| Name | Type | Description |
|---|---|---|
| data | Blob | The binary file data. Usually a File. |
| metadata | AudioFileMetadata | Information about the audio file, see below. |
| Property | Type | Description |
|---|---|---|
| filename | string | The name of the file, including the extension. |
| duration | number | The duration of the audio file in seconds, if known. |
A promise that resolves to a FileToken that can be used to send the file in a message.
1uploadVoice(data: Blob, metadata: VoiceFileMetadata): Promise<FileToken>;
Uploads a voice recording with voice-specific metadata. This is a variant of uploadFile used for voice recordings.
| Name | Type | Description |
|---|---|---|
| data | Blob | The binary file data. Usually a File. |
| metadata | VoiceFileMetadata | Information about the audio file, see below. |
| Property | Type | Description |
|---|---|---|
| filename | string | The name of the file, including the extension. |
| duration | number | The duration of the voice recording in seconds, if known. |
| userRef | UserRef | A reference to the user that this session is connected as. |
A promise that resolves to a FileToken that can be used to send the 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.