How do you implement WebSocket connections in a Nuxt.js server?

Answer

Nuxt 3 supports WebSockets through Nitro's WebSocket event handlers (available from Nuxt 3.12+). You create a WebSocket handler in server/routes/_ws.ts using defineWebSocketHandler({ open(peer) { ... }, message(peer, message) { ... }, close(peer) { ... } }). Nitro uses crossws under the hood, which abstracts WebSocket implementations across Node.js (uWebSockets.js), Bun, Deno, and Cloudflare Durable Objects. On the client, you connect using the native WebSocket API or Nuxt's useWebSocket composable from VueUse. For production scaling (multiple server instances), you need a shared pub/sub layer like Redis or a Cloudflare Durable Object to broadcast messages across instances, since WebSocket connections are tied to specific server nodes.