Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

189
Views
Notification with socket.io. NodeJS

So, I'm trying to make a notification system but I'm running into a problem.

I sent a invitation to a user to join the club.

socket.on("notify", async (message) => {
  // invite the user John Doe
  io.to('socket.id of John Doe').emit('notificaton', msg);
});

Question

But how do I get the socket.id of John Doe to emit the invitation notification to him?

John Doe receives the message after refreshing the page, which gets the notification from database. But I don't want John Doe to refresh every time to check his notification. I want it to be in real time. But to send him the notification in real time, I can only think of one thing and that is to store the socket.id of John Doe in database and update that every time John Doe login to the application, which might cause a problem if John Doe has logged on to multiple devices with same account cuz the socket.id might be different in other devices. And only one of his device receives the notification. * I don't know if socket.id is different for every devices when logged on with multiple devices *

Can you please help me to come up with a better solution ?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Usually, one keeps the socket in some in-memory data structure (such as a Map object) where a userID is the key and the current socket for that user is the data. Then, you can look up any user's socket with their userID and internal to your app, you use your userID (a persistent thing not tied to socket.io) to identify the user. Then, you can look up any user's socket at any time (if they are currently connected).

When a user connects, you add their socket to the Map object and when they disconnect, you remove it. You can also make sure that both client and server ends of the socket.io connection know which userID they represent.

Note, you cannot store a socket object in your database as it's a live object that includes native code state that can't be directly stored in a database. You would store a socket.id which is just a string in a database, but usually you would just maintain an in-memory data structure for currently connected users.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!