denoland/deno · error · TypeError
Socket is already destroyed - cannot upgrade to WebSocket
Error message
Socket is already destroyed - cannot upgrade to WebSocket
What it means
In the node:http upgrade path — `Deno.upgradeWebSocket(request, { socket })`, reached from a `node:http` server's `'upgrade'` event — Deno writes the 101 response directly onto the caller's `net.Socket` and then detaches its TCP stream. If `socket.destroyed` is already `true`, the underlying file descriptor is gone and the upgrade throws before writing anything.
Solutions
- Perform the upgrade synchronously inside the `'upgrade'` event handler
- Check `socket.destroyed` first and bail out quietly when the client is gone
- Ensure exactly one handler upgrades a given socket
Example fix
// before
server.on("upgrade", (req, socket, head) => {
setTimeout(() => {
const { response, socket: ws } = Deno.upgradeWebSocket(req, { socket }); // may throw
}, 1000);
});
// after
server.on("upgrade", (req, socket, head) => {
if (socket.destroyed) return;
const { response, socket: ws } = Deno.upgradeWebSocket(req, { socket, head });
}); Defensive patterns
Strategy: validation
Validate before calling
if (socket.destroyed) return; // client already gone
const { response, socket: ws } = Deno.upgradeWebSocket(req, { socket }); Type guard
const isUpgradableNodeSocket = (
s: { destroyed?: boolean; _handle?: { takeStream?: unknown } },
): boolean => !s.destroyed; Try / catch
try {
return Deno.upgradeWebSocket(req, { socket });
} catch (err) {
if (err instanceof TypeError && err.message.includes("destroyed")) return; // ignore dead client
throw err;
} Prevention
- Upgrade synchronously inside the 'upgrade' event, before any await
- Do minimal auth/validation after upgrading, not before
- Register only one 'upgrade' listener per server to avoid double handling
When it happens
Trigger: The client disconnected between emitting `'upgrade'` and the call; earlier handlers or timeout logic destroyed the socket; attempting a second upgrade on a socket already upgraded (a successful upgrade sets `destroyed = true` as part of detaching the handle).
Common situations: Async work (auth, DB lookup) done before upgrading while the client times out; error middleware that destroys sockets; the same socket handled by two upgrade listeners.
Related errors
- Socket has no handle - cannot upgrade
- Already closed
- Already upgraded
- Invalid Header: 'upgrade' header must contain 'websocket'
- Socket is not a TCP socket - only TCP connections can be…
AI-assisted analysis of denoland/deno@9ad36f7a2c (2026-08-20).
Data as JSON: /api/errors/e2d57c933da2542a.
Report an issue: GitHub.
Appendix: source
Thrown at ext/http/02_websocket.ts:156
}
})();
} else if (options.socket) {
// node:http upgrade path: the socket is a node net.Socket from the
// "upgrade" event. Write the 101 response, take the TCP stream from
// libuv, and create a WebSocket over it via ext/http.
const nodeSocket = options.socket;
// Build the 101 response from r.headerList so the headers stay in
// sync with the header-list built above (protocol negotiation, etc.).
let responseHead = "HTTP/1.1 101 Switching Protocols\r\n";
for (let i = 0; i < r.headerList.length; i++) {
const { 0: name, 1: value } = r.headerList[i];
responseHead += `${name}: ${value}\r\n`;
}
responseHead += "\r\n";
if (nodeSocket.destroyed) {
throw new TypeError(
"Socket is already destroyed - cannot upgrade to WebSocket",
);
}
const handle = nodeSocket._handle;
if (!handle) {
throw new TypeError("Socket has no handle - cannot upgrade");
}
if (typeof handle.takeStream !== "function") {
throw new TypeError(
"Socket is not a TCP socket - only TCP connections can be upgraded to WebSocket",
);
}
// Extra bytes that were already buffered (e.g., from the upgrade
// request body that arrived with the headers)
const extraBytes = options.head || new Uint8Array(0);
// Defer setup so the caller can attach event handlers (onopen,View on GitHub (pinned to 9ad36f7a2c)