I am making a chat application and I want people to be able to use specific usernames. I saw https://npmjs.com/socket.io.users, however, the last publication was 8 years ago. I also don’t know how to really use socket.id to check for a username, since there is no identifiable information for the username, and the id changes for each socket/refresh.
How do I get the username of the person sending the message from the server side? I do not want to send it with the client side because I think that would be quite easy to bypass and send a message as any user, though it doesn’t have to be insanely secure.
Sorry if this has been said before, everywhere I have checked talks about socket.id, but I don’t think that can check what user is sending a message.
2
Answers
I suggest using one of the tutorials from https://socket.io (https://socket.io/get-started/chat) instead of an 8-year-old tutorial. This tutorial includes a username input dialog and features messages being sent with their username as the prefix.
In the chat application, you need to check each user if it is authenticated to send any message. so you could write a middleware on the server and attach the new property to the
socket
. Depending on your authentication mechanism you write a different logic but i will demonstrate on authentication by jwt.you need to register this middleware to the
io
not to theexpress
Now on the server, if user is authenticated, you have
socket.user
object. depending on how you constructed theuser
object injwt
, you could usesocket.user.user_id
orsocket.user.username