Files
bun.sh/docs/guides/websocket/simple.mdx
Michael H 87eca6bbc7 docs: re-apply many recent changes that somehow aren't present (#24719)
lots of recent changes aren't present, so this reapplies them
2025-11-16 19:23:01 +11:00

39 lines
1023 B
Plaintext

---
title: Build a simple WebSocket server
sidebarTitle: Simple server
mode: center
---
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 server.ts icon="/icons/typescript.svg"
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: {
// TypeScript: specify the type of ws.data like this
data: {} as { authToken: string },
// 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}`);
```