NuxtN
Nuxt16mo ago
48 replies
Quei

Reusable websocket component

Hi Community and @manniL / TheAlexLichter
i found the super helpfull small guide on YT:
https://www.youtube.com/watch?v=OfY7JcrqkPg&t=33s

It works like a charm! Now I'm wondering how I can create a reusable component for sending messages.

The idea is to have a central "channel" for updates across the web app. For example, I've written a mail client, and when this client receives a new email, it should send a message to the channel. Based on this message, a component refresh should be triggered.

But I'm having trouble implementing this. The main idea is to have a function that I can import anywhere on the server side to send messages to this channel.

server\api\websocket.ts
export default defineWebSocketHandler({
    open(peer) {
        logger.warn('WebSocket opened:', peer)
    },
    close(peer) {
        logger.warn('WebSocket closed:', peer)
    },
    error(peer, error) {
        logger.error('WebSocket error:', error)
    },
    message(peer, message) {
        logger.warn('WebSocket message:', peer, message)
    }
})
YouTubeAlexander Lichter
🎉 Nitro 2.9 was released just before Vue.js Amsterdam and brings new features such as a database layer, a task API and also WebSocket support! But how can we integrate it in a Nuxt application? This video will teach you 👌

Key points:
🛠 How to set up WebSockets in Nitro and in Nuxt
💡 Working from scratch to a functional application
⚠️ Hints to m...
Integrating WebSockets in Nuxt and Nitro
Was this page helpful?