DEV Community

Discussion on: Using WebSockets with React.js, the right way (no library needed)

bikash9609 profile image

Hi, I am learning with NodeJs and ReactJS. Please point me in the right direction.
Suppose, I want users to connect to a server (Express.JS) using - securely. I am using auth token - JWT for that. How does it work.
I mean, do I need to send JWT with every event or just once during Join. And even when during join - i verify that the user is authenticated and JWT is legit. How do I know the second time that the user is the one who authenticated and not someone else in place of him. I am a bit confused as you must be getting from my questions.

My real intention is to get realtime data using NodeJS server from MongoDB using and reactjs in the frontend. The data should be private to each user. I think I would need to create separate room for each user.

Just like Facebook friend request system. If you put a request for someone else, it is in realtime updated to the end user.

Just point me in the right direction, blogs, stackoverflow, guides etc. Anything works.

Thanks already to everyone!

itays123 profile image
Itay Schechner Author

I suggest this solution:

  • attach the token to the Websocket URL in the query params. I.e: ws://localhost:4000/ws?token=...
  • In the server, in the connection established event, get the sessions URL (I supposed you have access to it although I can't recall), and get the search params from it.
  • validate the token, and if not validated - manually disconnect the websocket from the server.