How to access express.session.MemoryStore via socket.io objects? How to access express.session.MemoryStore via socket.io objects? express express

How to access express.session.MemoryStore via socket.io objects?


I am not sure if you're still working on this, but you can access session data with just a MemoryStore. After all how else would Express use it if it didn't work? :)

A simple way to demonstrate MemoryStore working is this:

var express = require("express")  , app = express()  , sessionStore = new express.session.MemoryStore();// middlewareapp.use(express.cookieParser());app.use(express.session({store: sessionStore, secret: "mysecret"}));// any endpoint sets a cookieapp.get("/", function(req,res) {  res.send('ok');});// This endpoint reveals itapp.get("/session", function(req, res){  sessionStore.get(req.sessionID, function(err, data) {    res.send({err: err, data:data});  });});app.listen(3000);

Hitting / followed by /session results in a response of:

{  "err": null,  "data": {    "cookie": {      "originalMaxAge": null,      "expires": null,      "httpOnly": true,      "path": "/"    }  }}

I suspect your issue may be how you are getting the sessionID from the socket, but it is definitely possible to extract a session from a MemoryStore. Also, remember that restarting the Express server will destroy all of your sessions so you'll need a new cookie after each restart.


You have to use a database to store your express session, then parse the cookie data inside the socket.io definition and with the information obtained get the session info from the database, here is a complete example:

https://stackoverflow.com/a/13098742/218418

You can also use the session ID parsed from the cookie and join the user into a "chat room" with the name of the session.