Express Session用户信息无法传入Socket.IO的问题求助
socket.handshake.session.user in Socket.IO + Express Session Hey there! Let's get to the bottom of why your socket.handshake.session.user is showing up as undefined. I've spotted a couple of critical issues in your code that are breaking the session sharing between Express and Socket.IO:
Key Problems in Your Code
1. Duplicate express-session Instances
You're initializing two completely separate express-session objects—one for Express, and another for Socket.IO via sharedsession. These don't share any state, so the session data you set in Express (req.session.user) never makes it to Socket.IO. You need to reuse the same session configuration instance for both.
2. Wrong Server Startup Method
You created an http server instance to attach Socket.IO to, but then you start the server with app.listen() instead of http.listen(). This means your Socket.IO server isn't actually running on the same server as Express, so the session cookies aren't being passed through when a client connects via WebSocket.
Corrected Code
Here's the fixed version with explanations of the changes:
const express = require('express'); const path = require('path'); const cookieParser = require('cookie-parser'); const expressSession = require('express-session'); const sharedsession = require("express-socket.io-session"); var app = express(); var http = require('http').createServer(app); var io = require('socket.io').listen(http); app.set('port', process.env.PORT || 3001); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); // 👇 Create ONE session instance to reuse across Express and Socket.IO const session = expressSession({ key: 'userID', secret: 'k39dzqlp@k5d&k@dh&', saveUninitialized: false, resave: false, cookie: {maxAge: 1200000} }); // Use the same session instance for Express app.use(session); // 👇 Pass the existing session instance to sharedsession, not a new one io.use(sharedsession(session, { autoSave:true // Optional: helps ensure session changes are saved })); app.route('/login') .post((req, res) => { // Assume user.dataValues is your fetched user data req.session.user = user.dataValues; res.redirect('home'); }); // 👇 Start the server with http.listen() instead of app.listen() http.listen(app.get('port'), () => { console.log(`Server running on port ${app.get('port')}`); }); io.on('connection', (socket) => { console.log(socket.handshake.session.user); // Now this should show your user data! // Optional: Save session if you modify it in Socket.IO socket.handshake.session.save(); });
Additional Debugging Tips
- Check your browser's dev tools (Application tab → Cookies) to confirm the
userIDcookie is being set after login. - In the Socket.IO
connectionevent, log the entiresocket.handshake.sessionobject to see if any session data is being passed through at all. - If you're testing in production, make sure your
cookieconfiguration includessecure: true(since WebSockets over HTTPS require secure cookies) andsameSite: 'strict'or'lax'to avoid CORS issues.
内容的提问来源于stack exchange,提问作者Heide Nei

