A JavaScript library for WebSockets

Engineered to handle unexpected socket closures.


npm i @anephenix/sarus

What is Sarus?

A Javascript library that makes WebSockets more resilient to unexpected disconnections. Sarus acts as a wrapper around the WebSocket API, and adds some convenient features:

Automatic reconnections

If a WebSocket unexpectedly closes, Sarus will create a new WebSocket to replace the closed one automatically.

Robust event listener binding

Sarus handles attaching event listener functions to WebSockets, so that you don't have to re-bind those functions manually.

Resilient message delivery

Sarus uses a message queue for sending messages to the server, ensuring that they get sent only when the WebSocket is open.

How do I use it?

Here is a simple example you can copy and paste into your frontend code right now:

// Load the library
import Sarus from '@anephenix/sarus';

// Connect to a WebSocket server
const sarus = new Sarus({
  url: 'wss://echo.websocket.org',

// Call a function when a message
// is received from the server
sarus.on('message', event => {

// Send a message to the server
sarus.send('hello world');

// Close the WebSocket connection

For a bit more information, checkout the get started page.

What problem is it trying to solve?

WebSockets are great, but they have a weakness - they don't recover when a connection unexpectedly closes.

When a WebSocket connection closes, that connection is closed for good - it will never receive any messages from the server again. Any messages you try to send to the server via that WebSocket will throw an error, and if you don't keep a record of the messages that are being sent, then they are gone for good as well.

If you want to re-establish a WebSocket connection to the server, then you have to replace the closed WebSocket connection with a new WebSocket connection. Not only that, any event-listener functions that you have attached to the closed WebSocket connection need to be attached to the new Websocket connection as well.

You end up writing code to handle detecting the closures, re-attempting connections, binding event listener functions to new WebSocket connections, and guaranteeing message delivery.

Sarus solves these problems for you, so that you can focus on building your application.