2

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"
  }
Atr0x
  • 176
  • 7
  • For starters, `return "custom:id:" + 1;` is not unique. It generates the same value every time. Try at least making a unique value using a counter like the example in the doc shows. – jfriend00 Dec 28 '20 at 01:45
  • @jigirend00 I already tried that out and it makes no difference, if you do that or not. Actually I had the bug in another project, where I tried out the solution from this [post](https://stackoverflow.com/questions/18294620/reuse-socket-id-on-reconnect-socket-io-node-js). I only created this file to "isolate" the error and make it more clear. – Atr0x Dec 28 '20 at 18:43
  • @Atr0x can you show the code used with unique ids as jfriend00 suggested? I also think the issue could be around uniqueness of the returned id – Daniel Reina Dec 31 '20 at 16:49
  • I'm struggling with the same issue! – Ivan Dokov Jan 10 '21 at 20:14

1 Answers1

3

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();
});
LoneSpawn
  • 988
  • 1
  • 8
  • 8