---
url: https://talkjs.com/docs/Data_APIs/JavaScript/TalkSession
---

# TalkSession

Ask a question Copy for LLM [View as Markdown](/docs/Data_APIs/JavaScript/TalkSession.md)

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`](https://www.npmjs.com/package/@talkjs/core).

If you use the JavaScript Data API as part of the Classic JavaScript SDK, [use `Session` instead](/docs/UI_Components/JavaScript/Classic/Session/#Session__conversation). 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:

```typescript
import { getTalkSession } from '@talkjs/core';

const session = getTalkSession({
  appId: '<APP_ID>',
  userId: '<USER_ID>',
});
```

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](/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](#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](#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](#TalkSession__setToken) | Set the auth token to be used on this session. |
| [user](#TalkSession__user) | Get a reference to a user. |
| [conversation](#TalkSession__conversation) | Get a reference to a conversation. |
| [subscribeConversations](#TalkSession__subscribeConversations) | Subscribe to your most recently active conversations. |
| [searchConversations](#TalkSession__searchConversations) | Search all of your conversations for a string. |
| [searchMessages](#TalkSession__searchMessages) | Search all of your messages for a string. |
| [onError](#TalkSession__onError) | Attach a listener for fatal errors. |
| [uploadFile](#TalkSession__uploadFile) | Upload a generic file without any additional metadata. |
| [uploadImage](#TalkSession__uploadImage) | Upload an image with image-specific metadata. |
| [uploadVideo](#TalkSession__uploadVideo) | Upload a video with video-specific metadata. |
| [uploadAudio](#TalkSession__uploadAudio) | Upload an audio file with audio-specific metadata. |
| [uploadVoice](#TalkSession__uploadVoice) | Upload a voice recording with voice-specific metadata. |

## Properties

| Field | Type | Description |
| --- | --- | --- |
| **appId** | `string` | The unique TalkJS ID that you passed when calling `getTalkSession` |
| **currentUser** | [`UserRef`](/docs/JavaScript_Data_API/Users/#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](/docs/Features/Security/Advanced_Authentication/#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

```typescript
const session = getTalkSession({
  appId: '<APP_ID>',
  userId: '<USER_ID>',
});
session.setToken('...');
```

**Example 2** Refreshable authentication

```typescript
const session = getTalkSession({
  appId: '<APP_ID>',
  userId: '<USER_ID>',
});
session.onNeedToken = async () => {
  const token = await fetchToken();
  session.setToken(token);
};
```

### user

*talkSession*. user (id): [UserRef](/docs/Data_APIs/JavaScript/Users/#UserRef)

Get a reference to a user.

The returned UserRef is part of the [Data API](/docs/JavaScript_Data_API/Users/), 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.

Calling this method multiple times with the same ID reuses the same [UserRef](/docs/Data_APIs/JavaScript/Users/#UserRef) object.

#### Parameters

##### id

: string

The ID of the user that you want to reference

#### Returns

[UserRef](/docs/Data_APIs/JavaScript/Users/#UserRef) A UserRef for the user with that ID

#### Usage

**Example 1**

Initialising a user

```ts
const userRef = session.user("test");
userRef.createIfNotExists({ name: "Alice" });
```

**Example 2**

Subscribing to changes

```ts
const userRef = session.user("test");
const userSub = userRef.subscribe(snapshot => console.log(snapshot));

// Changing the user's name emits a snapshot and triggers the `console.log`
await userRef.set({ name: "Bob" });
```

### conversation

*talkSession*. conversation (id): [ConversationRef](/docs/Data_APIs/JavaScript/Conversations/#ConversationRef)

Get a reference to a conversation.

The returned ConversationRef is part of the [Data API](/docs/JavaScript_Data_API/Conversations/), which is included in the Chat SDK. You can use references to get, edit, and subscribe to your data.

Calling this method multiple times with the same ID reuses the same [ConversationRef](/docs/Data_APIs/JavaScript/Conversations/#ConversationRef) object.

#### Parameters

##### id

: string

The ID of the conversation that you want to reference

#### Returns

[ConversationRef](/docs/Data_APIs/JavaScript/Conversations/#ConversationRef) A ConversationRef for the conversation with that ID

#### Usage

**Example 1**

Ensure that the conversation exists and you are a participant

```ts
session.conversation("test").createIfNotExists();
```

**Example 2**

Set the conversation's subject

```ts
session.conversation("test").set({ subject: "Power tools" });
```

**Example 3**

Stop receiving notifications for this conversation

```ts
session.conversation("test").set({ notify: false });
```

**Example 4**

Send a message

```ts
session.conversation("test").send("Hello");
```

### subscribeConversations

*talkSession*. subscribeConversations (onSnapshot): [ConversationListSubscription](/docs/Data_APIs/JavaScript/Conversations/#ConversationListSubscription)

*talkSession*. subscribeConversations (options, onSnapshot): [ConversationListSubscription](/docs/Data_APIs/JavaScript/Conversations/#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`.

You can optionally provide an `options` object as the first argument. If you provide `options` with a `filter`, only conversations matching the filter will be included in the snapshot. See [ConversationFilter](/docs/Data_APIs/JavaScript/Filters/#ConversationFilter) for more details on what filter options are supported. Note that this filter is part of the JS Data API - it is slightly different to the `ConversationPredicate` used in the classic JS SDK's `setFeedFilter`.

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](/docs/Data_APIs/JavaScript/Conversations/#ConversationSnapshot) [], loadedAll: boolean ) => void

##### options

: { filter?: [ConversationFilter](/docs/Data_APIs/JavaScript/Filters/#ConversationFilter) }

#### Returns

[ConversationListSubscription](/docs/Data_APIs/JavaScript/Conversations/#ConversationListSubscription)
#### Usage

**Example 1**

Subscribe to all your conversations and log them

```ts
session.subscribeConversations(snapshots => console.log(snapshots));
```

**Example 2**

Subscribe to conversations with a custom field

```ts
session.subscribeConversations({
  filter: { custom: { category: ["==", "support"] } }
}, onSnapshot);
```

**Example 3**

Subscribe to conversations with recent activity (last 7 days)

```ts
const sevenDaysAgo = Date.now() - 7 * 24 * 60 * 60 * 1000;
session.subscribeConversations({
  filter: { lastActivityAt: [">", sevenDaysAgo] }
}, onSnapshot);
```

### searchConversations

*talkSession*. searchConversations (onResults): [ConversationSearch](/docs/Data_APIs/JavaScript/Conversations/#ConversationSearch)

Creates a search for all the current user's conversations.

The search feature is available on the Growth plan or higher. On the Basic plan, this method will return an error.

Search is a two-step process. After calling `searchConversations`, call [ConversationSearch​.setQuery](/docs/Data_APIs/JavaScript/Conversations/#ConversationSearch__setQuery) to specify a search query and begin the search.

As search can be quite slow, there are two different ways of using search:

Option 1: Processing each search result as soon as it is received:

```ts
const search = session.searchConversations((results, status) => {
  console.log("Found a new conversation. All conversations found so far:", results);
});
search.setQuery("Hello");
```

Option 2: Wait until the full page is received (up to 60s delay) before processing:

```ts
const search = session.searchConversations();
const { results, loadedAll } = await search.setQuery("Hello");
console.log("Search completed, first page of conversations:", results);
```

#### Parameters

##### onResults

: ( results: [ConversationSnapshot](/docs/Data_APIs/JavaScript/Conversations/#ConversationSnapshot) [], status: "searching" | "canLoadMore" | "loadedAll" ) => void

Callback to run whenever we receive new results or the status changes. Status `searching` means we are actively searching for more conversations. `canLoadMore` means that the search is idle, but you can load older results with [ConversationSearch​.loadMore](/docs/Data_APIs/JavaScript/Conversations/#ConversationSearch__loadMore). `loadedAll` means that there are no more conversations to load.

#### Returns

[ConversationSearch](/docs/Data_APIs/JavaScript/Conversations/#ConversationSearch) A [ConversationSearch](/docs/Data_APIs/JavaScript/Conversations/#ConversationSearch). Call [ConversationSearch​.setQuery](/docs/Data_APIs/JavaScript/Conversations/#ConversationSearch__setQuery) to specify the string to search for, and begin receiving results.

#### Usage

**Example**

Basic UI integration (search-on-keypress)

```ts
const search = session.searchConversations((results, status) => {
  render(results, status);
});

const searchInput = document.querySelector("#searchInput");
searchInput.addEventListener("change", () => {
  search.setQuery(searchInput.value);
});
```

### searchMessages

*talkSession*. searchMessages (onResults): [MessageSearch](/docs/Data_APIs/JavaScript/Messages/#MessageSearch)

Creates a search for messages in all the current user's conversations.

The search feature is available on the Growth plan or higher. On the Basic plan, this method will return an error.

Search is a two-step process. After calling `searchMessages`, call [MessageSearch​.setQuery](/docs/Data_APIs/JavaScript/Messages/#MessageSearch__setQuery) to specify a search query and begin the search.

As search can be quite slow, there are two different ways of using search:

Option 1: Processing each search result as soon as it is received:

```ts
const search = session.searchMessages((results, status) => {
  console.log("Found a new message. All messages found so far:", results);
});
search.setQuery("Hello");
```

Option 2: Wait until the full page is received (up to 60s delay) before processing:

```ts
const search = session.searchMessages();
const { results, loadedAll } = await search.setQuery("Hello");
console.log("Search completed, first page of messages:", results);
```

#### Parameters

##### onResults

: ( results: [SearchMessageSnapshot](/docs/Data_APIs/JavaScript/Messages/#SearchMessageSnapshot) [], status: "searching" | "canLoadMore" | "loadedAll" ) => void

Callback to run whenever we receive new results or the status changes. Status `searching` means we are actively searching for more messages. `canLoadMore` means that the search is idle, but you can load older results with [MessageSearch​.loadMore](/docs/Data_APIs/JavaScript/Messages/#MessageSearch__loadMore). `loadedAll` means that there are no more messages to load.

#### Returns

[MessageSearch](/docs/Data_APIs/JavaScript/Messages/#MessageSearch) A search object. Call [MessageSearch​.setQuery](/docs/Data_APIs/JavaScript/Messages/#MessageSearch__setQuery) to specify the string to search for, and begin receiving results.

#### Usage

**Example**

Basic UI integration (search-on-keypress)

```ts
const search = session.searchMessages((results, status) => {
  render(results, status);
});

const searchInput = document.querySelector("#searchInput");
searchInput.addEventListener("change", () => {
  search.setQuery(searchInput.value);
});
```

### 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](/docs/Data_APIs/JavaScript/Message_Content/#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](/docs/Data_APIs/JavaScript/Message_Content/#SendFileBlock) when calling [ConversationRef​.send](/docs/Data_APIs/JavaScript/Conversations/#ConversationRef__send).

[See the documentation](/docs/Concepts/Message_Content/#sending-message-content) 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](https://developer.mozilla.org/en-US/docs/Web/API/File).

##### metadata

: [GenericFileMetadata](/docs/Data_APIs/JavaScript/TalkSession/#GenericFileMetadata)

Information about the file

##### interface GenericFileMetadata

##### filename

: string

The name of the file including extension.

#### Returns

Promise< [FileToken](/docs/Data_APIs/JavaScript/Message_Content/#FileToken) > A file token that can be used to send the file in a message.

### uploadImage

*talkSession*. uploadImage (data, metadata): Promise< [FileToken](/docs/Data_APIs/JavaScript/Message_Content/#FileToken) >

Upload an image with image-specific metadata.

This is a variant of [uploadFile](/docs/Data_APIs/JavaScript/TalkSession/#Session__uploadFile) used for images.

#### Parameters

##### data

: Blob

The binary image data. Usually a [File](https://developer.mozilla.org/en-US/docs/Web/API/File).

##### metadata

: [ImageFileMetadata](/docs/Data_APIs/JavaScript/TalkSession/#ImageFileMetadata)

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](/docs/Data_APIs/JavaScript/Message_Content/#FileToken) > A file token that can be used to send the image in a message.

### uploadVideo

*talkSession*. uploadVideo (data, metadata): Promise< [FileToken](/docs/Data_APIs/JavaScript/Message_Content/#FileToken) >

Upload a video with video-specific metadata.

This is a variant of [uploadFile](/docs/Data_APIs/JavaScript/TalkSession/#Session__uploadFile) used for videos.

#### Parameters

##### data

: Blob

The binary video data. Usually a [File](https://developer.mozilla.org/en-US/docs/Web/API/File).

##### metadata

: [VideoFileMetadata](/docs/Data_APIs/JavaScript/TalkSession/#VideoFileMetadata)

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](/docs/Data_APIs/JavaScript/Message_Content/#FileToken) > A file token that can be used to send the video in a message.

### uploadAudio

*talkSession*. uploadAudio (data, metadata): Promise< [FileToken](/docs/Data_APIs/JavaScript/Message_Content/#FileToken) >

Upload an audio file with audio-specific metadata.

This is a variant of [uploadFile](/docs/Data_APIs/JavaScript/TalkSession/#Session__uploadFile) used for audio files.

#### Parameters

##### data

: Blob

The binary audio data. Usually a [File](https://developer.mozilla.org/en-US/docs/Web/API/File).

##### metadata

: [AudioFileMetadata](/docs/Data_APIs/JavaScript/TalkSession/#AudioFileMetadata)

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](/docs/Data_APIs/JavaScript/Message_Content/#FileToken) > A file token that can be used to send the audio file in a message.

### uploadVoice

*talkSession*. uploadVoice (data, metadata): Promise< [FileToken](/docs/Data_APIs/JavaScript/Message_Content/#FileToken) >

Upload a voice recording with voice-specific metadata.

This is a variant of [uploadFile](/docs/Data_APIs/JavaScript/TalkSession/#Session__uploadFile) used for voice recordings.

#### Parameters

##### data

: Blob

The binary audio data. Usually a [File](https://developer.mozilla.org/en-US/docs/Web/API/File).

##### metadata

: [VoiceRecordingFileMetadata](/docs/Data_APIs/JavaScript/TalkSession/#VoiceRecordingFileMetadata)

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](/docs/Data_APIs/JavaScript/Message_Content/#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.