aboutsummaryrefslogtreecommitdiff
path: root/docs/guides/websocket/context.md
diff options
context:
space:
mode:
authorGravatar Colin McDonnell <colinmcd94@gmail.com> 2023-07-26 14:59:39 -0700
committerGravatar GitHub <noreply@github.com> 2023-07-26 14:59:39 -0700
commit4c89c60867591b50e0b31bf5009fd5ad6a3cebe1 (patch)
treefc1d2f47309c0345a850933496baa40d94bfdcbb /docs/guides/websocket/context.md
parent6bfee02301a2e2a0b79339974af0445eb5a2688f (diff)
downloadbun-4c89c60867591b50e0b31bf5009fd5ad6a3cebe1.tar.gz
bun-4c89c60867591b50e0b31bf5009fd5ad6a3cebe1.tar.zst
bun-4c89c60867591b50e0b31bf5009fd5ad6a3cebe1.zip
Add files (#3826)
Diffstat (limited to 'docs/guides/websocket/context.md')
-rw-r--r--docs/guides/websocket/context.md72
1 files changed, 72 insertions, 0 deletions
diff --git a/docs/guides/websocket/context.md b/docs/guides/websocket/context.md
new file mode 100644
index 000000000..9e387d685
--- /dev/null
+++ b/docs/guides/websocket/context.md
@@ -0,0 +1,72 @@
+---
+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()](/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<{ socketId: number }>({
+ fetch(req, server) {
+ const success = server.upgrade(req, {
+ data: {
+ socketId: Math.random(),
+ },
+ });
+ if (success) return undefined;
+
+ // handle HTTP request normally
+ // ...
+ },
+ websocket: {
+ // define websocket handlers
+ async message(ws, message) {
+ // the contextual dta 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;
+};
+
+// TypeScript: specify the type of `data`
+Bun.serve<WebSocketData>({
+ 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(ws.data.authToken);
+
+ const upgraded = server.upgrade(req, {
+ data: {
+ createdAt: Date.now(),
+ token: cookies["X-Token"],
+ userId: user.id,
+ },
+ });
+
+ if (upgraded) return undefined;
+ },
+ websocket: {
+ async message(ws, message) {
+ // save the message to a database
+ await saveMessageToDatabase({
+ message: String(message),
+ userId: ws.data.userId,
+ });
+ },
+ },
+});
+```