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
+2 -23
View File
@@ -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
+1
View File
@@ -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)
+162
View File
@@ -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<WebSocket>();
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);
};
```
+1
View File
@@ -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"],
],
},