/ Javascript

Native Web Sockets

Recently I was working on a project which was going to use web sockets to relay backend updates to all connected clients in real time. I have worked with Socket.IO in the past and found it wonderfully easy to use. This time however I thought, since my use case was fairly straight forward, it seemed like overkill to bring in a library and decided to simply use the native api.

The Goal

My aim was very straightforward: when the user hits a specific page open a socket connection with the server and tell it which group to connect to. The server then setup a change feed on my RethinkDB and would just send new information to the client as it appeared in the database. Since there was only going to be one data type going in each direction, a string to the server and an image to the client, it did prove very simple.

The Setup

First thing was first, when the specific page loaded I needed to create a connection and then send the initial message telling the server which table in the database to watch. Since I was working in react this of course occurred in the componentDidMount function.

componentDidMount() {
  const wsuri = 'ws://localhost:4028/sockets/groupConnect';

  const sock = new WebSocket(wsuri);


If you have ever made use of the browsers XMLHttpRequest or web workers you will be familiar with the syntax that follows.

First we need to set up an onmessage handler to receive and manage incoming data. In this case since I was going to send an initial stream of existing data followed by the individual changes I needed to handle the data in two potential formats.

sock.onmessage = (msg) => {
  const data = JSON.parse(msg.data);
  const photo = data.new_val !== undefined ? data.new_val : data;

With this setup I then gave the socket an onopen function which would fire immediately when the connection was established. This function just told the server which table to setup a change feed on.

sock.onopen = () => {
  this.state.sock = sock;

And that was it for the client! Like I said very simple. Certainly Socket.IO gives a more familiar syntax and is also very simple but it's also an extra bit of weight in my JS bundle and in this case I just didn't need it.

It's good to remember we don't always have to grab the biggest tool just because we know how to use it.

P.S. to use secure websockets when you deploy simply add the 's' to the uri: wss://yourdeployedurl.here