brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: WebSocket close codes tell you why a connection ended

Web-Development
~/tips/tip-websockets-close-codes-1000-1001-1006

const ws = new WebSocket("wss://example.com/chat");

The close code on a WebSocket close event names the reason, from normal closure to protocol errors.

A WebSocket that drops usually gets blamed on the network. Often the connection did say why it closed, and nobody read the code. In the browser it is one property away.

const ws = new WebSocket("wss://example.com/chat");
ws.onclose = (e) => console.log(e.code, e.reason, e.wasClean);

MDN defines code as the close code, reason as a server-specific string and wasClean as whether the connection closed cleanly. The codes themselves come from RFC 6455, section 7.4.1:

  • 1000: normal closure, the purpose of the connection was fulfilled.
  • 1001: an endpoint is going away, such as a server going down or a browser leaving the page.
  • 1002: protocol error.
  • 1003: data of a type the endpoint cannot accept, for example binary data sent to a text-only endpoint.
  • 1007: data inconsistent with the message type, such as non-UTF-8 data in a text message.
  • 1008: a message violated the endpoint’s policy. It is a generic code.
  • 1009: a message was too big to process.
  • 1011: the server hit an unexpected condition.

The caveat is 1006. The RFC reserves 1005, 1006 and 1015 and says an endpoint must not send them in a Close frame. 1006 is for applications that need a value meaning the connection closed abnormally, without a Close frame being sent or received. If your client reports 1006, the peer never said goodbye, so look at proxies, timeouts and crashes instead of the application code.

Further reading: RFC 6455, section 7.4.1, MDN: CloseEvent

More Web-Development tips curl -si -X OPTIONS \ | openssl dgst -sha1 -binary | openssl base64 ab -n 200 -c 10 https://example.com/ console.assert(items.length > 0, 'cart is empty', items) document.designMode = "on" All Web-Development tips (70) All topics

Link