1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471---
slug: build-a-realtime-chat-app-with-directus-and-sveltekit
title: Build a Realtime Chat App with Directus and SvelteKit
technologies:
- sveltekit
authors:
- name: Temitope Oyedelde
title: Guest Author
description: Learn how to setup Directus realtime with SvelteKit.
---
Directus offers real-time capabilities powered by WebSockets. You can use these with the Directus SDK to create your own real-time applications. In this tutorial, you will build a chat application using SvelteKit and a Directus project.
## Before You Start
You will need:
- A Directus project with admin access.
- Fundamental understanding of Svelte concepts.
- Optional but recommended: Familiarity with data modeling in Directus.
## Set Up Your Directus Project
## Configure Cors and WebSocket
You also need to configure CORS and WebSocket. Update your `docker-compose.yml` file as follows:
```bash
WEBSOCKETS_ENABLED: "true"
CORS_ENABLED: "true"
CORS_ORIGIN: "http://localhost:5173"
CORS_CREDENTIALS: "true"
```
### Create a Collection
Create a new collection called `messages` with the following fields:
- `content` (Type: textarea)
After which, you can go to the optional fields and add the following:
- `user_created`
- `date_created`

### Edit Public Policy
Navigate to Settings -> Access Policies -> Public. Under `messages` grant full access for `create` and `read`.
## Set Up Your Sveltekit Project
### Initialize Your Project
To start building, you need to install SvelteKit and Directus sdk. Run this command to install SvelteKit:
```bash
npx sv create realtime-app
```
When prompted, select SvelteKit minimal as the template. Do not add type checking, as this tutorial is implemented in JavaScript. Your output should look like this:
```bash
Welcome to the Svelte CLI! (v0.6.16)
โ
โ Which template would you like?
โ SvelteKit minimal
โ
โ Add type checking with Typescript?
โ No
โ
โ Project created
โ
โ What would you like to add to your project? (use arrow keys / space bar)
โ none
โ
โ Which package manager do you want to install dependencies with?
โ npm
โ
โ Successfully installed dependencies
โ
โ Project next steps โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฎ
โ โ
โ 1: cd realtime-app โ
โ 2: git init && git add -A && git commit -m "Initial commit" (optional) โ
โ 3: npm run dev -- --open
```
Afterward, `cd` into your project directory and install the Directus SDK by running this command:
```bash
npm install @directus/sdk
```
You need to initialize Directus SDK in your project. Create a file called `directus.js` inside the `./src/lib` directory. Add the following code:
```javascript
import { createDirectus, authentication, realtime, rest } from "@directus/sdk";
const directusURL = "http://localhost:8055";
export const directus = createDirectus(directusURL)
.with(authentication())
.with(rest())
.with(realtime());
```
### Create a Login Form
Create a file called `+page.svelte` file in the `./src/route` directory. Add the following code:
```javascript
<script>
import { onMount, onDestroy } from "svelte";
import { directus } from "../lib/directus.js";
import { tick } from "svelte";
let email = "";
let password = "";
let loggedIn = false;
let messages = [];
let messageContent = "";
let websocketConnected = false;
let refreshToken = null;
let reconnectAttempts = 0;
let maxReconnectAttempts = 20;
let reconnectDelay = 2000;
async function login(event) {
event.preventDefault();
try {
const authResponse = await directus.login({ email, password }, {
mode: "json",
});
console.log("Login successful");
refreshToken = authResponse.refresh_token;
if (!refreshToken) {
throw new Error("No refresh token received from login.");
}
loggedIn = true;
await connectWebSocket();
} catch (error) {
console.error("Login failed:", error);
}
}
async function connectWebSocket() {
if (!loggedIn || websocketConnected) return;
try {
setupWebSocketEventHandlers();
await directus.connect();
websocketConnected = true;
console.log("WebSocket Connected");
const accessToken = await directus.getToken();
if (accessToken) {
await directus.sendMessage({
type: "auth",
access_token: accessToken,
});
} else if (refreshToken) {
await directus.sendMessage({
type: "auth",
refresh_token: refreshToken,
});
} else {
throw new Error("No authentication tokens available");
}
console.log("WebSocket Authenticated");
reconnectAttempts = 0;
reconnectDelay = 2000;
await directus.sendMessage({
type: "items",
collection: "messages",
action: "read",
query: {
limit: 100,
sort: "-date_created",
fields: ["id", "content", "user_created.first_name"],
},
uid: "get-recent-messages",
});
subscribeToMessages();
} catch (error) {
console.error("WebSocket connection failed:", error);
websocketConnected = false;
attemptReconnect();
}
}
onMount(async () => {
if (loggedIn) {
await connectWebSocket();
}
});
onDestroy(() => {
if (websocketConnected) {
directus.disconnect();
}
});
</script>
```
In the code above we use WebSocket authentication via [handshake mode](https://directus.io/docs/guides/realtime/authentication#handshake-mode) to connect to Directus in real-time. When the WebSocket starts, the app sends authentication details to stay connected. The authentication function handles login, stores tokens, loads recent messages, and reconnects automatically if the connection drops or authentication expires.
### Subscribe to Incoming Messages
Add the following code at the bottom of the `script` in your `./src/routes/+page.svelte`:
```javascript
async function subscribeToMessages() {
try {
const { subscription } = await directus.subscribe("messages", {
event: "create",
query: {
fields: ["id", "content", "user_created.first_name"],
},
});
for await (const event of subscription) {
receiveMessage(event);
}
} catch (error) {
console.error("Subscription error:", error);
if (websocketConnected) {
websocketConnected = false;
attemptReconnect();
}
}
}
```
The `subscribeToMessages()` function sets up a real-time listener for new messages in Directus using WebSocket subscriptions. It subscribes to the `messages` collection, requesting only the message ID, content, and senderโs first name while also including a [UID](https://directus.io/docs/guides/realtime/actions#use-uids-to-better-understand-responses) for [good practice](https://directus.io/docs/guides/realtime/subscriptions#using-uids)
This allows the app to match responses with specific requests, improving reliability when handling multiple subscriptions. As new messages arrive, the function processes each event in a loop and calls `receiveMessage(event)`, ensuring real-time updates in the app.
## Send Messages
To begin sending messages, add the following code at the bottom of the script in your `.src/routes/+page.svelte` file
```javascript
const sendMessage = async (event) => {
event.preventDefault();
if (!messageContent.trim() || !refreshToken) return;
try {
if (!websocketConnected) {
await connectWebSocket();
}
await directus.sendMessage({
type: "items",
collection: "messages",
action: "create",
data: { content: messageContent },
});
console.log("Message sent via WebSocket");
messageContent = "";
} catch (error) {
console.error("Failed to send message:", error);
if (!websocketConnected) {
attemptReconnect();
}
}
};
```
The `sendMessage` function handles sending a new message via WebSocket in Directus. It first prevents the default form submission behavior and checks if the message content is empty or if the user is not logged in, in which case it stops execution.
If the WebSocket is not connected, it attempts to reconnect before sending the message. It then sends the message as a create action in the "messages" collection using Directus' WebSocket API. If successful, it logs confirmation and clears the message input. If sending fails, it logs the error, and if the WebSocket is disconnected, a reconnection attempt is triggered.
## Fetching the Latest Messages On Load
Add the following code at the bottom of the `script` in your `./src/routes/+page.svelte`.:
```javascript
async function receiveMessage(newMessage) {
console.log("New message received with UID:", newMessage.uid, newMessage);
if (newMessage.data && Array.isArray(newMessage.data)) {
messages = [
...messages,
...newMessage.data.map((msg) => ({
id: msg.id,
content: msg.content,
user: msg.user_created?.first_name || "User",
})),
];
await tick();
}
}
```
The receiveMessage function processes incoming WebSocket messages and ensures they belong to the correct subscription by checking the UID before updating the app.
If valid, it extracts the message ID, content, and senderโs first name, then updates the message list.
## Display Incoming Messages
To display the messages, you need to add the UI templates for the chats. Right after the script tag in your `./src/routes/+page.svelte`, add the following code:
```javascript
<div class="container-center">
{#if !loggedIn}
<div class="card">
<h2>Login</h2>
<form on:submit="{login}">
<div class="form-group">
<label>Email</label>
<input type="email" bind:value="{email}" required />
</div>
<div class="form-group">
<label>Password</label>
<input type="password" bind:value="{password}" required />
</div>
<button type="submit">Login</button>
</form>
</div>
{:else}
<div class="chat-container">
<div class="chat-header">
Chat Room
<span
class="connection-status {websocketConnected ? 'connected' : 'disconnected'}"
>
{websocketConnected ? "โข Connected" : "โข Disconnected"}
</span>
</div>
<div class="chat-body">
<ul class="list-unstyled">
{#each messages as msg (msg.id)}
<li class="message {msg.user === 'You' ? 'user' : 'other'}">
<strong>{msg.user}</strong>: {msg.content}
</li>
{/each}
</ul>
</div>
<div class="chat-footer">
<form on:submit="{sendMessage}">
<input
type="text"
bind:value="{messageContent}"
placeholder="Type a message..."
required
disabled="{!websocketConnected}"
/>
<button type="submit" disabled="{!websocketConnected}">Send</button>
</form>
</div>
</div>
{/if}
</div>
```
This manages the login form and the real-time chat interface, switching between them based on the user's authentication status.
## Handling Connection Stability
Add the following code at the bottom of the `script` in your `./src/routes/+page.svelte`:
```javascript
function setupWebSocketEventHandlers() {
directus.onWebSocket("close", () => {
console.log("WebSocket connection closed");
websocketConnected = false;
if (refreshToken) {
attemptReconnect();
}
});
directus.onWebSocket("error", (error) => {
console.error("WebSocket error:", error);
websocketConnected = false;
});
directus.onWebSocket("message", async (message) => {
if (message.type === "ping") {
directus.sendMessage({ type: "pong" });
}
if (message.uid === "get-recent-messages") {
console.log("Received past messages:", message);
if (message.data && Array.isArray(message.data)) {
const pastMessages = [...message.data].reverse().map((msg) => ({
id: msg.id,
content: msg.content,
user: msg.user_created?.first_name || "User",
}));
messages = [...pastMessages, ...messages];
await tick();
}
}
if (message.type === "auth" && message.status === "expired") {
console.log("Authentication expired, re-authenticating...");
if (refreshToken) {
try {
await directus.sendMessage({
type: "auth",
refresh_token: refreshToken,
});
console.log("Re-authentication successful");
} catch (error) {
console.error("Re-authentication failed:", error);
attemptReconnect();
}
} else {
console.log("No refresh token available, cannot re-authenticate.");
attemptReconnect();
}
}
});
}
function attemptReconnect() {
if (reconnectAttempts >= maxReconnectAttempts) {
console.log("Max reconnect attempts reached. Please log in again.");
dispatch("connectionLost");
return;
}
reconnectAttempts++;
setTimeout(async () => {
if (!websocketConnected && refreshToken) {
try {
await directus.connect();
websocketConnected = true;
await directus.sendMessage({
type: "auth",
refresh_token: refreshToken,
});
console.log("Reconnected and authenticated successfully");
subscribeToMessages();
reconnectAttempts = 0;
reconnectDelay = 2000;
} catch (error) {
console.error("Reconnection failed:", error);
reconnectDelay = Math.min(reconnectDelay * 1.5, 30000);
attemptReconnect();
}
}
}, reconnectDelay);
}
```
The `setupWebSocketEventHandlers()` and `attemptReconnect()` functions ensures a stable WebSocket connection by handling authentication expiration and keeping the session alive respectively.
## Test the Application
To test the application, run this command:
```bash
npm run dev
```
Afterward, open **http://localhost:5173/** in your browser. You should see a login form displayed:

Next, you'll see an empty chat. Go to the Directus dashboard and create a new message in the 'Messages' collection. After that, you should see the message displayed in the chat box, as shown in the image below.

You can also interact with the chat box by sending new messages, as shown in the image below.

## Summary
In this tutorial, you built a real-time chat application using Directus, SvelteKit, and WebSockets. You can expand it by adding features like user presence indicators, typing notifications, or even file sharing.