Skip to content

[v6.x] fix(websocket): fire close when the connection fails before it opens - #5998

Open
christianaurichzm wants to merge 1 commit into
nodejs:v6.xfrom
christianaurichzm:backport-websocket-close-v6
Open

christianaurichzm wants to merge 1 commit into
nodejs:v6.xfrom
christianaurichzm:backport-websocket-close-v6

Conversation

@christianaurichzm

Copy link
Copy Markdown
Member

This relates to...

#3546 was fixed on main by #3565 and #3566, but that landed after v6.x branched, so Node 22's global WebSocket still has the bug.

Rationale

I ran into this with Node 22 connecting to OBS's websocket server while OBS was closed. error fires, close never does, and readyState stays at 0, so anything waiting on close just hangs.

const ws = new WebSocket('ws://127.0.0.1:1')
ws.onerror = () => console.log('error', ws.readyState)
ws.onclose = (e) => console.log('close', e.code, ws.readyState)

6.29.0 prints error 0. 7.x, 8.x and this branch print error 3 and then close 1006 3.

Changes

v6 doesn't have the handler refactor from main, so this isn't a cherry-pick. failWebsocketConnection now fires close with 1006 itself when the connection was still connecting, since onSocketClose only gets attached after the handshake.

I also had to skip the second failure that comes from the aborted fetch when close() is called while connecting. It was already firing error twice there, and with this change the extra one would have landed after close.

Added test/websocket/issue-3546.js, all three cases fail without the fix.

Features

N/A

Bug Fixes

#3546 on v6.x

Breaking Changes and Deprecations

N/A

Status

A WebSocket whose connection fails before it is established (a refused
TCP connection, a non-101 response or an invalid opening handshake)
fires `error` and never `close`, and its readyState stays CONNECTING.
The spec closes the connection after failing it, so `close` has to
follow `error`, with code 1006 and readyState CLOSED.

onSocketClose is only attached once the handshake succeeds, so
failWebsocketConnection now closes a connection that is still
CONNECTING itself. The fetch that close() aborts no longer fails the
connection a second time, which used to fire a second `error`.

This matches main, where it was fixed by nodejs#3565 and nodejs#3566 after v6.x
branched.

Refs: nodejs#3546
Signed-off-by: Christian Aurich Zanettini Martins <christian.aurichzm@gmail.com>
@christianaurichzm
christianaurichzm force-pushed the backport-websocket-close-v6 branch from cda2048 to cf3c0fc Compare November 19, 2026 20:40

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant