I want to set some user information in a cookie and be able to access it on connection, is this possible?
Asked
Active
Viewed 4.4k times
4 Answers
38
Using Socket.IO 0.8.7, you can access request headers via:
socket.handshake.headers
You can find more detail on this at https://github.com/LearnBoost/socket.io/wiki/Authorizing

gabrtv
- 3,558
- 2
- 23
- 28
21
client.request.headers.cookie
leads to race conditions as the cookie always points to the last logged in user.
Please see: Socket.IO Authentication.

Community
- 1
- 1

Shripad Krishna
- 10,463
- 4
- 52
- 65
-
11Any evidence for that? The link you provided doesn't mention that. – rvighne Nov 16 '14 at 16:40
-
2016: https://github.com/socketio/socket.io/issues/2470 Latest Docs: https://socket.io/docs/server-api/#namespace-use-fn – Palisand Nov 27 '17 at 19:21
4
-
2According to this reply, this will work fine for development but break in production due to race conditions: http://stackoverflow.com/a/4754814/371122 – Tim Mar 24 '17 at 03:15
0
After looking to the engine.io source code you can set cookies using:
var io = require('socket.io')(3000);
io.use((socket, next) => {
socket.conn.transport.once('headers', (headers) => {
headers['set-cookie'] ="sess=test;"; });
next();
});
this code could conflict with the engine.io code that set the sid cookie. as both HTTP/1.1 and HTTP/2 headers are case-insensitive and engine.io use 'Set-Cookie' in the headers object adding a lowercase object name 'set-cookie' would avoid this problem.

gilbert
- 74
- 1
- 5