Y-websocket-server connection event emitted twice on page reload

I’m trying to add postgres persistence to y-websocket-server with the yjs codemirror demo code and found that bindState and writeState got called twice on page refresh. If I close the page and open a new one, it works as expected, bindState and writeState got called once.

I did some initial debugging and observed that the ‘connection’ event fires twice on page reload.

To reproduce, change the following in server.js

wss.on('connection', () => {
  setupWSConnection
  console.log('connection') // this gets logged twice on page refresh, and log once if close the tab and open a new one
})

I tested with Edge and Firefox on Windows, this only reproduces with Firefox.

It seems that Edge and Firefox behave differently with setTimeout when timeout is 0, in y-websocket.js, the initial timeout is 0, increasing the timeout (from log(1) to log(2)) is a way to work around this issue.

However, I don’t fully understand why this happens.