Skip to content

WebSocket fires both close and error events twice if the socket is closed before being opened. #4628

Closed

Description

@zbinlin

Reproducible By

import { WebSocket } from "undici";

const ws = new WebSocket("wss://example.com/");
ws.onopen = () => {
	console.log("Opened", ws.readyState);
}
ws.onclose = () => {
	console.log("Closed", ws.readyState);
}
ws.onerror = () => {
	console.log("error", ws.readyState);
}

setTimeout(() => {
	ws.close();
}, 100); // Modify this value to ensure the closing happens before or after opening

Expected output

error 2
Closed 3

Actual output

error 3
Closed 3
error 3
Closed 3

Environment

  • ArchLinux
  • nodejs v24.9.0
  • undici ^7.16.0

Activity

  1. added a commit that references this issue on Oct 18, 2025
    7102fc2
  2. KhafraDev commented on Oct 18, 2025

    @KhafraDev
    Member

    In other environments I get

    error 3
    Closed 3
    

    Why do you expect the state to be CLOSING (2) when emitting the error event?

  3. zbinlin commented on Oct 19, 2025

    @zbinlin
    ContributorAuthor

    Why do you expect the state to be CLOSING (2) when emitting the error event?

    In ws package, the readyState is 2.

  4. KhafraDev commented on Oct 19, 2025

    @KhafraDev
    Member

    I think this is the same as #4487 (comment), or at least close to it. The readyState being CLOSING seems to be correct and makes more sense.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions