I\'m building a simple little chat with Node.js and socket.io
When a user types his message, it is broadcasted to all other users.
Server sends the message :
The best way here, is for the server to do nothing!
Yes, you read that right. The correct place to "escape" content is where it's being outputted, in the context where it's being outputted. This is known as Filter-In, Escape out.
So in your case, the client should handle the escaping for you. Funny enough, jQuery (which it looks like you're using) has a method that does this for you: $.fn.text()
. So your client code becomes:
socket.on('fromServerToClient', function (data) {
$('#messages').append($('').text(data.message));
});
I added the div
so that each message can be styled appropriately...
But your server side should have nothing to do with this escaping.
Now, you could decide to filter out anything that looks like HTML on the server, which would be known as Filtering (and either replace it away, or reject it). But definitely do not escape it!