0

I'm trying to use the express-session library in my MERN stack app along with socket.io for the real time messaging part of the app.

For authentication I am using express-session and would like to use that same middleware for socket connections, however when I followed the answer for the same problem here, the middlware just simply didn't proceed to the next function and so when trying to connect, the middlware never went to the onConnect handler and the handshake never completed.

const day = 1000 * 60 * 60 * 24; // ms

const sessionStore = MongoStore.create({
    mongoUrl: "mongodb://localhost:27017/zooit",
    collection: "sessions"
});

// defining the session middlware from express-session
const session = () => expressSession({
    secret: process.env.SECRET_KEY,
    resave: false,
    saveUninitialized: true,
    store: sessionStore,
    cookie: {
        maxAge: day * 30
    }
});

// session middlware fine with express
app.use(session());

io.use((socket, next) => {
    // won't use next function
    session(socket.request, {}, next);

    // tried doing this but then in the handler session.request.session was undefined
    // next();
});

io.on("connection", require("./socket-controllers/onConnect"));
io.on("disconnect", require("./socket-controllers/onDisconnect"));
// onConnect.js
function onConnect(socket) {
    // this function isn't reached when not calling next but when explicitly calling next() socket.request.session is undefined
    console.log(`User connected: ${socket.request.session}`);
}

If anyone has any suggestions on how I should proceed that would be great

1 Answers1

0

Update, I found the answer.

In the socket.io documentation it goes over how you are able to use middleware and express-session.

Crucially it gives a wrapper function which seems to sort things:

const wrap = middleware => (socket, next) => middleware(socket.request, {}, next);

From here you wrap the express-session middleware already defined in an io.use:

io.use(wrap(session()));

Now I can access the session like so:

socket.request.session

Hope this helps anyone struggling with the same issue.