How can I get session information from koa-session inside a socket.io instance?

748 Views Asked by At

How can I use session information from the module koa-session inside a socket.io instance e.g.

In my app.js

const sesh = session(app);
require('./sockets/socket')(app);

My sockets.js file

module.exports = async(session) => {
    let app = require('http').createServer();
    let io = require('socket.io')(app);
    let models = require('../models');
    app.listen(3001);


    // io.use get session information and bind it to the socket

    io.on('connection', (socket) => {
        console.log('User Connected');
    });
}
2

There are 2 best solutions below

0
On

I have created a SocketIO middleware for Koa v2 and SocketIO v2 to handle not only getting of session info from Koa but also saving it back to the session. Its written in typescript but could be easily changed to vanilla js. Here is the Gist of it.

0
On

If you provide a session store to koa-session, you can use it to access its sessions from their key outside of koa request's lifecycle.