Files
bun.sh/docs/guides/websocket/context.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

78 lines
1.9 KiB
Markdown

---
name: Set per-socket contextual data on a WebSocket
---
When building a WebSocket server, it's typically necessary to store some identifying information or context associated with each connected client.
With [Bun.serve()](https://bun.com/docs/api/websockets#contextual-data), this "contextual data" is set when the connection is initially upgraded by passing a `data` parameter in the `server.upgrade()` call.
```ts
Bun.serve({
fetch(req, server) {
const success = server.upgrade(req, {
data: {
socketId: Math.random(),
},
});
if (success) return undefined;
// handle HTTP request normally
// ...
},
websocket: {
// TypeScript: specify the type of ws.data like this
data: {} as { socketId: number },
// define websocket handlers
async message(ws, message) {
// the contextual data is available as the `data` property
// on the WebSocket instance
console.log(`Received ${message} from ${ws.data.socketId}}`);
},
},
});
```
---
It's common to read cookies/headers from the incoming request to identify the connecting client.
```ts
type WebSocketData = {
createdAt: number;
token: string;
userId: string;
};
Bun.serve({
async fetch(req, server) {
// use a library to parse cookies
const cookies = parseCookies(req.headers.get("Cookie"));
const token = cookies["X-Token"];
const user = await getUserFromToken(token);
const upgraded = server.upgrade(req, {
data: {
createdAt: Date.now(),
token: cookies["X-Token"],
userId: user.id,
},
});
if (upgraded) return undefined;
},
websocket: {
// TypeScript: specify the type of ws.data like this
data: {} as WebSocketData,
async message(ws, message) {
// save the message to a database
await saveMessageToDatabase({
message: String(message),
userId: ws.data.userId,
});
},
},
});
```