denoland/deno · error · TypeError

Socket has no handle - cannot upgrade

Error message

Socket has no handle - cannot upgrade

What it means

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.

Solutions

  1. Ensure the upgrade happens exactly once per socket, before any close
  2. Guard with `if (!socket._handle) return;` before upgrading
  3. Fix double registration of 'upgrade' listeners on the same server

Example fix

// before
async function maybeUpgrade(req, socket) {
  await logRequest(req);
  return Deno.upgradeWebSocket(req, { socket }); // socket may have closed meanwhile
}

// after
async function maybeUpgrade(req, socket) {
  await logRequest(req);
  if (socket.destroyed || !socket._handle) return null; // socket is gone
  return Deno.upgradeWebSocket(req, { socket });
}
Defensive patterns

Strategy: validation

Validate before calling

if (socket.destroyed || !(socket as any)._handle) return; // unusable
const { response } = Deno.upgradeWebSocket(req, { socket });

Type guard

const hasNativeHandle = (
  s: { _handle?: unknown },
): boolean => s._handle != null;

Try / catch

try {
  return Deno.upgradeWebSocket(req, { socket });
} catch (err) {
  if (err instanceof TypeError && err.message.includes("no handle")) return;
  throw err;
}

Prevention

When it happens

Trigger: 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).

Common situations: Double-upgrade bugs; races between close and upgrade on flaky connections; wrappers that pre-destroy sockets on error paths.

Related errors


AI-assisted analysis of denoland/deno@9ad36f7a2c (2026-08-20). Data as JSON: /api/errors/3008da4caf609962. Report an issue: GitHub.

Appendix: source

Thrown at ext/http/02_websocket.ts:162

    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,
    // onmessage, etc.) before events fire.
    (async () => {
      try {
        // Wait for the 101 response to fully flush before taking the
        // stream. A fire-and-forget write could leave data in the
        // internal_write_queue that would be orphaned once we detach

View on GitHub (pinned to 9ad36f7a2c)