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

85
Views
Sharing SocketIDs Across Node.js files

I have a MERN stack application, and I have an array that keeps track of the logged in users.

server/index.js
var connectedUsers = []

io.on('connection', (socket) => {
    socket.on('addUser', (userId) => {
        connectedUsers.push({userId, socket.id})
    })
})

I also have a POST request for creating a Post document.

server/controllers/post
export const createPost = async (req, res) => {
    const post = req.body;

    const newPostMessage = new PostMessage({ ...post, 
        creator: req.userId, createdAt: new Date().toISOString() })

    try {
        await newPostMessage.save();

        res.status(200).json(newPostMessage);
        awardBadges(req.userId)
    } catch (error) {
        res.status(50).json({ message: error.message });
    }
}

After creating a post document and sending it as a JSON, it will check to see if the user meets any requirements for a badge (similar to Stackoverflow badge)

export const awardBadges = async (userId) => {
   // Assign awards
   // Update user's awards field with the badges he received 
   // and mailbox field with that specifies which awards he received
}

If the user is connected and received a badge, it will emit a message so that the user will send a GET request to the database to get his mailbox field.

I know I can accomplish this by doing the following:

io.to(socket.id).emit("getMailbox");

But how can I access the socketId if it's in a different node.js file? Would I have to make the connectedUsers a global var?

about 4 years ago · Juan Pablo Isaza
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!