Search code examples
node.jsserverchatapi-design

How could a client know if new messages are there for it for a web based chat app?


I am developing a chat app using NodeJS as backend and using MongoDB. I had designed the database for storing messages between every clients. But just then, I have no idea how the client could be notified of new messages.

If a client logs in, the client can send an API request to get the most recent messages. But if the client stays logged in, and new messages are delivered that are meant for this client, the server records them in the database but cannot notify it until it requests for it (either by reloading the page or some other way). How could this be accomplished?

I was thinking of constantly polling the server for new messages, but wouldn't that be a lot of requests? I hope there could be some better ways to implement this. I'm relatively new to web development and this is my first project.


Solution

  • Best solution is to use websocket server for receiving messages from server.
    Of course you can also use it for sending messages.

    If you don't want or can't use websocket connection, you can use SSE - Server Site Events.
    See here for details: https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events

    Constantly pooling messages is also possible. This is good old technique used before websocket era in many chat applications. It is called "long pooling", but SSE is newest, more convinient and generally better technique nowadays. See here for details: https://javascript.info/long-polling