Let’s Build a WebSockets Project With Rust and Yew 0.19
Tags: websocket, yew, rust
Published: 2022-02-15 10:09:34

---
title: Let’s Build a WebSockets Project With Rust and Yew 0.19
published: true
date: 2022-02-14 21:26:55 UTC
tags: websocket,yew,rust
canonical_url: https://fsjohnny.medium.com/lets-build-a-websockets-project-with-rust-and-yew-0-19-60720367399f
cover_image: https://cdn-images-1.medium.com/max/1024/1*XEtmkR0Qg6Y2j_Duy3uZIA.jpeg
---

#### Cover Photo by [Mike Winkler](href="https://unsplash.com/@ahmeyer?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText) on [Unsplash](https://unsplash.com/s/photos/socket?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText)

Let me start by saying I’m a HUGE fan of Yew. Using the power and flexibility of Rust to build front-end components is something that I feel will only get bigger as the adaptation of WebAssembly grows. Recently, one of my side projects needed some WebSockets love. I figured this would be the perfect time to dive into Yew’s recently released 0.19 version, which introduced several significant changes to the framework (the removal of web-sys and its supported services (i.e. ConsoleService) and the introduction of _Functional Components,_ to name a few).

As you might have guessed from the title already, we will build a chat app (such a cliche, I know, I’ll show myself out) using Yew, yew-router, yew-agent, and several other crates.

![YewChat](https://cdn-images-1.medium.com/max/615/0*OZlexFCroqrP80FF.jpg)
_At least it’s got GIF support!_

To give you a sense of what we are going to build, check out this lovely image:

![YewChat](https://cdn-images-1.medium.com/max/818/1*RbbAFl7MeYex63eTb9s0dQ.gif)

> 🛑  Before moving forward make sure you have Rust and NodeJS installed.

### 🗿 The WebSocket Server

To use WebSockets on the client-side you need a server capable of working with WebSockets (a shocker, I know). To keep this post a (somewhat) reasonable length, and for the sake of focusing on a single subject, we won’t be discussing the WebSockets server too much. In a nutshell: other than handling the incoming and outgoing connections, the server saves the incoming connections in an array called users. Every few seconds the server will compare the users array to the server’s current active connection list to verify that all the users in the list are in fact still connected.

While you can go and build/use your own WebSockets server for our lovely chat app, the easier solution here will be to clone the NodeJS WebSocket server I used at [https://github.com/jtordgeman/SimpleWebsocketServer](https://github.com/jtordgeman/SimpleWebsocketServer). Once cloned, run npm i and then npm start and if all went well, you should now have a cute WebSockets server running locally on port 8080.

### Time to Take Off 🚀

1. Clone the starter project at [https://github.com/jtordgeman/YewChat](https://github.com/jtordgeman/YewChat)
2. Install the toolchain dependencies

```
npm i
```

> The starter project is nothing but an empty project with wasm-pack and webpack already set up, so we can focus our attention to Yew

### **🛤 ️Routing**

Our app has three possible routes:

1. login— a simple page with a textbox and a button for a user to enter their nickname
2. chat — The main page — has a list of users, the chat display, and a textbox to write stuff to the chat
3. 404 — If anyone tries to go to a page that doesn't exist — this catch-all page will show up in all its glory

If you are coming from React you probably know (and use) react-router-dom. Well, good news! yew-router is pretty much the exact same idea! yew-router handles the display of different pages (components) depending on the URL.

So enough with the theory, let’s get busy:

1. Create a new folder named **components** under the **src** folder. We will host all of our components here.
2. Create three files under the newly created components folder: **chat.rs** , **login.rs** , **mod.rs.** We will leave chat and login empty for now, in mod.rs add the following:

{% gist https://gist.github.com/pxjohnny/1a03d09e61a13ed8be899a455fd96f1b %}

3. At the top of **lib.rs** , add the following use statements:

{% gist https://gist.github.com/pxjohnny/512748d2488508493c20e545c00aba5d %}

Note that **Login** and **Chat** will show as unresolved. We will fix that when we start dealing with components later on.

4. Thanks to yew-router we can use an enum to define our routes. We will add it to our **lib.rs** as follows:

{% gist https://gist.github.com/pxjohnny/2c8f46651f2d90eaf614066d8be0ace4 %}

Pretty neat stuff! We annotate each entry with the URL it handles. Note that the 404 route uses an additional annotation: #[not\_found] — this macro comes from the yew-router package and is basically what makes this route a catch-all route.

5. Next we need a way to translate the enum value of a route to an actual component. Add the following switch function just below the Route enum:

{% gist https://gist.github.com/pxjohnny/ee5afd82e33b1db6b96a42b05a8da7a0 %}

6. To render our router (and in turn, the components it routes to) we will use **a functional component.** But what is a functional component you may ask?  
A functional component is a simplified version of the regular Yew component which can receive properties and determines the rendered content by returning HTML. In short — functional components are basically components that have been reduced to have only the view method.

{% gist https://gist.github.com/pxjohnny/69c57f40f3ff29e71a38c5f7852ca59c %}

7. Last but not least, we need an entry point to our app — a function that the JavaScript can call in order to initiate our Yew app. Add the run\_app function to lib.rs as follows:

{% gist https://gist.github.com/pxjohnny/9a31646a882f38e66b05a0771c55cc70 %}

🔬So what do we have here?

- **Line 1** : Using the wasm\_bindgen macro we expose the run\_app function to JavaScript.
- **Line 3** : We initialize the wasm\_logger crate. Using wasm\_logger and the log crates we can write debug logs to the browser’s console.
- **Line 4** : We are passing our Main component (defined in the previous step) to the start\_app method of yew, to — as you might have guessed — start the app.

With the routing in place, let’s move on to creating our components.

### 🪅 **️Components — Phase 1**

For simplicity sake, our app will consist of two components:

- **Login**  — a simple functional component to get the username and connect to the WebSockets server.
- **Chat**  — the main component of the app — shows the chat window, and a text area to write content to the chat.

When users browse to the **Login** component they will type a username and click connect — that username then needs to pass down to the **Chat** component and be used there to connect to the WebSocket server. To achieve that we will use a **Context** (think of it as a global state of the app) that will hold the username for any component to use. The way we define a Context is as follows:

1. Define a struct for the context and a type alias for it:

{% gist https://gist.github.com/pxjohnny/662e8760c4fbc6de632cebfd88c8264f %}

2. In the main component, define a context using the use\_state hook:

{% gist https://gist.github.com/pxjohnny/1dbcb677f7a7cbd2b4ec4389db54e217 %}

3. Lastly, let’s use the context by wrapping the main component HTML with a ContextProvider element which enables the child elements to actually use this context.

{% gist https://gist.github.com/pxjohnny/9dc14f704dc7907a595c9aad24219302 %}

A ContextProvider element requires a context struct (User in our case) and a context object (ctx), that is set using the element’s context property.

> _👁️_ Note: the child elements of a ContextProvider will re-render whenever the context changes.

With the context in place, let’s build the **Login** component!

1. In **components/login.rs** add the **login** functional component:

{% gist https://gist.github.com/pxjohnny/f5e982ab8d8da5bd8b6ef0faf673635d %}

2. Declare a use\_state hook that will manage the state of the username the user typed in. When declaring a use\_state hook we provide the default value (an empty String in our case), similarly to React’s use\_state hook:

{% gist https://gist.github.com/pxjohnny/842cf98f8fc44606e05b364d541c491e %}

3. To get a reference to the context (which as you might remember will hold the global state for the username), use the use\_context hook:

{% gist https://gist.github.com/pxjohnny/c3b2d27d554675fd7bfe04ea4c440090 %}

4. The Login component UI will contain an input element and a button. Whenever the input changes we need to update the local username variable. To connect between the UI element and username, we use a callback:

{% gist https://gist.github.com/pxjohnny/6e2c7adbf259287c9648adf3f7ec03d0 %}

🔬So what do we have here?

- **Line 7** : We clone the username state handler so we can later update it using its set method.
- **Line 9** : We create a Callback from the input element’s onchange event.
- **Line 10** : We get the target element (the element that fired the event) using the InputEvent’s target\_unchecked\_into method.
- **Line 11** : We update the username state with the new value that the input element currently holds using the element’s value method.

> _🎉_ If you have ever done any JavaScript work with HTML elements then all of this should look pretty similar.

5. The next callback we need to create is for the submit button. Once the username is typed, and the user clicks on the submit button — we need to save that username to the global context so that other components can use it if needed. Create the onclick callback as follows:

{% gist https://gist.github.com/pxjohnny/ab08763a973eee804fd8c0c97d7ca69c %}

6. Lastly, let’s add the actual UI for this component using the html! macro:

{% gist https://gist.github.com/pxjohnny/051265ec1ef5dc943085e53b5a8263f5 %}

👀 A few callouts:

- The input element registers to the oninput callback. Every time the input changes — we call oninput and update the username state.
- We use the Link element from the yew\_router crate to route the browser to the Chat route using the to property.
- The Link element contains a button element, which registers to the onclick callback which updates the global context with the value of username. In addition to that, the button also sets the disabled property to prevent the user from clicking it, unless username has a length of 2 characters or more.

And that’s a wrap for the Login component 🎊. We now have a component that uses a Context in order to share its data (username in our case) with other components.

Now we may be tempted to run ahead and create the chat component, but let’s stop for a minute and think about how the chat component even works…

### 👋 Hello WebSockets!

At the heart of our chat application are WebSockets. WebSockets enable us to asynchronously send and receive messages between the server and the client without the need for constant polling from the client. This feature makes Websockets the perfect centerpiece for our chat app. Let’s go ahead and create a WebSocket service that will handle all the aspects of working with WebSockets in our app!

1. Create a new folder called **services** under the **src**  folder.
2. Add a new file called **mod.rs** inside **services** with the following content:

{% gist https://gist.github.com/pxjohnny/4d86efb3be19686d6bd541714aa35510 %}

3. Our Websocket service will handle the following:

- Listen to incoming messages from the WebSocket server.
- Write messages to the WebSocket server.
- Communicate with other components using MPSC (Multi Producers Single Consumer) Channel (more on this soon 🤔)

Add a new file called **websocket.rs** inside the **services** folder with the following content:

{% gist https://gist.github.com/pxjohnny/73a300c131ba8b441c3ac504a92e3dfc %}

😱 OMG there’s a lot going on here, let’s bite-size this whole thing:

- **Lines 6–8:** Creates the WebsocketService struct that holds a single property of type Sender. Sender allows us to asynchronously send messages on the channel that the receiver will later receive, in the order they are sent. Sender is cloneable, which means that every component that uses the service can clone it and use it to send messages back to the receiver, which as the name suggests — there can only be a single one.
- **Lines 11–46** : The new function initialize the service, similar to a constructor in other languages. The function does the following:  
- Connects to the WebSocket server (line 12)  
- Create the MPSC channel (line 16)  
- Spawns a new future (async task) on the current thread that will listen to the receiving end of the MPSC channel and write the received message to the WebSocket server. This is how components communicate with our service — by sending messages across the channel (lines 18–23).  
- Spawns another new future on the current thread to listen to the incoming messages from the WebSocket server and log them out(lines 25–43).  
- Finally, the function returns an instance of WebSocketService (Self) that holds the channel transmitter (in\_tx).

Here’s a handy diagram visualizing how everything connects:

![Component/Service Diagram](https://cdn-images-1.medium.com/max/551/1*NrZlkCpS7Wj8Oiehxur4ig.png)

Awesome, with the WebSocket service behind us, let’s proceed with creating the actual chat component!

### 🪅 ️Components — Phase 2

For our Chat component, we will use a regular (read not functional) component because we will make good use of its different lifecycle methods.

1. Open up **chat.rs** and add the following:

{% gist https://gist.github.com/pxjohnny/ef20c037f2d67442acef66d8285840e7 %}

👀 A few callouts:

- The Msg enum holds the possible messages (read actions) our component can receive. Chat has two basic functionalities: either it handles a message received from the WebSocket server (HandleMsg), or it submits a message to the server (SubmitMessage) — for example when a user types something into the chat.
- MessageData represents a chat message, containing who is it from and what the actual message is.
- The MsgTypes enum holds the different types of messages the component can send or receive.
- Lastly, WebSocketMessage represents what a message to the WebSocket server looks like: it has a type (message\_type) and then either an array of strings (such as in the case of the chat users list) or a single string (such as the case of sending a chat message to the server).

2. Next, let’s add the Chat component itself:

{% gist https://gist.github.com/pxjohnny/119abdc86696ccd4bb4f25d9a8997ca7 %}

The Chat components hold the user list (users), the input typed to the text box (chat\_input), a reference to the Websocket service (wss), and finally, an array of all the messages typed to the chat (messages).

3. The first component lifecycle method we add is the create method. create initializes the component state and it’s ComponentLink:

{% gist https://gist.github.com/pxjohnny/4c2115fb283c45802315d3ac1a7b03c6 %}

👀 Quite a few things are happening here so let’s break them down:

- We get the user object (of type Rc<UserInner>) we saved in the Context (lines 4–7) and then clone its username field (line 9), which is the actual user name the user used to log in.
- We create a new WebSocket message to register the current client with the WebSocket server (lines 11–15). Next, we send it to the WebSocket server using the WebSocketService’s channel transmitter (tx) (lines 17–23). If everything goes well we log a message to the console (line 22).
- We finish the method off by sending a fresh instance of Chat (lines 25–30).

4. Next, we add the view method, which is responsible for rendering the component:

{% gist https://gist.github.com/pxjohnny/6069a285076afe50766b1d6aa511898c %}

That's one long method 😅 Most of the stuff here is just HTML and styling so we won't dive into that, but here are a few interesting pointers:

- On line 4 we create a callback of type MouseEvent to use when the submit button is clicked. The callback will send a message of type SubmitMessage whenever the button is clicked. This message will then get handled by the update lifecycle method.
- On line 10 we iterate over the users field by using map and collect to render a list of currently connected users (each user is rendered in its own div element).
- On line 33 we iterate over the messages field, similar to how we did it previously for users.
- We use the ref property on the input element (line 57) so we can later reference it (i.e. to read its value) outside of the view lifecycle method.
- We set the Submit button’s onclick property (line 58) to submit the callback defined on line 4.

5. We are FINALLY ready to run the project for the first time and see what we achieved so far! Inside the project root folder run npm start. This will kick the process of compiling our app into WASM, optimizing it, building the HTML (with Webpack), and finally — running a dev server.

If all goes well you should be greeted with a login page where you can enter a username. Once done the main chat screen appears, let’s inspect the dev tools console:

![dev tools](https://cdn-images-1.medium.com/max/1024/1*JoF7BoLa-6R4DMX1Mm6VJg.png)

Three lines pop out almost immediately:

- We successfully sent a WebSocket message from our chat component to the WebSocket server (first debug line)
- The WebSocket service sent the username to the WebSocket server
- The WebSocket server returned a message with a type of users containing an array with the names of the connected users.

Now that begs the question: if our WebSocket service received a message back with all the connected users — why don't we see that on our UI? Did our chat component even get that message at all?

Eagled-eyed readers might notice that when we previously discussed our WebSocket service. We only discussed how components send messages to the service, but nowhere did we mention how the service sends back messages to the components. Let’s take another dive into the rabbit hole that is our WebSocket service…

### 🔌 WebSockets — Phase 2

We are currently using an MPSC channel to communicate between components and the WebSocket service, but as the name implies — we cannot use the same approach for updating the components since we would need the opposite direction, i.e. multi consumers (components) single producer (service), which doesn't exist.

<iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FQs0dNPYUNlOLZHU6u0%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FQs0dNPYUNlOLZHU6u0%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FQs0dNPYUNlOLZHU6u0%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/644b0fe0703d066ae60bd7165831a174/href">https://medium.com/media/644b0fe0703d066ae60bd7165831a174/href</a></iframe>

We use Yew Agents! Agents can be used to “route messages between components independently of where they sit in the component hierarchy” (taken from Yew’s official docs). That means we can use an agent’s dispatcher to send a message from the WebSocket service down to any listening component. Let’s create an event bus service which we will use to send these messages with.

Create a new file called **event\_bus.rs** under services and paste the following content to it:

<iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d8876d1d684913d723182682dcef02e/href">https://medium.com/media/5d8876d1d684913d723182682dcef02e/href</a></iframe>

🔬So what do we have here?

- **Lines 10–13** : we create the EventBus struct which holds a link and a list of subscribers.
- **Lines 15–47** : we implement the Agent trait for our EventBus. There are a bunch of methods we need to implement (connected, disconnected etc), but the one we care about the most is handle\_input, which iterates over all of the subscribers and using link, sends them the content of the message.

Now let’s go back to our WebSocket service and use the new event bus:

1. Open **websocket.rs** under the services folder. Add the required use statements and the event\_bus initializing. We are creating a dispatcher because we need a one-way communication channel between the service and the components:
<iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ed2ab338cd5d31bbdf04811ba1758bc/href">https://medium.com/media/8ed2ab338cd5d31bbdf04811ba1758bc/href</a></iframe>

2. To send a message on the channel, all we have to do is use send:

<iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/40bf2850055509e4dc735edd39e7aed5/href">https://medium.com/media/40bf2850055509e4dc735edd39e7aed5/href</a></iframe>

You can see we are making use of the EventBusMsg struct we defined in **event\_bus.rs** to send a String message down the channel (lines 9 and 15).

Lastly, we need to add the event bus to the Chat component.

1. Open **chat.rs** under the **components** folder, and add \_producer to the Chat struct:
<iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/35f9ec005dceb966bf32355d07e3360a/href">https://medium.com/media/35f9ec005dceb966bf32355d07e3360a/href</a></iframe>

2. Head over to the create lifecycle method of Chat and add the default value for \_producer to the returning Self statement:

<iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/04010ad3c68e103fd8c2ba33ba68b048/href">https://medium.com/media/04010ad3c68e103fd8c2ba33ba68b048/href</a></iframe>

If you run the app again now you’ll notice nothing really changes. The reason for that is we never implemented the update lifecycle method, which is in charge of handling the different messages our component get (like HandleMsg or SubmitMessage). The method returns a boolean indicating whether the component should be re-rendered or not.

3. Under the create method, add the following implementation of update:

<iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a758d26b80832373969f8b0a75d5a68d/href">https://medium.com/media/a758d26b80832373969f8b0a75d5a68d/href</a></iframe>

🔬So what do we have here?

The method matches msg to one of the two possible messages the component can get: HandleMsg or SubmitMessage. If the message is of type HandleMsg we perform another match and check whether it is a message of type Users or of type Message. Messages of type Users get sent every time the connected user list changes (a user connect/disconnect) and upon receiving this message — we populate the users array with the name and avatar of each user that is connected. Messages of type Message get sent when a user posts a message to the chat, and pretty similar to how we handled users, we append the new message to the messages array. In both of these cases, we return true since we need the component to rerender itself with the new data.

In the case the message is of type SubmitMessage we grab the message text from the input HTML element (remember that ref property we set earlier?) and using the WebSocket service channel transmitter (tx) we send the message to the WebSocket server. In the case of SubmitMessage we return false as we don't need the component to rerender itself.

And with this change, our app is now ready for prime time!

![final product](https://cdn-images-1.medium.com/max/1024/1*GTmruZMoiZUJw43JH9I4GA.png)

This post was definitely on the longer side, but I hope you got to experience how it is like working with Yew when building a web app. You can find the full source code at [https://github.com/jtordgeman/YewChat](https://github.com/jtordgeman/YewChat). Feel free to hit me up on [Twitter](https://twitter.com/FullStackJ) or by leaving a comment here — I promise I'll answer nicely ;p

Last but not least, huge thanks to [Sara Lumelsky](https://medium.com/u/9caa2c6ac2a4) for proofreading and fixing my stupid spelling mistakes! :)