WebSocket
Add real-time communication to your Bun applications with TezX. This middleware enables native WebSocket support, full event handling, and seamless integration with your routes.
Import
import { upgradeWebSocket, wsHandlers } from "tezx/ws";Types
type WebSocketEvent = {
open?: (ws: WebSocket, ctx?: Context) => void;
message?: (ws: WebSocket, data: string | Buffer | ArrayBuffer) => void;
close?: (ws: WebSocket, info: { code: number; reason: string }) => void;
ping?: (ws: WebSocket, data: Buffer) => void;
pong?: (ws: WebSocket, data: Buffer) => void;
drain?: (ws: WebSocket) => void;
};
type WebSocketCallback = (ctx: Context) => WebSocketEvent;
type WebSocketOptions = {
onUpgradeError?: (err: Error, ctx: Context) => HttpBaseResponse;
};Basic Usage
app.use(
"/chat",
upgradeWebSocket((ctx) => ({
open(ws) { console.log("Connected"); },
message(ws, data) { ws.send(`Echo: ${data}`); },
close(ws, { code, reason }) { console.log("Closed", code, reason); },
}))
);Bun Server Setup
Bun.serve({
port: 3000,
fetch: app.serve,
websocket: wsHandlers()
});Upgrade Error Handling
app.use(
"/chat",
upgradeWebSocket((ctx) => ({
open(ws) { console.log("Connected"); }
}), {
onUpgradeError: (err, ctx) => ctx.text("Upgrade failed: " + err.message, 400),
})
);Advanced Events
message(ws, data) { ws.send("Hello"); },
ping(ws, buffer) { console.log("Ping:", buffer); },
pong(ws, buffer) { console.log("Pong:", buffer); },
drain(ws) { console.log("Backpressure relieved"); }xssProtection
The xssProtection middleware adds HTTP headers to protect against Cross-Site Scripting (XSS) attacks. It sets the X-XSS-Protection header and optionally a fallback Content-Security-Policy (CSP) for enhanced security.
Route Registry
TezX provides a flexible router system to register and manage routes with middlewares and callback handlers.