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?