|
| 1 | +# Bun WebSocket Router |
| 2 | + |
| 3 | +A type-safe WebSocket router for Bun with Zod-based message validation. Route WebSocket messages to handlers based on message type with full TypeScript support. |
| 4 | + |
| 5 | +### Key Features |
| 6 | + |
| 7 | +- **Type-safe messaging**: Built-in validation using Zod schemas |
| 8 | +- **Simple API**: Intuitive routing system for WebSocket messages |
| 9 | +- **Performance**: Leverages Bun's native WebSocket implementation |
| 10 | +- **Flexible**: Works with any Bun server setup, including Hono |
| 11 | +- **Room support**: Easily group clients and broadcast messages |
| 12 | +- **Lightweight**: Minimal dependencies for fast startup |
| 13 | + |
| 14 | +Perfect for real-time applications like chat systems, live dashboards, multiplayer games, and notification services. |
| 15 | + |
| 16 | +## Installation |
| 17 | + |
| 18 | +```bash |
| 19 | +bun add bun-ws-router zod |
| 20 | +``` |
| 21 | + |
| 22 | +## Getting Started |
| 23 | + |
| 24 | +The following example demonstrates how to set up a Bun server with both (RESTful) HTTP and WebSocket routers. |
| 25 | + |
| 26 | +```ts |
| 27 | +import { Hono } from "hono"; |
| 28 | +import { WebSocketRouter } from "bun-ws-router"; |
| 29 | +import { exampleRouter } from "./example"; |
| 30 | + |
| 31 | +// HTTP router |
| 32 | +const app = new Hono(); |
| 33 | +app.get("/", (c) => c.text("Welcome to Hono!")); |
| 34 | + |
| 35 | +// WebSocket router |
| 36 | +const ws = new WebSocketRouter(); |
| 37 | +ws.addRoutes(exampleRouter); // Add routes from another file |
| 38 | + |
| 39 | +Bun.serve({ |
| 40 | + port: 3000, |
| 41 | + |
| 42 | + fetch(req, server) { |
| 43 | + const url = new URL(req.url); |
| 44 | + |
| 45 | + // Handle WebSocket upgrade requests |
| 46 | + if (url.pathname === "/ws") { |
| 47 | + return ws.upgrade(req, { |
| 48 | + server, |
| 49 | + }); |
| 50 | + } |
| 51 | + |
| 52 | + // Handle regular HTTP requests |
| 53 | + return app.fetch(req, { server }); |
| 54 | + }, |
| 55 | + |
| 56 | + // Handle WebSocket connections |
| 57 | + websocket: ws.websocket, |
| 58 | +}); |
| 59 | + |
| 60 | +console.log(`WebSocket server listening on ws://localhost:3000/ws`); |
| 61 | +``` |
| 62 | + |
| 63 | +## How to handle authentication |
| 64 | + |
| 65 | +You can handle authentication by checking the `Authorization` header for a JWT token or any other authentication method you prefer. The following example demonstrates how to verify a JWT token and pass the user information to the WebSocket router. |
| 66 | + |
| 67 | +```ts |
| 68 | +import { WebSocketRouter } from "bun-ws-router"; |
| 69 | +import { DecodedIdToken } from "firebase-admin/auth"; |
| 70 | +import { verifyIdToken } from "./auth"; // Your authentication logic |
| 71 | + |
| 72 | +type Meta = { |
| 73 | + user?: DecodedIdToken | null; |
| 74 | +}; |
| 75 | + |
| 76 | +// WebSocket router |
| 77 | +const ws = new WebSocketRouter<Meta>(); |
| 78 | + |
| 79 | +Bun.serve({ |
| 80 | + port: 3000, |
| 81 | + |
| 82 | + async fetch(req, server) { |
| 83 | + const url = new URL(req.url); |
| 84 | + |
| 85 | + // Check if the user is authenticated |
| 86 | + const user = await verifyToken(req); |
| 87 | + |
| 88 | + // Handle WebSocket upgrade requests |
| 89 | + if (url.pathname === "/ws") { |
| 90 | + return ws.upgrade(req, { |
| 91 | + server, |
| 92 | + data: { user }, |
| 93 | + }); |
| 94 | + } |
| 95 | + |
| 96 | + // Handle regular HTTP requests |
| 97 | + return await app.fetch(req, { server, user }); |
| 98 | + }, |
| 99 | + |
| 100 | + // Handle WebSocket connections |
| 101 | + websocket: ws.websocket, |
| 102 | +}); |
| 103 | +``` |
| 104 | + |
| 105 | +The `verifyIdToken` function is a placeholder for your authentication logic which could use user ID token verification from `firebase-admin` or any other authentication library. |
| 106 | + |
| 107 | +## How to define message types |
| 108 | + |
| 109 | +You can define message types using the `messageSchema` function from `bun-ws-router`. This function takes a message type name such as `JOIN_ROOM`, `SEND_MESSAGE` etc. and a Zod schema for the message payload. The following example demonstrates how to define message types for a chat application. |
| 110 | + |
| 111 | +```ts |
| 112 | +import { messageSchema } from "bun-ws-router"; |
| 113 | +import { z } from "zod"; |
| 114 | + |
| 115 | +export const JoinRoom = messageSchema("JOIN_ROOM", { |
| 116 | + roomId: z.string(), |
| 117 | +}); |
| 118 | + |
| 119 | +export const UserJoined = messageSchema("USER_JOINED", { |
| 120 | + roomId: z.string(), |
| 121 | + userId: z.string(), |
| 122 | +}); |
| 123 | + |
| 124 | +export const UserLeft = messageSchema("USER_LEFT", { |
| 125 | + userId: z.string(), |
| 126 | +}); |
| 127 | + |
| 128 | +export const SendMessage = messageSchema("SEND_MESSAGE", { |
| 129 | + roomId: z.string(), |
| 130 | + message: z.string(), |
| 131 | +}); |
| 132 | +``` |
| 133 | + |
| 134 | +## How to define routes |
| 135 | + |
| 136 | +You can define routes using the `WebSocketRouter` instance methods: `onOpen`, `onMessage`, and `onClose`. |
| 137 | + |
| 138 | +```ts |
| 139 | +import { WebSocketRouter } from "bun-ws-router"; |
| 140 | +import { Meta, JoinRoom, UserJoined, SendMessage, UserLeft } from "./schema"; |
| 141 | + |
| 142 | +const ws = new WebSocketRouter<Meta>(); |
| 143 | + |
| 144 | +// Handle new connections |
| 145 | +ws.onOpen((c) => { |
| 146 | + console.log( |
| 147 | + `Client connected: ${c.ws.data.clientId}, User ID: ${c.ws.data.userId}` |
| 148 | + ); |
| 149 | + // You could send a welcome message here |
| 150 | +}); |
| 151 | + |
| 152 | +// Handle specific message types |
| 153 | +ws.onMessage(JoinRoom, (c) => { |
| 154 | + const { roomId } = c.payload; |
| 155 | + const userId = c.ws.data.userId || c.ws.data.clientId; // Use userId if available, else clientId |
| 156 | + c.ws.data.roomId = roomId; // Store room in connection data |
| 157 | + console.log(`User ${userId} joining room: ${roomId}`); |
| 158 | + |
| 159 | + // Example: Send confirmation back or broadcast to room |
| 160 | + // This requires implementing broadcast/room logic separately |
| 161 | + // c.send(UserJoined, { roomId, userId }); |
| 162 | +}); |
| 163 | + |
| 164 | +ws.onMessage(SendMessage, (c) => { |
| 165 | + const { message } = c.payload; |
| 166 | + const userId = c.ws.data.userId || c.ws.data.clientId; |
| 167 | + const roomId = c.ws.data.roomId; |
| 168 | + console.log(`Message in room ${roomId} from ${userId}: ${message}`); |
| 169 | + // Add logic to broadcast message to others in the room |
| 170 | +}); |
| 171 | + |
| 172 | +// Handle disconnections |
| 173 | +ws.onClose((c) => { |
| 174 | + const userId = c.ws.data.userId || c.ws.data.clientId; |
| 175 | + console.log(`Client disconnected: ${userId}, code: ${c.code}`); |
| 176 | + // Example: Notify others in the room the user left |
| 177 | + // This requires implementing broadcast/room logic separately |
| 178 | + // broadcast(c.ws.data.roomId, UserLeft, { userId }); |
| 179 | +}); |
| 180 | +``` |
| 181 | + |
| 182 | +**Note:** The `c.send(...)` function sends a message back to the _current_ client. |
| 183 | + |
| 184 | +## How to compose routes |
| 185 | + |
| 186 | +You can compose routes from different files into a single router. This is useful for organizing your code and keeping related routes together. |
| 187 | + |
| 188 | +```ts |
| 189 | +import { WebSocketRouter } from "bun-ws-router"; |
| 190 | +import { Meta } from "./schemas"; |
| 191 | +import { chatRoutes } from "./chat"; |
| 192 | +import { notificationRoutes } from "./notification"; |
| 193 | + |
| 194 | +const ws = new WebSocketRouter<Meta>(); |
| 195 | +ws.addRoutes(chatRoutes); |
| 196 | +ws.addRoutes(notificationRoutes); |
| 197 | +``` |
| 198 | + |
| 199 | +Where `chatRoutes` and `notificationRoutes` are other router instances defined in separate files. |
| 200 | + |
| 201 | +## Support |
| 202 | + |
| 203 | +Feel free to discuss any issues or suggestions on our [Discord](https://discord.com/invite/bSsv7XM) channel. We welcome contributions and feedback from the community. |
| 204 | + |
| 205 | +## Backers |
| 206 | + |
| 207 | +<a href="https://reactstarter.com/b/1"><img src="https://reactstarter.com/b/1.png" height="60" /></a> <a href="https://reactstarter.com/b/2"><img src="https://reactstarter.com/b/2.png" height="60" /></a> <a href="https://reactstarter.com/b/3"><img src="https://reactstarter.com/b/3.png" height="60" /></a> <a href="https://reactstarter.com/b/4"><img src="https://reactstarter.com/b/4.png" height="60" /></a> <a href="https://reactstarter.com/b/5"><img src="https://reactstarter.com/b/5.png" height="60" /></a> <a href="https://reactstarter.com/b/6"><img src="https://reactstarter.com/b/6.png" height="60" /></a> <a href="https://reactstarter.com/b/7"><img src="https://reactstarter.com/b/7.png" height="60" /></a> <a href="https://reactstarter.com/b/8"><img src="https://reactstarter.com/b/8.png" height="60" /></a> |
| 208 | + |
| 209 | +## License |
| 210 | + |
| 211 | +This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details. |
0 commit comments