skills/bun-guides-websocket-context/SKILL.md
Set per-socket contextual data on a WebSocket
npx skillsauth add jarle/bun-skills Bun Set per-socket contextual data on a WebSocketInstall this skill globally with one command. Works with Claude Code, Cursor, and Windsurf.
3 of 9 scanners reported clean
Some scanners were skipped, did not run, or reported a non-clean status. Review each row below.
When building a WebSocket server, it's typically necessary to store some identifying information or context associated with each connected client.
With Bun.serve(), this "contextual data" is set when the connection is initially upgraded by passing a data parameter in the server.upgrade() call.
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.
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,
});
},
},
});
development
Using TypeScript with Bun, including type definitions and compiler options
development
Learn how to write tests using Bun's Jest-compatible API with support for async tests, timeouts, and various test modifiers
testing
Learn how to use snapshot testing in Bun to save and compare output between test runs
testing
Learn about Bun test's runtime integration, environment variables, timeouts, and error handling