Can I do what I want with websockets in a worker?
I havent used websockets in workers before and have some trouble understanding how it works. I just want to confirm if what I want to do is possible or not: a long-running websocket server that sends messages based on receiving other external events.
My actual end goal is something like this: a client (a browser) connects to my worker acting as a websocket server, and they are fed messages over that WS periodically. They are triggered by certain external events, which is the part I'm having trouble thinking about. For example, say I have a discord bot (running somewhere else) that wants to trigger an event on this worker websocket, how would I do that? Sending a simple webhook to my worker with the event data sure, but how do I feed that through to that websocket connection? Is that the part durable objects helps with?
Thank you
1 Reply
I think instead of adding web socket support in a Worker itself you would want to keep it in a Durable Object where it can be a longer running process. When you deploy a durable object you're also deploying a worker alongside it, and in that worker you can setup that webhook route that receives data from your Discord bot and then have it send that data into your durable object which would then process it in the web socket with
server.send("Your message")
See the CF example below:
https://developers.cloudflare.com/durable-objects/examples/websocket-server/
But you will likely want to use the web socket Hibernation API to avoid any charges when you're not actively using any web sockets.Cloudflare Docs
Build a WebSocket server · Cloudflare Durable Objects docs
Build a WebSocket server using Durable Objects and Workers.