I was trying to find better implementations for this topic, i do have it working, my issue is that, before mounted i get an error:
Firefox can’t establish a connection to the server at http://localhost:3000/api/redis?channel=ads_channel.
But it works fine anyways.
First: install npm i ioredis.
Second: Create an endpoint at your nuxt/server/api folder.
server/api/redis.ts
import Redis from "ioredis";
const redisClient = new Redis(6379);
redisClient.on("error", (err) => console.error("Redis Client Error",err));
export default defineEventHandler((e) => {
e.node.res.writeHead(200, {
"Cache-Control": "no-cache",
Connection: "keep-alive",
"Content-Type": "text/event-stream",
});
const { channel } = getQuery(e);
redisClient.subscribe(channel, (err, count) => {
if (err) {
e.node.res.end(JSON.stringify({ error: err.message }));
return;
}
redisClient.on("message", (channel, message) => {
e.node.res.write(`data: ${message}\n\n`);
});
// e.node.res.setHeader("Content-Type", "text/event-stream");
// e.node.res.setHeader("Cache-Control", "no-cache");
// e.node.res.setHeader("Connection", "keep-alive");
});
return true;
});
Third: Now in your component or page add this:
onMounted(() => {
const connectEventSource = () => {
const eventSource = new EventSource(`/api/redis?channel=your_channel_name`);
eventSource.onmessage = (event) => {
let parsed = JSON.parse(event.data);
console.log(parsed);
};
eventSource.onerror = (error) => {
console.error("EventSource failed:", error);
eventSource.close();
setTimeout(connectEventSource, 5000); // Retry connection after 5 seconds
};
};
setTimeout(connectEventSource, 1000);
});