I am working on a Next.js chat application that uses MongoDB to store chat messages. After sending a message, it gets inserted into the collection, but I’m facing issues with reading the messages in real-time.
To achieve real-time updates, I am using MongoDB change streams on the Next.js API and Server-Sent Events (SSE) to send responses to the client. On the client side, I have the following code:
const eventSource = new EventSource("/api/sse", {
withCredentials: true,
});
console.info("Listening on SSE", eventSource);
eventSource.onmessage = (event) => {
const result = callback(event);
if (result?.cancel) {
console.info("Closing SSE");
eventSource.close();
}
};
This setup works fine on my local machine, but on the server, it times out and gives a 504 error.
Could anyone suggest some solutions to achieve the same real-time message updates without facing these issues on the server? Any help would be greatly appreciated!
Thank you!
I tried Server-Sent Events (SSE) but it gives 504 timeout on vercel