Search code examples
javascriptnode.jscookiesexpressalertifyjs

Alertifyjs alerts shown to the person who triggered it


As a disclaimer, I'm new to nodejs and express framework in general so please bear with me while I'm still trying to learn.
I'm using alertifyjs library to show notifications for various alerts to a user. Now, the problem is that the notifications are showing for everyone who is on the site. I get why this is happening and it makes sense. How do I go about making it so a specific alert only shows for the person that triggered it? What exactly do I use to make this happen? Cookies? Thank you for your help and let me know if you need any more information.

Here's a code example...

//client code
socket.on('word length', function(data) {
  alertify.error('Check word length!');
});


//server code
if (word.length > 50 || word.length <= 1) { // check word length:
  io.sockets.emit('word length', word);
}

Solution

  • This is nothing to do with alertify but more to do with how socket.io works. The io.socket.emit call will broadcast a message to all connected sockets.

    You want to call emit on the client socket only

    io.on('connection', function (socket) {
        io.socket.emit('message', 'to everyone');
        socket.emit('message', 'to this client only');
    });