nagy.zsolt.hun
nagy.zsolt.hun

Reputation: 6694

set cookie in WebSocket only if missing

We can set the cookie in WebSocket handshake: Set cookie inside websocket connection, however I can't decide whether the cookie was already set:

const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8088 });

wss.on("headers", onHeaders);

function onHeaders(headers) {
    console.log("onHeaders cookie: " + headers.cookie); // undefined
    headers.push('Set-Cookie: ' + cookie.serialize('client', 1));
}

How can I see whether the "client" value is already available, before setting the cookie?

Upvotes: 1

Views: 828

Answers (1)

ottomeister
ottomeister

Reputation: 5808

Install a handler function for the connection event on the WebSocket server. This fires when a WebSocket request is received, and it is passed a request object (an instance of http.IncomingMesssage) as an argument. You can examine the headers of the request object to see whether your cookie is present in the request. Something like:

wss.on('connection', onConnection);

function onConnection(websock, request) {
    console.log(request.headers);
}

although of course you'll want to do something more complicated than just printing the headers.

Upvotes: 1

Related Questions