10

On my client i do this:

  useEffect(() => {
    socket.emit('login', myLoginCode)
  }, [])

On server side previosly i did this:

app.get('login', (req, res) => {
      const cookieProtected = {
        maxAge: 946080000000,
        httpOnly: true,
        secure: true,
        sameSite: true
      } 
      res.cookie('id', login, cookieProtected)
      res.cookie('session', encryptSession, cookieProtected)
      res.cookie('logged', 'true', {
        maxAge: 946080000000,
        secure: true,
        sameSite: true
      })
})

But how can i do the same with socket?

  socket.on('login', loginCode => {
     // How to to place cookies in user browser from here?
    }

Maybe there is a way to send headers with socket.emit?

ZiiMakc
  • 31,187
  • 24
  • 65
  • 105
  • Did you try this one: https://stackoverflow.com/questions/10771337/adding-a-cookie-value-on-socket-io? – Alejandro Nov 24 '18 at 12:22
  • io.on('connection', async socket => { try { socket.handshake.headers.cookie = 'test=1; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/' Yes, it's not working. – ZiiMakc Nov 24 '18 at 13:44

1 Answers1

6

There us no way to do it without rewriting IO library, so only option is to set cookies on client side.

Now i just verify user on server and send client cookies like an object, then on client i do like this:

document.cookie =
    'id=' +
    loginData.id +
    '; expires=Fri, 31 Dec 9999 23:59:59 GMT; secure; samesite=strict; path=/'
ZiiMakc
  • 31,187
  • 24
  • 65
  • 105