How to reconnect to websocket after close connection

NOTE: The question is tagged socket.io so this answer is specifically regarding socket.io.
As many people have pointed out, this answer doesn't apply to vanilla websockets, which will not attempt to reconnect under any circumstances.

Websockets will not automatically try to reconnect. You'll have to recreate the socket in order to get a new connection. The only problem with that is you'll have to reattach your handlers.

But really, websockets are designed to stay open.

A better method would be to have the server close the connection. This way the websocket will fire an onclose event but will continue attempting to make the connection. When the server is listening again the connection will be automatically reestablished.


When the server closes the connection, the client does not try to reconnect. With some JS frameworks maybe, but the question was, at the time of this answer, tagged as plain Vanilla JS.

I'm a bit frustrated because the accepted, upvoted answer is plainly wrong, and it cost me some additional time while finding the correct solution.

Which is here: Reconnection of Client when server reboots in WebSocket


I found a great solution on this page: sam-low.com

Once the original connection has been closed, you need to create a new WebSocket object with new event listeners

function startWebsocket() {
  var ws = new WebSocket('ws://localhost:8080')

  ws.onmessage = function(e){
    console.log('websocket message event:', e)
  }

  ws.onclose = function(){
    // connection closed, discard old websocket and create a new one in 5s
    ws = null
    setTimeout(startWebsocket, 5000)
  }
}

startWebsocket();

Note that if there’s a problem reconnecting, the new WebSocket object will still receive another close event, meaning that onclose() will be executed even if it never technically opened. That’s why the delay of five seconds is sensible - without it you could find yourself creating and destroying thousands of websocket connections at a rate that would probably break something.