ZiiMakc
ZiiMakc

Reputation: 37026

How to send cookies to socket.io client from server?

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?

Upvotes: 10

Views: 1905

Answers (1)

ZiiMakc
ZiiMakc

Reputation: 37026

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=/'

Upvotes: 6

Related Questions