How to use the hibernatable websocket API on workers + durable objects?

I'm creating a worker + DO that accept websocket requests. I'm a little bit confused of how do I implement the hibernatable API. Does someone have an example? And also, how do I know that I did it right?
2 Replies
0x0dd154
0x0dd1549mo ago
You accept new connections with the state.acceptWebSocket function and your durable object interface should implement the handlers - here is an incomplete example:
export function myDurableObject(state, env) {

const fetch = (request) => {
// stuff that handles websocket upgrade
// calling state.acceptWebSocket()
const [client, server] = new WebSocketPair();
state.acceptWebSocket(server);
return new Response(null, { status: 101, webSocket: client })
}

const webSocketMessage = (ws, message) => {
// handle message
}

const webSocketClose = (ws, code, reason, wasClean) => {
// handle close
}

const webSocketError = (ws, error) => {
// handle error
}

return { fetch, webSocketMessage, webSocketClose, webSocketError };
}
export function myDurableObject(state, env) {

const fetch = (request) => {
// stuff that handles websocket upgrade
// calling state.acceptWebSocket()
const [client, server] = new WebSocketPair();
state.acceptWebSocket(server);
return new Response(null, { status: 101, webSocket: client })
}

const webSocketMessage = (ws, message) => {
// handle message
}

const webSocketClose = (ws, code, reason, wasClean) => {
// handle close
}

const webSocketError = (ws, error) => {
// handle error
}

return { fetch, webSocketMessage, webSocketClose, webSocketError };
}
0x0dd154
0x0dd1549mo ago
There is a full example in the workers-chat-demo repo https://github.com/cloudflare/workers-chat-demo/blob/hibernation/src/chat.mjs
GitHub
workers-chat-demo/src/chat.mjs at hibernation · cloudflare/workers-...
Contribute to cloudflare/workers-chat-demo development by creating an account on GitHub.
Want results from more Discord servers?
Add your server