Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
R

robust-websocket

> 编程语言
Open source

A robust reconnecting WebSocket client for the browser

199 stars0 likes2 views
WebsiteGitHub

About

A robust reconnecting WebSocket client for the browser

robust-websocket

A robust, reconnecting WebSocket client for the browser

robust-websocket is a wrapper around the standard WebSocket class that implements the same interface, but can reconnect when disconnected or the user's computer comes back online.

It is error-code aware and will not reconnect on 1008 (HTTP 400 equivalent) and 1011 (HTTP 500 equivalent) by default. This behavior is fully configurable via the shouldConnect (see Usage).

Compared to reconnecting-websocket

  • Tests! You know it works like stated and regressions will be caught.
  • Is aware of online and offline, and won't burn up the users battery and CPU reconnected when offline, and will reconnect when it is online again.
  • Natively aware of error codes
  • Any kind of reconnect strategy is possible via functional composition

Usage

CodePen Example

Use it as you would a normal websocket:

javascript
var ws = new RobustWebSocket('ws://echo.websocket.org/')

ws.addEventListener('open', function(event) {
  ws.send('Hello!')
})

ws.addEventListener('message', function(event) {
  console.log('we got: ' + event.data)
})

But with an optional set of options you can specify as a 3rd parameter

…

shouldReconnect Examples

Reconnect with an exponetial backoff on all errors

javascript
function shouldReconnect(event, ws) {
  return Math.pow(1.5, ws.attempts) * 500
}

Reconnect immediately but only 20 times per RobustWebSocket instance

javascript
function shouldReconnect(event, ws) {
  return ws.reconnects <= 20 && 0
}

Reconnect only on some whitelisted codes, and only 3 attempts, except on online events, then connect immediately

javascript
function shouldReconnect(event, ws) {
  if (event.type === 'online') return 0
  return [1006,1011,1012].indexOf(event.code) && [1000,5000,10000][ws.attempt]
}

See documentation for CloseEvent and online event, the two types of events that shouldReconnect will receive.

Typically, websockets closed with code 1000 indicate that the socket closed normally. In these cases, robust-websocket won't call shouldReconnect (and will not attempt to reconnect), unless you set shouldReconnect.handle1000 to true.

Polyfills needed

You may need these polyfills to support older browsers

  • Object.assign - npm package or 24-line MDN snippet
  • CustomEvent - npm package or 15-line MDN snippet

Issues· 5 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

JavaScript

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 18, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言