Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

336
Vistas
Saving an express-session in socket.io

I can not understand why my sessions do not want to be saved.

Each time I connect, I get a new session id, but if I just go (through the browser) to tessocket.local, the session is saved and already when called through the socket, it is normally determined. That's actually the question - how to defeat it?

Forcing the session to be saved after io.on("connection" doesn't help.

If you remove transports: ["websocket"] - polling starts working, but then the session is not defined at all through the socket.

client.js

const socketOptions =  {

    "force new connection" : true,
    "reconnectionAttempts": "Infinity", 
    "timeout" : 10000,
    "transports" : ["websocket"]
};
// @ts-ignore
socket = io('https://tessocket.local',socketOptions)
 // @ts-ignore
socket.onAny((event, ...args) => {
    console.log(event, args);
  });
return socket

server.js

 const app = require('express')(),
  http = require('http'),
  https = require('https'),
  // http  = require("http"),
  fs = require( "fs" ),
  path = require("path"),
  eSession = require("express-session"),
  MongoDBStore = require('express-mongodb-session')(eSession),
  store = new MongoDBStore({
    uri: 'mongodb://admin:admin@localhost:27017/tmp?authSource=admin',
    collection: 'sessions'
  });
 
 
    options = {
    key: fs.readFileSync(path.resolve(__dirname, "../minica/test.local/key.pem")),
    cert: fs.readFileSync(path.resolve(__dirname, "../minica/test.local/cert.pem")),
    },
    server =  https.createServer(options, app)

  const io = require("socket.io")(server, {
    cors: "http://test.local:3000",
    transports: ["websocket"]
  }),
  session = eSession({
    secret: "my-secret",
    resave: true,
    saveUninitialized: true,
    store,
    cookie: {
      httpOnly: false, // key
      maxAge: null,
      path: "/",
      secure: true,
      sameSite: 'none'
    },
  }),
  sharedsession = require("express-socket.io-session");


// Attach session
app.use(session);

// Share session with io sockets

io.use(sharedsession(session));

io.on("connection", function(socket) {
    // Accept a login event with user's data
    console.log(socket.handshake.session.id) 
    socket.on("login", function(userdata) {
        socket.handshake.session.userdata = userdata;
        socket.handshake.session.save();
    });
    socket.on("logout", function(userdata) {
        if (socket.handshake.session.userdata) {
            delete socket.handshake.session.userdata;
            socket.handshake.session.save();
        }
    });        
});

server.listen(443);

socket.io@4.4.1

express@4

over 4 years ago · Santiago Trujillo
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda