From 0ab5a2ab289689fda48d28c7ac7c2e679059306b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bartek=20Iwa=C5=84czuk?= Date: Wed, 22 Apr 2026 19:17:43 +0200 Subject: [PATCH] feat: add first-class WebSocket support via ctx.upgrade() and app.ws() (#3774) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## 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 --- docs/latest/examples/common-patterns.md | 25 +-- docs/latest/examples/index.md | 1 + docs/latest/examples/websockets.md | 162 ++++++++++++++ docs/toc.ts | 1 + packages/fresh/src/app.ts | 24 ++- packages/fresh/src/context.ts | 133 ++++++++++++ packages/fresh/src/mod.ts | 8 +- packages/fresh/src/websocket_test.ts | 276 ++++++++++++++++++++++++ 8 files changed, 605 insertions(+), 25 deletions(-) create mode 100644 docs/latest/examples/websockets.md create mode 100644 packages/fresh/src/websocket_test.ts diff --git a/docs/latest/examples/common-patterns.md b/docs/latest/examples/common-patterns.md index 0fe5d1e2..f14a3a9d 100644 --- a/docs/latest/examples/common-patterns.md +++ b/docs/latest/examples/common-patterns.md @@ -175,29 +175,8 @@ export const handler = define.handlers({ ## WebSockets -Fresh runs on Deno, so you can upgrade HTTP connections to WebSockets directly: - -```ts routes/api/ws.ts -import { define } from "@/utils.ts"; - -export const handler = define.handlers({ - GET(ctx) { - const { socket, response } = Deno.upgradeWebSocket(ctx.req); - - socket.onopen = () => { - console.log("Client connected"); - }; - socket.onmessage = (event) => { - socket.send(`Echo: ${event.data}`); - }; - socket.onclose = () => { - console.log("Client disconnected"); - }; - - return response; - }, -}); -``` +Fresh provides first-class WebSocket support via `ctx.upgrade()`. See the full +[WebSocket guide](/docs/examples/websockets) for all options. ## Subdomain routing diff --git a/docs/latest/examples/index.md b/docs/latest/examples/index.md index 957bbe20..f5a4b9f6 100644 --- a/docs/latest/examples/index.md +++ b/docs/latest/examples/index.md @@ -13,4 +13,5 @@ that you may like in your Fresh project. - [Sharing state between islands](./examples/sharing-state-between-islands) - [Active links](./examples/active-links) - [Session management](./examples/session-management) +- [WebSockets](./examples/websockets) - [Common Patterns](./examples/common-patterns) diff --git a/docs/latest/examples/websockets.md b/docs/latest/examples/websockets.md new file mode 100644 index 00000000..cac0bc85 --- /dev/null +++ b/docs/latest/examples/websockets.md @@ -0,0 +1,162 @@ +--- +description: | + Add real-time WebSocket endpoints to your Fresh app with ctx.upgrade() or app.ws(). +--- + +Fresh provides built-in helpers for upgrading HTTP connections to WebSockets. +There are two main approaches depending on your use case. + +## Quick start with `app.ws()` + +The simplest way to add a WebSocket endpoint: + +```ts main.ts +import { App } from "fresh"; + +const app = new App() + .ws("/ws", { + open(socket) { + console.log("Client connected"); + }, + message(socket, event) { + socket.send(`Echo: ${event.data}`); + }, + close(socket, code, reason) { + console.log("Client disconnected", code, reason); + }, + }); +``` + +`app.ws(path, handlers)` registers a GET route that automatically upgrades the +request to a WebSocket connection and wires up your event handlers. + +## Using `ctx.upgrade()` in route handlers + +For file-based routes or when you need more control, use `ctx.upgrade()` inside +a GET handler. + +### Managed mode + +Pass an event handlers object and receive the upgrade `Response` directly: + +```ts routes/api/ws.ts +import { define } from "@/utils.ts"; + +export const handlers = define.handlers({ + GET(ctx) { + return ctx.upgrade({ + open(socket) { + console.log("Client connected"); + }, + message(socket, event) { + socket.send(`Echo: ${event.data}`); + }, + close(socket, code, reason) { + console.log("Disconnected", code, reason); + }, + error(socket, event) { + console.error("WebSocket error", event); + }, + }); + }, +}); +``` + +### Bare mode + +Call `ctx.upgrade()` without arguments to get the raw `WebSocket` object. This +is useful when you need to store the socket in a shared structure like a chat +room or pub/sub registry: + +```ts routes/api/chat.ts +import { define } from "@/utils.ts"; + +const clients = new Set(); + +export const handlers = define.handlers({ + GET(ctx) { + const { socket, response } = ctx.upgrade(); + + socket.onopen = () => { + clients.add(socket); + }; + socket.onmessage = (event) => { + // Broadcast to all connected clients + for (const client of clients) { + if (client.readyState === WebSocket.OPEN) { + client.send(event.data); + } + } + }; + socket.onclose = () => { + clients.delete(socket); + }; + + return response; + }, +}); +``` + +## Upgrade options + +Both modes accept an options object to configure the underlying WebSocket: + +```ts +// Managed mode — pass handlers first, then options +ctx.upgrade(handlers, { + idleTimeout: 60, // close if no ping received within 60s (default: 120) + protocol: "graphql-ws", // sub-protocol to negotiate +}); + +// Bare mode — pass options without handlers to get the raw socket back +const { socket, response } = ctx.upgrade({ idleTimeout: 60 }); +``` + +> **How does Fresh tell the two calls apart?** The first argument is treated as +> managed-mode handlers when it contains at least one function-valued handler +> key (`open`, `message`, `close`, or `error`). A plain options object only has +> non-function fields (`idleTimeout`, `protocol`), so it always enters bare +> mode. + +The same options can be passed to `app.ws()`: + +```ts +app.ws("/ws", handlers, { idleTimeout: 60 }); +``` + +> `app.ws()` always uses managed mode. For bare-mode access to the raw socket, +> use `app.get()` with `ctx.upgrade()` instead. + +## Error handling + +If a non-WebSocket request hits a WebSocket route, `ctx.upgrade()` throws an +`HttpError(400)` with the message "Expected a WebSocket upgrade request". This +is handled automatically by Fresh's error pipeline and returns a 400 response. + +## Handler reference + +All handler callbacks are optional: + +| Callback | Arguments | Description | +| --------- | ------------------------ | ---------------------------------------------------- | +| `open` | `(socket)` | Connection established | +| `message` | `(socket, event)` | Message received (`event.data` contains the payload) | +| `close` | `(socket, code, reason)` | Connection closed | +| `error` | `(socket, event)` | Error occurred on the connection | + +## Client-side example + +Connect from the browser: + +```ts +const protocol = location.protocol === "https:" ? "wss:" : "ws:"; +const ws = new WebSocket(`${protocol}//${location.host}/ws`); + +ws.onopen = () => { + ws.send("Hello from the client!"); +}; + +ws.onmessage = (event) => { + console.log("Received:", event.data); +}; +``` diff --git a/docs/toc.ts b/docs/toc.ts index ae8ac560..15c3937c 100644 --- a/docs/toc.ts +++ b/docs/toc.ts @@ -107,6 +107,7 @@ const toc: RawTableOfContents = { ], ["active-links", "Active links", "link:latest"], ["session-management", "Session management", "link:latest"], + ["websockets", "WebSockets", "link:latest"], ["common-patterns", "Common Patterns", "link:latest"], ], }, diff --git a/packages/fresh/src/app.ts b/packages/fresh/src/app.ts index 90aac96b..c5910075 100644 --- a/packages/fresh/src/app.ts +++ b/packages/fresh/src/app.ts @@ -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 { 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. */ diff --git a/packages/fresh/src/context.ts b/packages/fresh/src/context.ts index 782beb2a..3c2d9c07 100644 --- a/packages/fresh/src/context.ts +++ b/packages/fresh/src/context.ts @@ -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; + 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 { 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) { diff --git a/packages/fresh/src/mod.ts b/packages/fresh/src/mod.ts index 0798a2bb..58ed6019 100644 --- a/packages/fresh/src/mod.ts +++ b/packages/fresh/src/mod.ts @@ -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"; diff --git a/packages/fresh/src/websocket_test.ts b/packages/fresh/src/websocket_test.ts new file mode 100644 index 00000000..01e7e7b5 --- /dev/null +++ b/packages/fresh/src/websocket_test.ts @@ -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((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((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((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((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((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(); + + 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((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(); + + 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((resolve) => { + ws.onopen = () => resolve(); + }); + ws.close(); + + await closed.promise; + expect(events).toEqual(["open", "close"]); + + ac.abort(); + await server.finished; +});