#44098·bun

ws: a finishRequest that calls req.end() later opens two connections

Author: robobunCreated Sep 27, 2026Updated Sep 28, 2026

What version of Bun is running?

1.4.2+744846f84. Also a build of main at a4f1429148.

What platform is your computer?

Linux x64

What steps can reproduce the bug?

Use the finishRequest option of the ws client, and call req.end() after finishRequest returns.

javascript
const { WebSocket } = require("ws");
const seen = { connections: [], events: [] };
process.on("exit", () => console.log(JSON.stringify(seen)));
const server = Bun.serve({
  port: 0,
  hostname: "127.0.0.1",
  fetch(req, s) {
    seen.connections.push(req.headers.get("authorization"));
    if (s.upgrade(req, { data: req.headers.get("authorization") })) return;
    return new Response("no", { status: 400 });
  },
  websocket: {
    open(w) {
      w.send("hello from connection with authorization=" + w.data);
    },
    message() {},
  },
});
const ws = new WebSocket(`ws://127.0.0.1:${server.port}`, {
  finishRequest(req) {
    Promise.resolve().then(() => {
      req.setHeader("authorization", "token");
      req.end();
    });
  },
});
ws.on("open", () => seen.events.push("open"));
ws.on("message", d => seen.events.push("message: " + d));
ws.on("error", () => seen.events.push("error"));
setTimeout(() => {
  ws.terminate();
  server.stop(true);
}, 2000);

What is the expected behavior?

One connection, with the header. Node v26.3.0 with ws 8.18.3 prints this for the same client and a WebSocketServer:

{"connections":["token"],"events":["open","message: hello from connection with authorization=token"]}

What do you see instead?

Two connections. The listeners get the events of the first one, which does not have the header.

{"connections":[null,"token"],"events":["open","message: hello from connection with authorization=null"]}

Additional information

The cause is in src/js/thirdparty/ws.js. When finishRequest returns and req.end() was not called, the client connects at once. A later req.end() connects again and replaces the private #ws. The listeners stay on the first native socket. send(), close() and terminate() go to the second.

The same cause has these effects. Each line is one client, counted by a raw TCP server.

Call order Node + ws 8.18.3 Bun
end() in a microtask or a timer 1 upgrade request, with the header 2 upgrade requests, the first without the header
end() called 2 times, after finishRequest returned 1 upgrade request 2 upgrade requests
close() or terminate(), then end() no upgrade request, readyState 3 1 upgrade request, readyState goes from 3 to 1
end() never called no upgrade request, readyState 0 1 upgrade request, readyState 1
invalid URL or duplicate subprotocol throws, finishRequest is not called finishRequest is called, then it throws
second argument of finishRequest the WebSocket undefined

A finishRequest that calls req.end() before it returns is not affected.