Skip to main content
Deno 2 is finally here 🎉️
Learn more
Module

x/deno/cli/tsc/dts/lib.deno.ns.d.ts>Deno.upgradeWebSocket

A modern runtime for JavaScript and TypeScript.
Latest
function Deno.upgradeWebSocket
import { Deno } from "https://deno.land/x/deno@v2.0.4/cli/tsc/dts/lib.deno.ns.d.ts";
const { upgradeWebSocket } = Deno;

Upgrade an incoming HTTP request to a WebSocket.

Given a Request, returns a pair of WebSocket and Response instances. The original request must be responded to with the returned response for the websocket upgrade to be successful.

Deno.serve((req) => {
  if (req.headers.get("upgrade") !== "websocket") {
    return new Response(null, { status: 501 });
  }
  const { socket, response } = Deno.upgradeWebSocket(req);
  socket.addEventListener("open", () => {
    console.log("a client connected!");
  });
  socket.addEventListener("message", (event) => {
    if (event.data === "ping") {
      socket.send("pong");
    }
  });
  return response;
});

If the request body is disturbed (read from) before the upgrade is completed, upgrading fails.

This operation does not yet consume the request or open the websocket. This only happens once the returned response has been passed to respondWith().