Infura websockets disconnect after an hour of in-activity so they suggest you ping / pong the connection at an interval less then an hour.

My problem is I'm new to server-side programming and don't know how to ping the websocket connection from my back-end (node.js).

When googling I found this framework of code (below). Is this what I'd put in my back-end to 'ping' the connection?

I'm unclear if the conditional socket.readyState !== 1 is universal/'the norm' for all websockets in JS. Same with socket.send("heartbeat"). If it is then I assume it would work for Infura as well.

If anyone already has a ping pattern set-up I'd love to hear your insight!

let socket = null;

function connect_socket() {
  socket = new WebSocket(ws_url);
  socket.on("close", connect_socket); // <- rise from your grave!

function heartbeat() {
  if (!socket) return;
  if (socket.readyState !== 1) return;
  setTimeout(heartbeat, 550000); 


Thanks for any help!

  • I am stuck at the same point, using Infura socket to listen contract events, could you please suggest if you figure out this issue 2 years ago? – Surinder kumar Jun 22 '20 at 13:40