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

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

A modern runtime for JavaScript and TypeScript.
Go to Latest
function Deno.upgradeWebSocket
import { Deno } from "https://deno.land/x/deno@v1.28.0/cli/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.

const conn = Deno.listen({ port: 80 });
const httpConn = Deno.serveHttp(await conn.accept());
const e = await httpConn.nextRequest();
if (e) {
  const { socket, response } = Deno.upgradeWebSocket(e.request);
  socket.onopen = () => {
    socket.send("Hello World!");
  };
  socket.onmessage = (e) => {
    console.log(e.data);
    socket.close();
  };
  socket.onclose = () => console.log("WebSocket has been closed.");
  socket.onerror = (e) => console.error("WebSocket error:", e);
  e.respondWith(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().