Websockets allow real time “pushing” of data between the backend of your app and the frontend of your app.

Here’s an example of using Express with Websockets to create a websocket connection between the server.js and the consuming index.html and assets/client.js:

Responsibilities per file:

  • server.js - creates the websocket connection && serves the index.html file on the root path
  • assets/script.js - creates the client side websocket instance and connects to the server instance
  • index.html - duh

Chat Example with Express, Websockets & React

This example is slightly more advanced. In addition to Express & Websockets it includes the use of React & React useEffect and useState hooks for state management:

On the backend, the server.js will broadcast messages to all connected clients. This is possible with the wss.clients.forEach(...) statement. Very cool.

Responsibilities per file:

  • server.js - creates the websocket connection && serves the index.html file on the root path
  • app/components/Chat.jsx - creates the client side websocket instance and connects to the server instance
  • index.html - duh

I gave a presentation on this for the Cleveland React meetup group. Here’s the slides if you’d like to run through them to learn more about WebSockets and how they differ from normal API calls: