In this short tutorial, you'll learn how to quickly add real time data to your application or project using WebSockets and Directus Realtime. Follow along with Bryant as he covers the three easy steps to get started with WebSockets.
Speaker 0: Hi, Bryant here for Directus. In this quick tutorial, I'm gonna show you just how easy it is to add real time data to your project with Directus Real Time using WebSockets. With Directus, adding real time data to your project takes just 3 easy steps. Number 1, connect. Number 2, authenticate.
And number 3, subscribe. Let's work through each of these 3 steps together in a sample project. Okay. So in our sample project, you can see I've already spec'd out a couple different variables. Our URL for our WebSocket connection, our Directus instance, we've got an access token for authentication, And we have a collection for messages.
You'll also need a Directus project up and running to make this work. So if we open this and go to the data model settings, you can see I've got a single messages collection with a user field for our user, a date created timestamp, and a text area field called text for the actual text of the message. Step number 1 is as simple as opening a connection using the WebSocket protocol. So we'll define a new connection and then we're also going to drop in a couple of event handlers just so we can actually get some feedback through the console whenever we are opening a connection or whenever we receive a message through this connection. Step 2 is authentication.
So whenever you open a new connection, you'll have to send an authentication request before the connection times out. To do that, we are going to send a new message within the open event listener. So connection dot send, we're gonna stringify the JSON body with a type of auth. We're passing that access token that we already previously generated. The last step is actually subscribing to updates from a collection.
So here, we're just gonna drop in a new subscribe method that subscribes to the messages collection. So if we open up our file now, we can test this out. We can see that the auth message is being received, that the connection is open and authenticated, but the next step is to actually subscribe to the messages collection. So just gonna call that right here within the console. We can see that subscription is working.
And next, let's just actually test this by creating new messages inside Direct Us. Whenever I save this, you can see the messages show up inside our console with all of the data that we created. No refresh. No latency. Just smooth real time data inside your project in 3 minutes or less.
Stay tuned for more content on direct us real time, and we can't wait to see what you build. Thanks for watching.