feat: add first-class WebSocket support via ctx.upgrade() and app.ws() (#3774)

## Summary

- **`ctx.upgrade()`** on the `Context` class with two overloads:
- **Bare mode**: `ctx.upgrade()` or `ctx.upgrade(options)` returns `{
socket, response }` for manual event wiring
- **Managed mode**: `ctx.upgrade(handlers)` accepts `{ open, message,
close, error }` and returns the upgrade `Response` directly
- **`app.ws(path, handlers, options?)`** shorthand that registers a GET
route with automatic WebSocket upgrade (managed mode only)
- Both support `idleTimeout` and `protocol` options forwarded to
`Deno.upgradeWebSocket()`
- Throws `HttpError(400)` on non-WebSocket requests
- Case-insensitive `Upgrade` header check per RFC 6455 §4.2.1
- Exports `WebSocketHandlers` and `WebSocketUpgradeOptions` types from
`fresh`
- Full documentation page with examples for managed mode, bare mode,
broadcast chat, and client-side usage
This commit is contained in:
Bartek Iwańczuk
2026-04-22 19:17:43 +02:00
committed by GitHub
parent 49c4be1ac6
commit 0ab5a2ab28
8 changed files with 605 additions and 25 deletions
+23 -1
View File
@@ -3,7 +3,11 @@ import { trace } from "@opentelemetry/api";
import { DENO_DEPLOYMENT_ID } from "@fresh/build-id";
import * as colors from "@std/fmt/colors";
import type { MaybeLazyMiddleware, Middleware } from "./middlewares/mod.ts";
import { Context } from "./context.ts";
import {
Context,
type WebSocketHandlers,
type WebSocketUpgradeOptions,
} from "./context.ts";
import { mergePath, type Method, UrlPatternRouter } from "./router.ts";
import type { FreshConfig, ResolvedFreshConfig } from "./config.ts";
import type { BuildCache } from "./build_cache.ts";
@@ -301,6 +305,24 @@ export class App<State> {
return this;
}
/**
* Register a WebSocket endpoint at the specified path.
*
* ```ts
* app.ws("/chat", {
* open(socket) { console.log("connected"); },
* message(socket, event) { socket.send(event.data); },
* });
* ```
*/
ws(
path: string,
handlers: WebSocketHandlers,
options?: WebSocketUpgradeOptions,
): this {
return this.get(path, (ctx) => ctx.upgrade(handlers, options));
}
/**
* Add middlewares for all HTTP verbs at the specified path.
*/
+133
View File
@@ -11,6 +11,7 @@ import { jsxTemplate } from "preact/jsx-runtime";
import { SpanStatusCode } from "@opentelemetry/api";
import type { ResolvedFreshConfig } from "./config.ts";
import type { BuildCache } from "./build_cache.ts";
import { HttpError } from "./error.ts";
import type { LayoutConfig } from "./types.ts";
import {
FreshScripts,
@@ -31,6 +32,59 @@ import { renderToString } from "preact-render-to-string";
const ENCODER = new TextEncoder();
/**
* Event handlers for a WebSocket connection upgraded via
* {@linkcode Context.upgrade}.
*/
export interface WebSocketHandlers {
/** Called when the WebSocket connection is established. */
open?(socket: WebSocket): void;
/** Called when a message is received. */
message?(socket: WebSocket, event: MessageEvent): void;
/** Called when the connection is closed. */
close?(socket: WebSocket, code: number, reason: string): void;
/** Called when an error occurs. */
error?(socket: WebSocket, event: Event | ErrorEvent): void;
}
/**
* Options forwarded to `Deno.upgradeWebSocket()`.
*/
export interface WebSocketUpgradeOptions {
/** Automatically close the connection if no ping is received
* within this many seconds. Default: 120. */
idleTimeout?: number;
/** The WebSocket sub-protocol to negotiate. */
protocol?: string;
}
/**
* Duck-type check: treats the argument as managed-mode handlers when at least
* one of the handler keys (`open`, `message`, `close`, `error`) is a
* function. This works because {@link WebSocketUpgradeOptions} only has
* non-function fields (`idleTimeout`, `protocol`), so a plain options object
* will never match.
*
* **Edge case:** an empty object `{}` satisfies `WebSocketHandlers` at the
* type level (all keys are optional) but returns `false` here, so
* `ctx.upgrade({})` enters bare mode. This is harmless — an empty handlers
* object would be a no-op in managed mode anyway.
*
* If `WebSocketUpgradeOptions` ever gains a function-valued field whose name
* collides with a handler key, this guard must be updated (or replaced with a
* branded/sentinel approach).
*/
function isWebSocketHandlers(
value: unknown,
): value is WebSocketHandlers {
if (typeof value !== "object" || value === null) return false;
const v = value as Record<string, unknown>;
return typeof v.open === "function" ||
typeof v.message === "function" ||
typeof v.close === "function" ||
typeof v.error === "function";
}
export interface Island {
file: string;
name: string;
@@ -489,6 +543,85 @@ export class Context<State> {
return new Response(body, init);
}
/**
* Upgrade the request to a WebSocket connection.
*
* **Bare mode** — returns the socket and the upgrade response.
* Wire events yourself and return `response` from your handler:
*
* ```ts
* app.get("/ws", (ctx) => {
* const { socket, response } = ctx.upgrade();
* socket.onmessage = (e) => socket.send(e.data);
* return response;
* });
* ```
*
* **Managed mode** — pass handlers and receive the response directly:
*
* ```ts
* app.get("/ws", (ctx) =>
* ctx.upgrade({
* message(socket, event) {
* socket.send(event.data);
* },
* })
* );
* ```
*/
upgrade(
options?: WebSocketUpgradeOptions,
): { socket: WebSocket; response: Response };
upgrade(
handlers: WebSocketHandlers,
options?: WebSocketUpgradeOptions,
): Response;
upgrade(
handlersOrOptions?: WebSocketHandlers | WebSocketUpgradeOptions,
maybeOptions?: WebSocketUpgradeOptions,
): { socket: WebSocket; response: Response } | Response {
let handlers: WebSocketHandlers | undefined;
let options: WebSocketUpgradeOptions | undefined;
if (isWebSocketHandlers(handlersOrOptions)) {
handlers = handlersOrOptions;
options = maybeOptions;
} else {
options = handlersOrOptions;
}
if (this.req.headers.get("upgrade")?.toLowerCase() !== "websocket") {
throw new HttpError(400, "Expected a WebSocket upgrade request");
}
const { socket, response } = Deno.upgradeWebSocket(this.req, options);
if (handlers === undefined) {
return { socket, response };
}
if (handlers.open) {
socket.addEventListener("open", () => handlers.open!(socket));
}
if (handlers.message) {
socket.addEventListener(
"message",
(ev) => handlers.message!(socket, ev),
);
}
if (handlers.close) {
socket.addEventListener(
"close",
(ev) => handlers.close!(socket, ev.code, ev.reason),
);
}
if (handlers.error) {
socket.addEventListener("error", (ev) => handlers.error!(socket, ev));
}
return response;
}
}
function getHeadersFromInit(init?: ResponseInit) {
+7 -1
View File
@@ -20,7 +20,13 @@ export {
} from "./middlewares/ip_filter.ts";
export { csp, type CSPOptions } from "./middlewares/csp.ts";
export type { FreshConfig, ResolvedFreshConfig } from "./config.ts";
export type { Context, FreshContext, Island } from "./context.ts";
export type {
Context,
FreshContext,
Island,
WebSocketHandlers,
WebSocketUpgradeOptions,
} from "./context.ts";
export { createDefine, type Define } from "./define.ts";
export type { Method } from "./router.ts";
export { HttpError } from "./error.ts";
+276
View File
@@ -0,0 +1,276 @@
import { expect } from "@std/expect";
import { App } from "./app.ts";
import { FakeServer } from "./test_utils.ts";
Deno.test("ctx.upgrade() - throws 400 on non-WebSocket request", async () => {
const app = new App()
.get("/ws", (ctx) => ctx.upgrade({ message() {} }));
const server = new FakeServer(app.handler());
const res = await server.get("/ws");
expect(res.status).toEqual(400);
});
Deno.test("app.ws() - throws 400 on non-WebSocket request", async () => {
const app = new App()
.ws("/ws", { message() {} });
const server = new FakeServer(app.handler());
const res = await server.get("/ws");
expect(res.status).toEqual(400);
});
Deno.test("ctx.upgrade() - bare mode with options", async () => {
const app = new App()
.get("/ws", (ctx) => {
// Options-only call must return { socket, response } (bare mode),
// NOT a plain Response (managed mode).
const { socket, response } = ctx.upgrade({ protocol: "graphql-ws" });
socket.onmessage = (e) => socket.send(`bare-opts: ${e.data}`);
return response;
});
const ac = new AbortController();
const server = Deno.serve({
hostname: "127.0.0.1",
port: 0,
signal: ac.signal,
onListen: () => {},
}, app.handler());
const port = server.addr.port;
const ws = new WebSocket(`ws://127.0.0.1:${port}/ws`, "graphql-ws");
const received = new Promise<string>((resolve, reject) => {
ws.onmessage = (e) => resolve(e.data);
ws.onerror = (e) => reject(e);
});
ws.onopen = () => ws.send("hello");
const msg = await received;
expect(msg).toEqual("bare-opts: hello");
expect(ws.protocol).toEqual("graphql-ws");
ws.close();
ac.abort();
await server.finished;
});
Deno.test("ctx.upgrade() - managed echo", async () => {
const app = new App()
.get("/ws", (ctx) =>
ctx.upgrade({
message(socket, event) {
socket.send(`echo: ${event.data}`);
},
}));
const ac = new AbortController();
const server = Deno.serve({
hostname: "127.0.0.1",
port: 0,
signal: ac.signal,
onListen: () => {},
}, app.handler());
const port = server.addr.port;
const ws = new WebSocket(`ws://127.0.0.1:${port}/ws`);
const received = new Promise<string>((resolve, reject) => {
ws.onmessage = (e) => resolve(e.data);
ws.onerror = (e) => reject(e);
});
ws.onopen = () => ws.send("hello");
const msg = await received;
expect(msg).toEqual("echo: hello");
ws.close();
ac.abort();
await server.finished;
});
Deno.test("ctx.upgrade() - bare overload", async () => {
const app = new App()
.get("/ws", (ctx) => {
const { socket, response } = ctx.upgrade();
socket.onmessage = (e) => socket.send(`bare: ${e.data}`);
return response;
});
const ac = new AbortController();
const server = Deno.serve({
hostname: "127.0.0.1",
port: 0,
signal: ac.signal,
onListen: () => {},
}, app.handler());
const port = server.addr.port;
const ws = new WebSocket(`ws://127.0.0.1:${port}/ws`);
const received = new Promise<string>((resolve, reject) => {
ws.onmessage = (e) => resolve(e.data);
ws.onerror = (e) => reject(e);
});
ws.onopen = () => ws.send("hello");
const msg = await received;
expect(msg).toEqual("bare: hello");
ws.close();
ac.abort();
await server.finished;
});
Deno.test("app.ws() - echo shorthand", async () => {
const app = new App()
.ws("/ws", {
message(socket, event) {
socket.send(`ws: ${event.data}`);
},
});
const ac = new AbortController();
const server = Deno.serve({
hostname: "127.0.0.1",
port: 0,
signal: ac.signal,
onListen: () => {},
}, app.handler());
const port = server.addr.port;
const ws = new WebSocket(`ws://127.0.0.1:${port}/ws`);
const received = new Promise<string>((resolve, reject) => {
ws.onmessage = (e) => resolve(e.data);
ws.onerror = (e) => reject(e);
});
ws.onopen = () => ws.send("hello");
const msg = await received;
expect(msg).toEqual("ws: hello");
ws.close();
ac.abort();
await server.finished;
});
Deno.test("app.ws() - with options", async () => {
const app = new App()
.ws("/ws", {
message(socket, event) {
socket.send(`ws-opts: ${event.data}`);
},
}, { protocol: "graphql-ws" });
const ac = new AbortController();
const server = Deno.serve({
hostname: "127.0.0.1",
port: 0,
signal: ac.signal,
onListen: () => {},
}, app.handler());
const port = server.addr.port;
const ws = new WebSocket(`ws://127.0.0.1:${port}/ws`, "graphql-ws");
const received = new Promise<string>((resolve, reject) => {
ws.onmessage = (e) => resolve(e.data);
ws.onerror = (e) => reject(e);
});
ws.onopen = () => ws.send("hello");
const msg = await received;
expect(msg).toEqual("ws-opts: hello");
expect(ws.protocol).toEqual("graphql-ws");
ws.close();
ac.abort();
await server.finished;
});
Deno.test("ctx.upgrade() - error handler fires", async () => {
const errors: Event[] = [];
const errored = Promise.withResolvers<void>();
const app = new App()
.get("/ws", (ctx) =>
ctx.upgrade({
open(socket) {
// Force a protocol error by sending invalid close code
socket.close(1002, "trigger-error");
},
error(_socket, event) {
errors.push(event);
errored.resolve();
},
close() {
// Resolve if error doesn't fire — close always fires
errored.resolve();
},
}));
const ac = new AbortController();
const server = Deno.serve({
hostname: "127.0.0.1",
port: 0,
signal: ac.signal,
onListen: () => {},
}, app.handler());
const port = server.addr.port;
const ws = new WebSocket(`ws://127.0.0.1:${port}/ws`);
await new Promise<void>((resolve) => {
ws.onclose = () => resolve();
});
await errored.promise;
// The error handler wiring is verified by reaching here without hanging.
// Whether the error event actually fires depends on the runtime, so we
// just assert the handler was registered (the close fallback resolves
// the promise if error doesn't fire).
ac.abort();
await server.finished;
});
Deno.test("ctx.upgrade() - open and close handlers fire", async () => {
const events: string[] = [];
const closed = Promise.withResolvers<void>();
const app = new App()
.get("/ws", (ctx) =>
ctx.upgrade({
open() {
events.push("open");
},
close() {
events.push("close");
closed.resolve();
},
}));
const ac = new AbortController();
const server = Deno.serve({
hostname: "127.0.0.1",
port: 0,
signal: ac.signal,
onListen: () => {},
}, app.handler());
const port = server.addr.port;
const ws = new WebSocket(`ws://127.0.0.1:${port}/ws`);
await new Promise<void>((resolve) => {
ws.onopen = () => resolve();
});
ws.close();
await closed.promise;
expect(events).toEqual(["open", "close"]);
ac.abort();
await server.finished;
});