{"record":{"id":"e2d57c933da2542a","repo":"denoland/deno","slug":"socket-is-already-destroyed-cannot-upgrade-to-we","errorCode":null,"errorMessage":"Socket is already destroyed - cannot upgrade to WebSocket","messagePattern":"Socket is already destroyed - cannot upgrade to WebSocket","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"ext/http/02_websocket.ts","lineNumber":156,"sourceCode":"      }\n    })();\n  } else if (options.socket) {\n    // node:http upgrade path: the socket is a node net.Socket from the\n    // \"upgrade\" event. Write the 101 response, take the TCP stream from\n    // libuv, and create a WebSocket over it via ext/http.\n    const nodeSocket = options.socket;\n\n    // Build the 101 response from r.headerList so the headers stay in\n    // sync with the header-list built above (protocol negotiation, etc.).\n    let responseHead = \"HTTP/1.1 101 Switching Protocols\\r\\n\";\n    for (let i = 0; i < r.headerList.length; i++) {\n      const { 0: name, 1: value } = r.headerList[i];\n      responseHead += `${name}: ${value}\\r\\n`;\n    }\n    responseHead += \"\\r\\n\";\n\n    if (nodeSocket.destroyed) {\n      throw new TypeError(\n        \"Socket is already destroyed - cannot upgrade to WebSocket\",\n      );\n    }\n    const handle = nodeSocket._handle;\n    if (!handle) {\n      throw new TypeError(\"Socket has no handle - cannot upgrade\");\n    }\n    if (typeof handle.takeStream !== \"function\") {\n      throw new TypeError(\n        \"Socket is not a TCP socket - only TCP connections can be upgraded to WebSocket\",\n      );\n    }\n\n    // Extra bytes that were already buffered (e.g., from the upgrade\n    // request body that arrived with the headers)\n    const extraBytes = options.head || new Uint8Array(0);\n\n    // Defer setup so the caller can attach event handlers (onopen,","sourceCodeStart":138,"sourceCodeEnd":174,"githubUrl":"https://github.com/denoland/deno/blob/9ad36f7a2cce60488e6ec52283efb32efddaf93a/ext/http/02_websocket.ts#L138-L174","documentation":"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.","triggerScenarios":"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).","commonSituations":"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.","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"],"exampleFix":"// before\nserver.on(\"upgrade\", (req, socket, head) => {\n  setTimeout(() => {\n    const { response, socket: ws } = Deno.upgradeWebSocket(req, { socket }); // may throw\n  }, 1000);\n});\n\n// after\nserver.on(\"upgrade\", (req, socket, head) => {\n  if (socket.destroyed) return;\n  const { response, socket: ws } = Deno.upgradeWebSocket(req, { socket, head });\n});","handlingStrategy":"validation","validationCode":"if (socket.destroyed) return; // client already gone\nconst { response, socket: ws } = Deno.upgradeWebSocket(req, { socket });","typeGuard":"const isUpgradableNodeSocket = (\n  s: { destroyed?: boolean; _handle?: { takeStream?: unknown } },\n): boolean => !s.destroyed;","tryCatchPattern":"try {\n  return Deno.upgradeWebSocket(req, { socket });\n} catch (err) {\n  if (err instanceof TypeError && err.message.includes(\"destroyed\")) return; // ignore dead client\n  throw err;\n}","preventionTips":["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"],"tags":["websocket","node-http","net-socket","upgrade"],"backgroundTag":"socket-already-destroyed","analyzedSha":"9ad36f7a2cce60488e6ec52283efb32efddaf93a","analyzedAt":"2026-08-20T13:07:44.778Z","contentChangedAt":"2026-08-20T13:07:44.778Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}