Svelte

This guide helps you add TalkJS to your Svelte app. It covers the core concepts of TalkJS, and introduces you to its JavaScript SDK.

In this guide we'll use SvelteKit, the official application framework recommended by the Svelte team. For an example of a basic Svelte app with TalkJS that doesn't use SvelteKit, see our TalkJS Svelte example GitHub repo.

Prerequisites

To make the most of this tutorial, you need:

  1. A TalkJS account
  2. A basic understanding of Svelte
  3. A Svelte app to add TalkJS to. If you don’t have an existing Svelte app yet, follow these steps to create one.

Install TalkJS

To get started, install TalkJS in your Svelte app:

1npm install talkjs --save

Create a chat component

The details of how and where you want to integrate TalkJS will depend on your app. For this example, create a /components/Chat.svelte component in your project. In this component, you can import TalkJS:

1// Chat.svelte
2<script>import Talk from 'talkjs';</script>

For either a chatbox or an inbox pre-built chat UI, also add a container element in which to load your chat:

1// Chat.svelte
2<script>
3 import Talk from 'talkjs';
4</script>
5
6<div id="talkjs-container" style="height: 600px">Loading chats..</div>

If you're adding a popup UI, you can omit this container, as the popup gets overlaid on top of your page. By default the popup displays in the bottom right corner, but you can change the position of the popup button on your page.

Next, import your new chat component. For this example, import the component into the top-level +page.svelte file:

1<!-- +page.svelte -->
2<script>
3 import Chat from '../components/Chat.svelte';
4</script>
5
6<main>
7 <Chat />
8</main>

View an existing conversation

You're now ready to view a conversation. Choose the tab for your preferred chat UI, and add the following code to your Chat.svelte component:

1<!-- Chat.svelte -->
2<script>
3 import Talk from 'talkjs';
4 import { onMount } from 'svelte';
5
6 onMount(async () => {
7 Talk.ready.then(function () {
8 const session = new Talk.Session({
9 appId: '<APP_ID>',
10 userId: 'sample_user_alice',
11 });
12
13 const chatbox = session.createChatbox();
14 chatbox.select('sample_conversation');
15 chatbox.mount(document.getElementById('talkjs-container'));
16 });
17 });
18</script>

Let's step through what this code is doing:

  • You make a connection to the TalkJS servers, known as a session. You'll need to replace <APP_ID> with your own app ID, which you can find on the Settings page of your TalkJS dashboard. For this tutorial, we recommend using the app ID for TalkJS's test mode, which has built-in sample users and conversations which we'll use in this tutorial. You'll also need to specify a current user to send messages as. In this example, you're setting me to be an existing user, the sample_user_alice sample user. For a user that already exists, we can call the Talk.User constructor with just their user ID.
  • Then you create the chat UI. Call the createChatbox method for a chatbox, createInbox for an inbox, or createPopup for a popup UI. Use the select method to display the sample conversation, and then use the mount method to render the UI. (The methods here are linked for the chatbox, but are also available on the inbox and popup UI.)

For example, for the chatbox UI, you should see something like the following:

Loading chat...

Try sending Sebastian a message! You can also try switching your user ID to sample_user_sebastian and viewing the other side of the conversation.

If you don't see the chat window, make sure that you entered your app ID, replacing <APP_ID> in the code.

Create new users and conversations

So far in this guide we've used a sample user and conversation. Next, we'll create new users and a conversation between them, and sync them with the TalkJS servers. Usually, you would create users based on the data from your database. For this getting started guide, we've hard-coded our user data instead.

First, let's add a new current user, Nina, and a new conversation. Update your code with the highlighted lines:

1onMount(async () => {
2 Talk.ready.then(function () {
3 const session = new Talk.Session({
4 appId: '<APP_ID>',
5 userId: 'nina',
6 });
7 session.currentUser.createIfNotExists({
8 name: 'Nina',
9 email: '[email protected]',
10 photoUrl: 'https://talkjs.com/new-web/avatar-7.jpg',
11 welcomeMessage: 'Hi!',
12 });
13
14 const conversationRef = session.conversation('new_conversation');
15 conversationRef.createIfNotExists();
16
17 const chatbox = session.createChatbox();
18 chatbox.select(conversationRef);
19 chatbox.mount(document.getElementById('talkjs-container'));
20 });
21});

Here you connect to TalkJS as a user with an ID of nina, and set initial user data if she does not yet exist. You then get a reference to a conversation with an ID of new_conversation, and set initial conversation data if it does not yet exist.

Next, create a second user, Frank, and add them to the conversation:

1onMount(async () => {
2 Talk.ready.then(function () {
3 const session = new Talk.Session({
4 appId: '<APP_ID>',
5 userId: 'nina',
6 });
7 session.currentUser.createIfNotExists({
8 name: 'Nina',
9 email: '[email protected]',
10 photoUrl: 'https://talkjs.com/new-web/avatar-7.jpg',
11 welcomeMessage: 'Hi!',
12 });
13
14 const otherRef = session.user('frank');
15 otherRef.createIfNotExists({
16 name: 'Frank',
17 email: '[email protected]',
18 photoUrl: 'https://talkjs.com/new-web/avatar-8.jpg',
19 welcomeMessage: 'Hey, how can I help?',
20 });
21
22 const conversationRef = session.conversation('new_conversation');
23 conversationRef.createIfNotExists();
24 conversationRef.participant(otherRef).createIfNotExists();
25
26 const chatbox = session.createChatbox();
27 chatbox.select(conversationRef);
28 chatbox.mount(document.getElementById('talkjs-container'));
29 });
30});

In this updated code, you get a reference to the other user, frank, and set initial user data if he does not yet exist. You then get a reference to the frank participant in the conversation, and create the participant if it does not already exist, adding frank to the conversation.

When you mount the UI, the new users and conversation are synced with the TalkJS servers.

You should now get something like the following:

Example chat with synced user and conversation

You can also create and sync users or conversations from your backend with the REST API. If you want to only sync users or conversations with the REST API, you can disable syncing in the browser. See Browser Synchronization for more details.

That's it! You now have a working chat component in your Svelte app.

Next steps

In this guide, you've added powerful user-to-user chat to your Svelte app. You also learned more about the fundamentals of TalkJS, and how it all fits together.

Most importantly, you've built a starting point to try out all the features TalkJS offers. For example, you could create a new UI theme in the Theme Editor, customize your chat with action buttons or HTML panels, or enable email notifications.

If you're planning to use reactive statements in Svelte, also check out a more advanced Svelte example.

Before you go live, make sure you enable authentication. Authentication keeps your user data secure, by ensuring that only legitimate users can connect to your chat. For details, see: Authentication.

Full code example

Here's what your working example should look like, in full:

1<!-- Chat.svelte -->
2<script>
3 import Talk from 'talkjs';
4 import { onMount } from 'svelte';
5
6 onMount(async () => {
7 Talk.ready.then(function () {
8 const session = new Talk.Session({
9 appId: '<APP_ID>',
10 userId: 'nina',
11 });
12 session.currentUser.createIfNotExists({
13 name: 'Nina',
14 email: '[email protected]',
15 photoUrl: 'https://talkjs.com/new-web/avatar-7.jpg',
16 welcomeMessage: 'Hi!',
17 });
18
19 const otherRef = session.user('frank');
20 otherRef.createIfNotExists({
21 name: 'Frank',
22 email: '[email protected]',
23 photoUrl: 'https://talkjs.com/new-web/avatar-8.jpg',
24 welcomeMessage: 'Hey, how can I help?',
25 });
26
27 const conversationRef = session.conversation('new_conversation');
28 conversationRef.createIfNotExists();
29 conversationRef.participant(otherRef).createIfNotExists();
30
31 const chatbox = session.createChatbox();
32 chatbox.select(conversationRef);
33 chatbox.mount(document.getElementById('talkjs-container'));
34 });
35 });
36</script>
37
38<div id="talkjs-container" style="height: 600px">Loading chats..</div>