Skip to content
Open
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 72 additions & 2 deletions docs/1.guide/2.hooks.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ Crossws provides a cross-platform API to define WebSocket servers. An implementa
import { defineHooks } from "crossws";

const hooks = defineHooks({
upgrade(req) {
console.log(`[ws] upgrading ${req.url}...`)
upgrade(request) {
console.log(`[ws] upgrading ${request.url}...`)
return {
headers: {}
}
Expand All @@ -42,3 +42,73 @@ const hooks = defineHooks({
},
});
```

## Authentication

During the `upgrade` hook it is possible to authenticate the user before upgrading the connection. If the user is not authenticated, you can throw an error to prevent the connection from being upgraded.

```ts
import { defineHooks } from "crossws";

const authToken = "Bearer myToken123";

const hooks = defineHooks({
upgrade(request) {
const authHeader = request.headers.get("Authorization");

if (!authHeader || !authHeader.startsWith("Basic ")) {
return new Response("Unauthorized", {
status: 401,
headers: {
"WWW-Authenticate": 'Basic realm="Websocket Authentication", charset="UTF-8"'
}
});
}

const base64Credentials = authHeader.split(" ")[1];
const [username, password] = atob(base64Credentials).split(":");

if (username !== "myUsername" || password !== "myPassword") {
return new Response("Unauthorized", {
status: 401,
headers: {
"WWW-Authenticate": 'Basic realm="Websocket Authentication", charset="UTF-8"'
}
});
}

return {
headers: {} // Optionally return custom headers
};
},
});
```

## Context

You can store data in the `context` property of the `request` object during the `upgrade` hook or the `peer` object during the other hooks. This data will be shared in all hooks for the lifetime of the connection.

> [!NOTE]
> context can be volatile in some environments like `cloudflare-durable`

```ts
import { defineHooks } from "crossws";

const hooks = defineHooks({
upgrade(request) {
request.context.data = "myData";
},

open(peer) {
console.log(peer.context.data); // myData
},

message(peer, message) {
console.log(peer.context.data); // myData
},

close(peer, details) {
console.log(peer.context.data); // myData
},
});
```