Session

The Session component represents a user's active TalkJS session. It handles authenticating your app with TalkJS. You need to ensure that your users can only have a TalkJS session when they have a valid session in your app.

The Session component can be used by itself or with the Chatbox, Inbox or Popup components as its descendants. If you use a Chatbox, Inbox or Popup then it must be a descendant of Session. It, however, does not need to be a direct descendant.

The session encapsulates a connection to the TalkJS realtime infrastructure, and this connection will live as long as the session component is mounted. If you want to listen for events or show desktop notifications for new messages, we recommend putting the session at the top of your component hierarchy, so that it is active even when no chat UI is being shown.

Props

NameTypeDescription
appId Required
stringYour app's unique TalkJS ID. Get it from the Settings page of the dashboard.
syncUser
Talk.User | () => Talk.UserRequired unless userId is provided.

A Talk.User object or a function returning a Talk.User object that identifies the currently active user.
userId
stringRequired unless syncUser is provided.

The id of the currently active user.
desktopNotificationsEnabled
booleanDetermines whether desktop notifications will be sent to the device the user is currently using.
sessionRef
React.MutableRefObject<Talk.Session>A React mutable ref object that holds the current TalkJS session object. See an example of how to use sessionRef in your application.
token
stringA token to authenticate the session with. Pass token if you use standard (non-refreshable) authentication.
tokenFetcher
() => Promise<string>A callback that fetches a new token from your backend and returns it. Pass tokenFetcher if you use authentication with refreshable tokens.
signature Deprecated
stringThe HMAC-SHA256 hash of the current user id, signed with your TalkJS secret key. Pass signature if you use legacy signature-based authentication.

Events

You can pass all events (methods with names starting with on) accepted by Talk.Session to the Session component as props with the same name.

You can pass the Unreads.onChange event to the session as the onUnreadsChange prop.

See below for an example.

Examples

This section gives some examples that demonstrate how to use the Session component.

You'll need to replace <APP_ID> with your TalkJS App ID. You can find your App ID in the Settings tab of the TalkJS dashboard.

Create a session with an existing user

Create a session for an existing user with the userId prop:

1import { Session } from '@talkjs/react';
2
3<Session appId={'<APP_ID>'} userId="pete">
4 {/* your main app here */}
5</Session>;

Create a session and sync a user

Create or update user data with the syncUser prop. This prop expects a callback that uses the regular TalkJS JavaScript SDK to create a Talk.User object:

1import { useCallback } from 'react';
2import { Session } from '@talkjs/react';
3import Talk from 'talkjs';
4
5// ...
6
7const syncUser = useCallback(
8 () =>
9 // regular TalkJS JavaScript code here
10 new Talk.User({
11 id: 'pete',
12 name: 'Pete',
13 photoUrl: 'https://example.com/pete.jpg',
14 // ...
15 }),
16 []
17);
18
19<Session appId={'<APP_ID>'} syncUser={syncUser}>
20 {/* your main app here */}
21</Session>;

Reference a session

To reference a session outside the Session component, assign the underlying Talk.Session object to a ref:

1import { useRef, useCallback } from 'react';
2import { Session } from '@talkjs/react';
3
4const session = useRef<Talk.Session>();
5
6// ...
7
8const onSomeEvent = useCallback(async () => {
9 // do something with the session.
10 if (session.current?.isAlive) {
11 const inboxes = await session.current.getInboxes();
12 }
13}, []);
14
15<Session appId={'<APP_ID>'} userId="pete" sessionRef={session}>
16 {/* your main app here */}
17</Session>;

The ref will be set once the Talk.Session object has initialized, and it will be set back to undefined once it has been destroyed.

Make sure you always check the isAlive property to ensure that the object is not destroyed, because React is prone to trigger race conditions here (especially when React.StrictMode is enabled or when using a development setup with hot reloading, both of which cause a lot of destroying).

Respond to events

Respond to events (in this case, new messages and changes in the number of unread message) by printing details to the console:

1import { Session } from '@talkjs/react';
2
3// ...
4
5<Session
6 appId={'<APP_ID>'}
7 userId="pete"
8 onMessage={(message) => console.log(message.body)}
9 onUnreadsChange={(unreads) => console.log(unreads.length)}
10>
11 {/* your main app here */}
12</Session>;