How to display a Connection Status widget in Rails
I saw a nifty Connection Status widget on another app today and wanted to build my own in Content Harmony, and came up with this solution using Stimulus and a simple /connection_status endpoint that serves a 200 response.
In short, the widget shows the user whether or not they're currently connected to our server.
Initially I was trying to hook this into an existing ActionCable or Turbo method to piggy back one of those existing connections. After fooling around for a bit I settled on a simpler solution that is disconnected from both of those.
I created a new /connection_status endpoint which serves a 200 response as well as plaintext message of Connected
. A Stimulus controller pings that endpoint every 15 seconds starting on page load. The Stimulus controller also checks the browser connection status that is reported.
As a result, in localhost, I can shut off my wi-fi and see an Offline
status because we're hooked into the browser's status, or I can shut down the local server after loading the page and see status change to Offline
, because the server is no longer responding to pings.
When either comes back online, the page displays Online
again.
Code Samples
Gist is embedded below, you can find the full version at https://gist.github.com/kanejamison/38d6c8bcca1b44012f964cdc5b4a369f