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.
To make the most of this tutorial, you need:
- A TalkJS account
- A basic understanding of Svelte
- A Svelte app to add TalkJS to. If you don’t have an existing Svelte app yet, follow these steps to create one.
To get started, install TalkJS in your Svelte app:
1npm install talkjs --save
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.svelte2<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.svelte2<script>3 import Talk from 'talkjs';4</script>56<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>56<main>7 <Chat />8</main>
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';56 onMount(async () => {7 Talk.ready.then(function () {8 const session = new Talk.Session({9 appId: '<APP_ID>',10 userId: 'sample_user_alice',11 });1213 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 settingme
to be an existing user, thesample_user_alice
sample user. For a user that already exists, we can call theTalk.User
constructor with just their user ID.
- Then you create the chat UI. Call the
createChatbox
method for a chatbox,createInbox
for an inbox, orcreatePopup
for a popup UI. Use theselect
method to display the sample conversation, and then use themount
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:
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.
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',10 photoUrl: 'https://talkjs.com/new-web/avatar-7.jpg',11 welcomeMessage: 'Hi!',12 });1314 const conversationRef = session.conversation('new_conversation');15 conversationRef.createIfNotExists();1617 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',10 photoUrl: 'https://talkjs.com/new-web/avatar-7.jpg',11 welcomeMessage: 'Hi!',12 });1314 const otherRef = session.user('frank');15 otherRef.createIfNotExists({16 name: 'Frank',18 photoUrl: 'https://talkjs.com/new-web/avatar-8.jpg',19 welcomeMessage: 'Hey, how can I help?',20 });2122 const conversationRef = session.conversation('new_conversation');23 conversationRef.createIfNotExists();24 conversationRef.participant(otherRef).createIfNotExists();2526 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:
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.
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.
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';56 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',15 photoUrl: 'https://talkjs.com/new-web/avatar-7.jpg',16 welcomeMessage: 'Hi!',17 });1819 const otherRef = session.user('frank');20 otherRef.createIfNotExists({21 name: 'Frank',23 photoUrl: 'https://talkjs.com/new-web/avatar-8.jpg',24 welcomeMessage: 'Hey, how can I help?',25 });2627 const conversationRef = session.conversation('new_conversation');28 conversationRef.createIfNotExists();29 conversationRef.participant(otherRef).createIfNotExists();3031 const chatbox = session.createChatbox();32 chatbox.select(conversationRef);33 chatbox.mount(document.getElementById('talkjs-container'));34 });35 });36</script>3738<div id="talkjs-container" style="height: 600px">Loading chats..</div>