Next.js + tRPC + Redis - pub/sub

Hi, I have an app made in Next.js, and I want to get some real-time log feature for it. I thought about using Redis Pub/Sub to do it, and use tRPC Subscriptions also. Ideally I want to publish a message from Next.js API Route and then handle it in tRPC subscription. But for now, I'm trying to make the simplest solution and it doesn't work. I follow docs and made needed things to use it (one diff is I replace event emitter with redis) and when I published my message it doesn't seem to be handled in subscription. Here's the code, I will be glad, if you can take a look and tell me what I'm doing wrong. Thanks in advance! 🙂 https://github.com/Bartek532/rssmarkable/pull/40
2 Replies
Endgame1013
Endgame1013•15mo ago
I’ve honestly never tried this myself, but I did notice in the ioredis docs that you can call redis.subscribe(). Have you tried that? I think you’ll need to subscribe to the same channel that you publish to (in your case, “test”, I think). Let me know if that works for you! From the ioredis docs: // subscriber.js const Redis = require("ioredis"); const redis = new Redis(); redis.subscribe("my-channel-1", "my-channel-2", (err, count) => { if (err) { // Just like other commands, subscribe() can fail for some reasons, // ex network issues. console.error("Failed to subscribe: %s", err.message); } else { // count represents the number of channels this client are currently subscribed to. console.log( Subscribed successfully! This client is currently subscribed to ${count} channels. ); } }); redis.on("message", (channel, message) => { console.log(Received ${message} from ${channel}); }); // There's also an event called 'messageBuffer', which is the same as 'message' except // it returns buffers instead of strings. // It's useful when the messages are binary data. redis.on("messageBuffer", (channel, message) => { // Both channel and message are buffers. console.log(channel, message); });
zagrodzki
zagrodzki•15mo ago
Yep, it's working, thanks @Endgame1013!