|
| 1 | +# WebSocket Middleware |
| 2 | + |
| 3 | +> **Reference**: [Deno.upgradeWebSocket API Documentation](https://docs.deno.com/api/deno/~/Deno.upgradeWebSocket) |
| 4 | +
|
| 5 | +This middleware handles WebSocket upgrades and provides event handling for real-time communication with explicit path listeners and error management. |
| 6 | + |
| 7 | +## Basic Usage |
| 8 | + |
| 9 | +Apply WebSocket middleware using Deserve's built-in middleware: |
| 10 | + |
| 11 | +```typescript |
| 12 | +import { Router } from '@neabyte/deserve' |
| 13 | + |
| 14 | +const router = new Router() |
| 15 | + |
| 16 | +// Apply WebSocket with explicit listener path |
| 17 | +router.apply([['websocket', { |
| 18 | + listener: '/ws', // Matches /ws/* prefixes |
| 19 | + onConnect: (socket, req) => console.log('Client connected'), |
| 20 | + onMessage: (socket, event, req) => { |
| 21 | + if (event.data === 'ping') { |
| 22 | + socket.send('pong') |
| 23 | + } |
| 24 | + } |
| 25 | +}]]) |
| 26 | + |
| 27 | +router.serve(8000) |
| 28 | +``` |
| 29 | + |
| 30 | +## Multiple WebSocket Endpoints |
| 31 | + |
| 32 | +**Important:** Deserve only processes the last WebSocket middleware pipeline. To support multiple endpoints, combine logic into a single middleware with path-based routing: |
| 33 | + |
| 34 | +```typescript |
| 35 | +router.apply([['websocket', { |
| 36 | + listener: '/', // Matches /* prefixes, i.e. /ws/chat, /api/ws, etc |
| 37 | + onConnect: (socket, req) => { |
| 38 | + const url = new URL(req.url) |
| 39 | + console.log(`WebSocket connected to ${url.pathname}!`) |
| 40 | + if (url.pathname === '/ws/chat') { |
| 41 | + socket.send(JSON.stringify({ type: 'connected', message: 'Welcome to chat!' })) |
| 42 | + } else if (url.pathname === '/ws/notifications') { |
| 43 | + socket.send(JSON.stringify({ type: 'connected', message: 'Notification service ready' })) |
| 44 | + } else if (url.pathname === '/api/ws') { |
| 45 | + socket.send(JSON.stringify({ type: 'api_ready' })) |
| 46 | + } |
| 47 | + }, |
| 48 | + onMessage: (socket, event, req) => { |
| 49 | + const url = new URL(req.url) |
| 50 | + const data = JSON.parse(event.data) |
| 51 | + if (url.pathname === '/ws/chat') { |
| 52 | + // Handle chat messages |
| 53 | + if (data.type === 'ping') { |
| 54 | + socket.send(JSON.stringify({ type: 'pong' })) |
| 55 | + } else if (data.type === 'message') { |
| 56 | + socket.send(JSON.stringify({ |
| 57 | + type: 'message', |
| 58 | + content: data.content, |
| 59 | + timestamp: new Date().toISOString(), |
| 60 | + user: data.user || 'anonymous' |
| 61 | + })) |
| 62 | + } |
| 63 | + } else if (url.pathname === '/ws/notifications') { |
| 64 | + // Handle notification subscriptions |
| 65 | + if (data.type === 'subscribe') { |
| 66 | + socket.send(JSON.stringify({ |
| 67 | + type: 'subscribed', |
| 68 | + topic: data.topic, |
| 69 | + timestamp: new Date().toISOString() |
| 70 | + })) |
| 71 | + } |
| 72 | + } else if (url.pathname === '/api/ws') { |
| 73 | + // Handle API messages |
| 74 | + socket.send(JSON.stringify({ |
| 75 | + type: 'api_response', |
| 76 | + data: data, |
| 77 | + timestamp: new Date().toISOString() |
| 78 | + })) |
| 79 | + } |
| 80 | + }, |
| 81 | + onDisconnect: (socket, req) => { |
| 82 | + const url = new URL(req.url) |
| 83 | + console.log(`WebSocket disconnected from ${url.pathname}!`) |
| 84 | + } |
| 85 | +}]]) |
| 86 | +``` |
| 87 | + |
| 88 | +## WebSocket Options |
| 89 | + |
| 90 | +### `listener` (Required) |
| 91 | +Specify the path to listen for WebSocket upgrades: |
| 92 | + |
| 93 | +```typescript |
| 94 | +listener: '/ws' // Matches /ws and /ws/anything |
| 95 | +listener: '/api/ws' // Matches /api/ws and /api/ws/anything |
| 96 | +listener: '/ws/chat' // Matches /ws/chat and /ws/chat/anything |
| 97 | +``` |
| 98 | + |
| 99 | +### `onConnect` |
| 100 | +Handle new WebSocket connections: |
| 101 | + |
| 102 | +```typescript |
| 103 | +onConnect: (socket, req) => { |
| 104 | + console.log('New client connected') |
| 105 | + socket.send('Welcome to the server!') |
| 106 | +} |
| 107 | +``` |
| 108 | + |
| 109 | +### `onMessage` |
| 110 | +Handle incoming WebSocket messages: |
| 111 | + |
| 112 | +```typescript |
| 113 | +onMessage: (socket, event, req) => { |
| 114 | + const data = JSON.parse(event.data) |
| 115 | + switch (data.type) { |
| 116 | + case 'ping': |
| 117 | + socket.send(JSON.stringify({ type: 'pong' })) |
| 118 | + break |
| 119 | + case 'broadcast': |
| 120 | + // Broadcast to all connected clients |
| 121 | + break |
| 122 | + } |
| 123 | +} |
| 124 | +``` |
| 125 | + |
| 126 | +### `onDisconnect` |
| 127 | +Handle WebSocket disconnections: |
| 128 | + |
| 129 | +```typescript |
| 130 | +onDisconnect: (socket, req) => { |
| 131 | + console.log('Client disconnected') |
| 132 | + // Clean up resources |
| 133 | +} |
| 134 | +``` |
| 135 | + |
| 136 | +### `onError` |
| 137 | +Handle WebSocket errors: |
| 138 | + |
| 139 | +```typescript |
| 140 | +onError: (socket, event, req) => { |
| 141 | + console.error('WebSocket error:', event) |
| 142 | + // Handle error gracefully |
| 143 | +} |
| 144 | +``` |
| 145 | + |
| 146 | +## Client-Side Usage |
| 147 | + |
| 148 | +Connect to WebSocket endpoints from JavaScript: |
| 149 | + |
| 150 | +```javascript |
| 151 | +// Connect to chat WebSocket |
| 152 | +const chatSocket = new WebSocket('ws://localhost:8000/ws/chat') |
| 153 | + |
| 154 | +// Handle connection open |
| 155 | +chatSocket.onopen = () => { |
| 156 | + console.log('Connected to chat') |
| 157 | +} |
| 158 | + |
| 159 | +// Handle incoming messages |
| 160 | +chatSocket.onmessage = (event) => { |
| 161 | + const data = JSON.parse(event.data) |
| 162 | + console.log('Received:', data) |
| 163 | +} |
| 164 | + |
| 165 | +// Handle connection close |
| 166 | +chatSocket.onclose = () => { |
| 167 | + console.log('Disconnected from chat') |
| 168 | +} |
| 169 | + |
| 170 | +// Send a message |
| 171 | +chatSocket.send(JSON.stringify({ |
| 172 | + type: 'chat', |
| 173 | + content: 'Hello, world!' |
| 174 | +})) |
| 175 | +``` |
| 176 | + |
| 177 | +## Best Practices |
| 178 | + |
| 179 | +1. **Use explicit listeners** - Always specify the `listener` path for clarity |
| 180 | +2. **Handle JSON parsing** - Wrap JSON.parse in try-catch blocks |
| 181 | +3. **Validate message types** - Check message structure before processing |
| 182 | +4. **Clean up resources** - Use `onDisconnect` to clean up connections |
| 183 | +5. **Error handling** - Implement `onError` for graceful error handling |
| 184 | +6. **Message validation** - Validate incoming message structure |
| 185 | +7. **Connection limits** - Consider implementing connection limits for production |
| 186 | + |
| 187 | +## Error Handling |
| 188 | + |
| 189 | +WebSocket upgrade failures throw errors handled by Deserve's error middleware: |
| 190 | + |
| 191 | +```typescript |
| 192 | +// If WebSocket upgrade fails, the middleware throws an error |
| 193 | +throw new Error(`WebSocket upgrade failed: ${errorMessage}`) |
| 194 | +``` |
| 195 | + |
| 196 | +## Troubleshooting |
| 197 | + |
| 198 | +### Common Issues |
| 199 | + |
| 200 | +**WebSocket connection fails:** |
| 201 | +- Check if `listener` path matches client connection URL |
| 202 | +- Verify WebSocket upgrade headers are present |
| 203 | +- Ensure server is running and accessible |
| 204 | + |
| 205 | +**Messages not received:** |
| 206 | +- Check `onMessage` handler implementation |
| 207 | +- Verify JSON message format |
| 208 | +- Check for errors in `onError` handler |
| 209 | + |
| 210 | +**Connection drops unexpectedly:** |
| 211 | +- Check network connectivity |
| 212 | +- Implement proper `onError` handling |
| 213 | +- Verify WebSocket protocol compatibility |
| 214 | + |
| 215 | +**Multiple endpoints not working:** |
| 216 | +- **Deserve WebSocket middleware** - combine all endpoints into one middleware |
| 217 | +- Use path-based routing with `url.pathname` to handle different endpoints |
| 218 | +- Check for path conflicts in your routing logic |
| 219 | + |
| 220 | +## Next Steps |
| 221 | + |
| 222 | +- [Global Middleware](/middleware/global) - Cross-cutting functionality |
| 223 | +- [Route-Specific Middleware](/middleware/route-specific) - Targeted middleware |
| 224 | +- [CORS Middleware](/middleware/cors) - Cross-origin request handling |
0 commit comments