Get SSE data from nuxt
I've written this code to retrieve SSE data, but it doesn't work properly.
2 Replies
Hi @TheDreWen. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
----------------------
To retrieve SSE (Server-Sent Events) data in Nuxt, you're on the right track, but there are a few improvements we can make to ensure it works properly. Let's modify your code based on the information from our knowledge sources:
Here are the key changes and explanations:
1. We're using
eventSource.onmessage
instead of addEventListener("message", ...)
. This is a more direct way to handle SSE messages Nuxt Docs: Data Fetching (https://nuxt.com/docs/getting-started/data-fetching#recipes).
2. We're logging event.data
instead of the entire event object. This gives you the actual message content.
3. I've added an onUnmounted
hook to close the EventSource connection when the component is unmounted. This is important for cleaning up resources.
4. Make sure your server is properly set up to send SSE. If you're using Nitro (Nuxt's server engine), you can set up an SSE endpoint like this Nitro Docs: WebSocket (https://nitro.unjs.io/guide/websocket#server-sent-events-sse):
This example sends a message every second. Adjust it according to your needs.
If you're still having issues, make sure:
1. Your server is correctly configured to send SSE.
2. The URL you're using is correct and accessible.
3. The token in the cookie is valid and being sent correctly.
Remember, SSE is unidirectional (server to client only). If you need bidirectional communication, consider using WebSockets instead.
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------<@1002206963532300298> Kapa.ai is still learning and improving, please let me know how I did by reacting below.