2

Using Express + ws (websocket) libraries.

"App" uses some Express middleware to add the current user to the request object, but WS gets a Node request object without the information I need.

How can I pass this data to the websocket when upgrading connection?

const server = http.createServer(app); // app is using the express middleware to add info I need

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

server.on('upgrade', (request, socket: any, head) => {
    wss.handleUpgrade(request, socket, head, (ws: WebSocket) => {
        wss.emit('connection', ws, request);
    });
});

server.listen(3000, () => {
    console.log('Listening on port 3000');
});
jdoe8227
  • 41
  • 4

1 Answers1

0

Depends a bit on what basis you establish the users. But if you use cookies for identifying / creating users, the good news is, you have the cookies available in the upgrade hook in the request object.

For more info, see a discussed solution with cookies: https://stackoverflow.com/a/59314360/4774136

whatever
  • 21
  • 4
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 18 '23 at 07:49