Files
bun.sh/docs/guides/websocket/simple.md
Alistair Smith b22e19baed [1.3] Bun.serve({ websocket }) types (#20918)
Co-authored-by: Claude Bot <claude-bot@bun.sh>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
2025-10-06 16:07:36 -07:00

34 lines
845 B
Markdown

---
name: Build a simple WebSocket server
---
Start a simple WebSocket server using [`Bun.serve`](https://bun.com/docs/api/http).
Inside `fetch`, we attempt to upgrade incoming `ws:` or `wss:` requests to WebSocket connections.
```ts
const server = Bun.serve({
fetch(req, server) {
const success = server.upgrade(req);
if (success) {
// Bun automatically returns a 101 Switching Protocols
// if the upgrade succeeds
return undefined;
}
// handle HTTP request normally
return new Response("Hello world!");
},
websocket: {
// this is called when a message is received
async message(ws, message) {
console.log(`Received ${message}`);
// send back a message
ws.send(`You said: ${message}`);
},
},
});
console.log(`Listening on ${server.hostname}:${server.port}`);
```