bkr

guide

WebSockets and HTTPS

Upgrade incoming HTTP requests to WebSockets and configure TLS with PEM certificates.

Upgrade requests to WebSockets

Call upgradeWebSocket(req, { protocol }) inside a route or fetch handler. Attach listeners to socket, then return response to finish the handshake:

import { serve, upgradeWebSocket } from "http";

serve({
  port: 8080,
  routes: {
    "/ws": (req) => {
      if (req.headers.get("upgrade")?.toLowerCase() !== "websocket") {
        return new Response("upgrade required", { status: 426 });
      }
      const { socket, response } = upgradeWebSocket(req);
      socket.onmessage = (e) => socket.send(e.data);
      return response;
    },
  },
});
bkr --allow-net=:8080 ws.ts

Server WebSockets enforce a 16 MiB message limit, a 120 s idle timeout, and automatic pings.

Serve HTTPS with PEM certificates

Pass tls: { cert, key } to serve() with paths to PEM-encoded certificate and private key files. Both files need read permission, and OpenSSL 3 must be installed at run time:

import { serve } from "http";

serve({
  port: 8443,
  tls: { cert: "./cert.pem", key: "./key.pem" },
  fetch() {
    return new Response("secure");
  },
});
bkr --allow-net=:8443 --allow-read=./cert.pem,./key.pem https.ts

serve({ tls }) runs on a single HTTP thread and cannot be combined with --http-workers or --http-processes. Terminate TLS in a reverse proxy in front of multi-worker pools.

Related