How to use the hibernatable websocket API on worke...
# workers-help
c
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?
u
You accept new connections with the
state.acceptWebSocket
function and your durable object interface should implement the handlers - here is an incomplete example:
Copy code
javascript
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 };
}
There is a full example in the
workers-chat-demo
repo https://github.com/cloudflare/workers-chat-demo/blob/hibernation/src/chat.mjs