{"record":{"id":"3008da4caf609962","repo":"denoland/deno","slug":"socket-has-no-handle-cannot-upgrade","errorCode":null,"errorMessage":"Socket has no handle - cannot upgrade","messagePattern":"Socket has no handle - cannot upgrade","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"ext/http/02_websocket.ts","lineNumber":162,"sourceCode":"    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,\n    // onmessage, etc.) before events fire.\n    (async () => {\n      try {\n        // Wait for the 101 response to fully flush before taking the\n        // stream. A fire-and-forget write could leave data in the\n        // internal_write_queue that would be orphaned once we detach","sourceCodeStart":144,"sourceCodeEnd":180,"githubUrl":"https://github.com/denoland/deno/blob/9ad36f7a2cce60488e6ec52283efb32efddaf93a/ext/http/02_websocket.ts#L144-L180","documentation":"Same node-socket upgrade path: after verifying the socket is alive, Deno reads `socket._handle` — the native/libuv handle. A socket without one (never fully connected, already closed and detached, or previously gutted by an earlier upgrade — success sets `nodeSocket._handle = null`) cannot be taken over, so the upgrade throws this TypeError.","triggerScenarios":"Upgrading a socket that was closed (destroy ran and nulled the handle); a socket whose connection setup has not completed; calling the upgrade twice — the first success nulls `_handle`, the second throws here (after the destroyed check).","commonSituations":"Double-upgrade bugs; races between close and upgrade on flaky connections; wrappers that pre-destroy sockets on error paths.","solutions":["Ensure the upgrade happens exactly once per socket, before any close","Guard with `if (!socket._handle) return;` before upgrading","Fix double registration of 'upgrade' listeners on the same server"],"exampleFix":"// before\nasync function maybeUpgrade(req, socket) {\n  await logRequest(req);\n  return Deno.upgradeWebSocket(req, { socket }); // socket may have closed meanwhile\n}\n\n// after\nasync function maybeUpgrade(req, socket) {\n  await logRequest(req);\n  if (socket.destroyed || !socket._handle) return null; // socket is gone\n  return Deno.upgradeWebSocket(req, { socket });\n}","handlingStrategy":"validation","validationCode":"if (socket.destroyed || !(socket as any)._handle) return; // unusable\nconst { response } = Deno.upgradeWebSocket(req, { socket });","typeGuard":"const hasNativeHandle = (\n  s: { _handle?: unknown },\n): boolean => s._handle != null;","tryCatchPattern":"try {\n  return Deno.upgradeWebSocket(req, { socket });\n} catch (err) {\n  if (err instanceof TypeError && err.message.includes(\"no handle\")) return;\n  throw err;\n}","preventionTips":["Treat _handle == null as 'socket already closed or consumed' and skip","Never re-upgrade a socket that a previous upgrade detached","Close out failed upgrades quietly — the peer is usually gone"],"tags":["websocket","node-http","net-socket","handle"],"backgroundTag":"invalid-socket-state","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"}