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: Use 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: 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.

Properties

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

Methods

The TalkSession object has the following methods:

setToken

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

user

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;
4
5// Changing the user's name emits a snapshot and triggers the `console.log`
6await userRef.set({ name: 'Bob' });

conversation

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');

subscribeConversations

1subscribeConversations(
2 snapshot: ConversationSnapshot[], loadedAll: boolean) => void
3): 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.

onError

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.

Returns

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

uploadFile

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.

Parameters

NameTypeDescription
dataBlobThe binary file data. Usually a File.
metadataGenericFileMetadataInformation about the file, see below.

GenericFileMetadata

PropertyTypeDescription
filename RequiredstringThe name of the file, including the extension.

Returns

A promise that resolves to a FileToken that can be used to send the file in a message.

uploadImage

1uploadImage(data: Blob, metadata: ImageFileMetadata): Promise<FileToken>;

Uploads an image with image-specific metadata. This is a variant of uploadFile used for images.

Parameters

NameTypeDescription
dataBlobThe binary file data. Usually a File.
metadataImageFileMetadataInformation about the image, see below.

ImageFileMetadata

PropertyTypeDescription
filename RequiredstringThe name of the file, including the extension.
widthnumberThe width of the image in pixels, if known.
heightnumberThe height of the image in pixels, if known.

Returns

A promise that resolves to a FileToken that can be used to send the file in a message.

uploadVideo

1uploadVideo(data: Blob, metadata: VideoFileMetadata): Promise<FileToken>;

Uploads a video with video-specific metadata. This is a variant of uploadFile used for videos.

Parameters

NameTypeDescription
dataBlobThe binary file data. Usually a File.
metadataVideoFileMetadataInformation about the video, see below.

VideoFileMetadata

PropertyTypeDescription
filename RequiredstringThe name of the file, including the extension.
widthnumberThe width of the video in pixels, if known.
heightnumberThe height of the video in pixels, if known.
durationnumberThe duration of the video in seconds, if known.

Returns

A promise that resolves to a FileToken that can be used to send the file in a message.

uploadAudio

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.

Parameters

NameTypeDescription
dataBlobThe binary file data. Usually a File.
metadataAudioFileMetadataInformation about the audio file, see below.

AudioFileMetadata

PropertyTypeDescription
filename RequiredstringThe name of the file, including the extension.
durationnumberThe duration of the audio file in seconds, if known.

Returns

A promise that resolves to a FileToken that can be used to send the file in a message.

uploadVoice

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.

Parameters

NameTypeDescription
dataBlobThe binary file data. Usually a File.
metadataVoiceFileMetadataInformation about the audio file, see below.

VoiceFileMetadata

PropertyTypeDescription
filename RequiredstringThe name of the file, including the extension.
durationnumberThe duration of the voice recording in seconds, if known.
userRefUserRefA reference to the user that this session is connected as.

Returns

A promise that resolves to a FileToken that can be used to send the 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.