Reputation: 2048
I know that I can set cookies during handshake:
const wss = new WebSocketServer({ server, path: '/ws' });
wss.on('headers', headers => {
headers.push('Set-Cookie: my-cookie=qwerty');
});
How can I change cookies inside websocket connection? For example, I want to set session cookie after some client message:
ws.on('message', () => {
// something like ws.setCookie('my-cookie=qwerty');
});
Upvotes: 22
Views: 18266
Reputation: 707386
You can't set a cookie upon receipt of a webSocket message because it's not an http request. Once the webSocket connection has been established, it's an open TCP socket and the protocol is no longer http, thus there is no built-in way to exchange cookies.
You can send your own webSocket message back to the client that tells it to set a cookie and then be listening for that message in the client and when it gets that message, it can set the cookie in the browser.
Upvotes: 16