0

I am trying to use express-session for session management. It works okay inside functions I create, but inside socket.io it doesn't work at all.

Here's what I have:

   socket.on('chat_message', function(message, req) {


    if (req.session.lang) {
        translate(message, null, req.session.lang, true).then(res => {
            console.log(res.translation);
    
            io.to(socket.id).emit('chat_message', '<strong>p' + socket.username + '</strong>: ' + res.translation);
    
            }).catch(err => {
            console.error(err);
            });
     }
    });
})

it is giving me the error:

TypeError: Cannot read property 'session' of undefined

on the if statement line: if (req.session.lang) {

why isn't this working? I have express-session defined as well.

Gianluca
  • 566
  • 1
  • 9
  • `socket.on` gets an event and a callback. the callback arguments are which you pass in the `socket.emit` function. This is not an express route callback! – Omri Attiya May 08 '21 at 15:35
  • 1
    @Gianluca this link may help you to access session in socket https://stackoverflow.com/questions/25532692/how-to-share-sessions-with-socket-io-1-x-and-express-4-x – Mic Fung May 08 '21 at 15:42

0 Answers0