How to send Socket.IO events to specific client from Express route handler

I’m working on an Express app with Socket.IO integration. I need to send real-time updates to only the specific user who made the HTTP request, not to all connected clients.

My current setup looks like this:

server.js

const express = require('express');
const app = express();
const routes = require('./routes');
const httpServer = require('http').createServer(app);
const socketIO = require('socket.io')(httpServer);

httpServer.listen(3000, 'localhost');
routes(app, socketIO);

routes.js

const jobHandler = require('./handlers/job');

module.exports = function(app, socketIO) {
  const apiRouter = express.Router();
  apiRouter.post('/job/execute', jobHandler.executeJob(socketIO));
}

job.js

exports.executeJob = function(io){
  return function(req, res){
    io.emit('job-started', 'Processing your request');
    // This sends to ALL clients, not just the requester
  }
}

The problem is that io.emit() broadcasts to every connected client. I want to emit only to the specific client who triggered the API call. How can I properly identify and target just that one client’s socket connection?

when a client connects through socket.io, save their socket ID in a map using the user ID or session key. then in your express route, grab that socket ID and use io.to(socketId).emit() instead of broadcasting to everyone. works great for targeted messaging.

I store socket connections in a Map with user IDs as keys. When someone connects, I grab their socket ID and user info from auth data or session cookies. Then in my route handler, I just pull the socket ID from the Map and use io.to(socketId).emit() to send messages directly to them. Don’t forget to clean up the Map when sockets disconnect or you’ll get memory leaks. This works great with multiple tabs per user and handles page refreshes way better than session storage alone.

Interesting challenge! You coud store the socket ID in a session or pass it as a header with the HTTP request. How are you linking the socket to the actual user making the API call tho?