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.

Create a session

The getTalkSession function returns a TalkSession object for a given app ID and user ID:

1import { getTalkSession } from '@talkjs/core';
2
3const session = getTalkSession({
4 appId: '<APP_ID>',
5 userId: '<USER_ID>',
6});

The following options are available when calling getTalkSession:

NameTypeDescription
appId
Required
stringYour app's unique TalkJS ID. Get it from the Settings page of the dashboard.
userId
Required
stringThe 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.

NameTypeDescription
token
Deprecated
stringDeprecated: 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.

class TalkSession

The session returned by getTalkSession.

Method Overview

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.

Properties

FieldTypeDescription
currentUserUserRefA read-only reference to the user whose ID you passed to getTalkSession.
onNeedToken
(Mutable)
() => voidA 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.

setToken

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

text
: string

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};

user

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

id
: string

The ID of the user that you want to reference

Returns

UserRef

A UserRef for the user with that ID

Usage

Example 1
Initialising a user
1const userRef = session.user("test");
2userRef.createIfNotExists({ name: "Alice" });
Example 2
Subscribing to changes
1const userRef = session.user("test");
2const userSub = userRef.subscribe(snapshot => console.log(snapshot));
3
4// Changing the user's name emits a snapshot and triggers the `console.log`
5await userRef.set({ name: "Bob" });

conversation

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

id
: string

The ID of the conversation that you want to reference

Returns

ConversationRef

A ConversationRef for the conversation with that ID

Usage

Example 1
Ensure that the conversation exists and you are a participant
1session.conversation("test").createIfNotExists();
Example 2
Set the conversation's subject
1session.conversation("test").set({ subject: "Power tools" });
Example 3
Stop receiving notifications for this conversation
1session.conversation("test").set({ notify: false });
Example 4
Send a message
1session.conversation("test").send("Hello");

subscribeConversations

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

onSnapshot (optional)
: ( snapshot: ConversationSnapshot[], loadedAll: boolean ) => void

Returns

ConversationListSubscription

onError

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

handler
: (error: Error) => void

A callback that runs whenever the session terminates due to an error.

Returns

A subscription object. Call Subscription.unsubscribe() to detach the listener.

uploadFile

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

data
: Blob

The binary file data. Usually a File.

Information about the file

interface GenericFileMetadata
filename
: string

The name of the file including extension.

Returns

Promise<FileToken>

A file token that can be used to send the file in a message.

uploadImage

talkSession.uploadImage(data, metadata): Promise<FileToken>

Upload an image with image-specific metadata.

This is a variant of uploadFile used for images.

Parameters

data
: Blob

The binary image data. Usually a File.

Information about the image.

interface ImageFileMetadata
filename
: string

The name of the file including extension.

height (optional)
: number

The height of the image in pixels, if known.

width (optional)
: number

The width of the image in pixels, if known.

Returns

Promise<FileToken>

A file token that can be used to send the image in a message.

uploadVideo

talkSession.uploadVideo(data, metadata): Promise<FileToken>

Upload a video with video-specific metadata.

This is a variant of uploadFile used for videos.

Parameters

data
: Blob

The binary video data. Usually a File.

Information about the video.

interface VideoFileMetadata
filename
: string

The name of the file including extension.

duration (optional)
: number

The duration of the video in seconds, if known.

height (optional)
: number

The height of the video in pixels, if known.

width (optional)
: number

The width of the video in pixels, if known.

Returns

Promise<FileToken>

A file token that can be used to send the video in a message.

uploadAudio

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

data
: Blob

The binary audio data. Usually a File.

Information about the audio file.

interface AudioFileMetadata
filename
: string

The name of the file including extension.

duration (optional)
: number

The duration of the audio file in seconds, if known.

Returns

Promise<FileToken>

A file token that can be used to send the audio file in a message.

uploadVoice

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

data
: Blob

The binary audio data. Usually a File.

Information about the voice recording.

interface VoiceRecordingFileMetadata
filename
: string

The name of the file including extension.

duration (optional)
: number

The duration of the recording in seconds, if known.

Returns

Promise<FileToken>

A file token that can be used to send the audio file in a message.

Automatic cleanup

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.