I'm learning basics of Socket.io and I want to implement connection ONLY upon when user logs in. Currently, the offical documentation doesn't really seem to mention this kind of implementation. I'm using JWT for authentication and Node.js for server side.
Currently, Socket.io connects upon website visit:
const express = require('express');
const app = express();
const server = app.listen( process.env.PORT || 5555 );
const io = require('socket.io')(server, {
cors: {
origin: "*",
methods: ["GET", "POST"]
}
});
io.on('connection', socket => {
console.log('A client connected but not logged in yet.');
socket.on('disconnect', () => {
console.log('A client disconnected');
});
});
I want Socket.io to connect only when user logs in:
/** Example Logic **/
if (user_is_logged_in) {
const io = require('socket.io')(server, {
cors: {
origin: "*",
methods: ["GET", "POST"]
}
});
}
Best way to implement this? or is it even possible? Thanks.