Skip to main content
Deno.upgradeWebSocket - Deno documentation
function Deno.upgradeWebSocket
upgradeWebSocket(
request: Request,
): WebSocketUpgrade

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().

Parameters

request: Request
optional
options: UpgradeWebSocketOptions

Return Type