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---
title: Connect to Realtime Data
description: This guide will cover connecting to Directus via WebSockets on the web, subscribing to changes, and creating new items over the connection.
navigation:
title: Connect to Realtime Data
---
:video-embed{video-id="4d3c062f-0f30-41b7-83e9-3d2ed34a86f4"}
Instead of needing to make a request to see if data has changed, your application can receive updates in realtime over a persistent connection with Directus. All subscriptions and actions over a realtime connection use the permissions of the authenticated user, or public permissions if not authenticated.
This guide will cover getting started with :product-link{product="realtime"} by connecting to Directus with the Directus SDK on the web, subscribing to changes, and creating new items.
## Before You Start
You will need a Directus project.
:cta-cloud
Create a `messages` collection with a `date_created` field enabled on collection creation. Add `text` and `user` text fields. Follow the [data modeling quickstart](/getting-started/data-model) to learn more.
Add an [access policy](/guides/auth/access-control) called **Public Posts** to your user in the Data Studio. Within it, create a new permission to allow the `read` and `create` actions on the `messages` collection.
In the Data Studio, create a [static token](/guides/auth/tokens-cookies) for your user, copy it, and save your user profile.
## Enable Realtime
Directus Realtime is disabled by default on self-hosted projects. Set the `WEBSOCKETS_ENABLED` environment variable to `true`. If you use Directus Cloud to host your project, you do not need to manually enable Realtime.
## Connect via Directus Realtime
Create an `index.html` file, import the Directus SDK from a CDN, create a client with the `realtime` composable, and connect. Be sure to replace your Directus project URL and access token.
```html
<!doctype html>
<html>
<body>
<script>
import { createDirectus, staticToken, realtime } from 'https://www.unpkg.com/@directus/sdk/dist/index.js';
const directus = createDirectus('https://example.directus.app')
.with(staticToken('your_access_token'))
.with(realtime());
await directus.connect();
</script>
</body>
</html>
```
## Subscribe to Changes
After subscribing to collections over your connection, you will receive new messages whenever items in the collection are created, updated, or deleted.
At the bottom of your `<script>`, create a new subscripion:
```js
const { subscription } = await directus.subscribe('messages', {
event: 'create',
query: { fields: ['user', 'text'] },
});
for await (const item of subscription) {
console.log(item);
}
```
Your page will log on the console every time an item is created in the `messages` collection.
## Create an Item
You can also perform actions over an open Realtime connection. Create a new function that sends a message over the connection to create an item:
```js
function createItem(text, user) {
directus.sendMessage({
type: 'items',
collection: 'messages',
action: 'create',
data: { text, user },
});
}
```
Open your browser and create items by using your new function directly in the console:
```js
createItem('Hello World!', 'Ben');
createItem('Hello Universe!', 'Rijk');
createItem('Hello Everyone Everywhere All At Once!', 'Kevin');
```
## Log Messages
Use the `directus.onWebSocket()` method to listen for events that happen to the WebSocket collection.
```js
directus.onWebSocket('open', function () {
console.log('Connection is open');
});
directus.onWebSocket('message', function (message) {
console.log('New message of type ' + message.type);
console.log(message.data);
});
directus.onWebSocket('close', function () {
console.log('Connection has closed');
});
directus.onWebSocket('error', function (error) {
console.log('Connection has had an error');
console.log(error);
});
```
## Next Steps
Learn more about [authenticating realtime connections](/guides/realtime/authentication) and [how to manage subscriptions](/guides/realtime/subscriptions).