Socket.io: Overwritten generateId() gets executed, but the returned id seems to be ignored

Viewed 535

I am trying to overwrite generateId. I used for that the example from the docs. But the behaviour is strange. generateId gets executed, but socket.id is like a regular id, instead of the desired result "custom:id:" + 1.

Code

const express = require('express');
const socketIO = require('socket.io');
const http = require('http');

const app = express();
app.set('port', 5000);
const server = http.Server(app);
const io = socketIO(server);


io.engine.generateId = (req) => {
    console.log('This here gets printed')
    return "custom:id:" + 1;
}

io.on('connection', socket => {
    console.log(socket.id);
})


server.listen(5000, async () => {
    console.log('Starting server on port 5000');
});

Expected Output: custom:id:1

Actual Output: MNWAC86CdPXB7thTAAAA

package.json Dependencies

  "dependencies": {
    "base64id": "^2.0.0",
    "clean-webpack-plugin": "^3.0.0",
    "cookie": "^0.4.1",
    "css-loader": "^5.0.1",
    "express": "^4.17.1",
    "file-loader": "^6.2.0",
    "html-webpack-plugin": "^4.5.0",
    "jquery": "^3.5.1",
    "ngrok": "^3.4.0",
    "sass": "^1.29.0",
    "sass-loader": "^10.1.0",
    "socket-io": "^1.0.0",
    "socket.io": "^3.0.3",
    "socket.io-client": "^3.0.3",
    "style-loader": "^2.0.0",
    "webpack": "^5.7.0",
    "webpack-dev-middleware": "^4.0.2"
  }
1 Answers

I was having this problem also. Apparently it is due to a change in socket.io version 4. The code below is from node_modules/socket.io/dist/socket.js. It appears the change is for security reasons.

if (client.conn.protocol === 3) {
    // @ts-ignore
    this.id = nsp.name !== "/" ? nsp.name + "#" + client.id : client.id;
}
else {
    this.id = base64id_1.default.generateId(); // don't reuse the Engine.IO id because it's sensitive information
}

client.id will have the value you return in your generateId but it won't be used as we expected.

After looking through the source and debugging, it looks like the socket id can be set in an io.use (example below.)

var idIndex = 0
io.use((socket, next) => {
    socket.id = `ID_${idIndex++}`;
    next();
});
Related