How to deal with server.handleUpgrade() was called more than once in Nodejs?

Viewed 5569

I am running a nodejs application which runs great the first time I use it but when I refresh and enter the new data Node crashes and gives me this. The error looks like this :

/www/wwwroot/domain.to/node_modules/ws/lib/websocket-server.js:267
      throw new Error(
      ^
Error: server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration
    at WebSocketServer.completeUpgrade (/www/wwwroot/domain.to/node_modules/ws/lib/websocket-server.js:267:13)
    at WebSocketServer.handleUpgrade (/www/wwwroot/domain.to/node_modules/ws/lib/websocket-server.js:245:10)
    at Server.upgrade (/www/wwwroot/tehran.us.to/node_modules/ws/lib/websocket-server.js:89:16)
    at Server.emit (events.js:327:22)
    at onParserExecuteCommon (_http_server.js:646:14)
    at onParserExecute (_http_server.js:587:3)

The code on the server looks like this for express :

const app = express();
const options = {
key: fs.readFileSync('./key.pem'),
cert: fs.readFileSync('./cert.pem')
};
const server = https.createServer(options, app)

server.listen(3000, function () {
  console.log("Express server listening on port " + 3000);
});

I also use Websocket on the same end point and the code looks like this :

const wss = new Websocket.Server({ server })
    console.log(url)
    wss.on('connection', ws => {
        console.log('user is connected to the server #mainpage')

I don't know how to go around it as the application seems to not create a new instance of the application for a new refresh.

How can I deal with this and make my app running continuously?

2 Answers

This is because you have already created the server using express and the handleUpgrade method is called inside express, so you need to inform your WebSocket server to ignore the server initiating part and continue with the existing resource as giving the options as { noServer: true }

const wss = new WebSocket.Server({ noServer: true });

server.on('upgrade', function (request, socket, head) {
  wss.handleUpgrade(request, socket, head, function (ws) {
     wss.emit('connection', ws, request);
  })
})

Well, In My project I was using express-monitor which was also using socket.io hence leading the server to handle the upgrade for ws connection request as well as socket.io initialization.

Removing express-monitor solved the issue

Related