I'm running webpack-dev-server on localhost:8000 for my app and express+socket.io on port 3000 for my api. I've proxied requests to socket.io in webpack.config.js as such:
devServer: {
proxy: {
'/socket.io': {
target: 'http://localhost:3000',
ws: true
}
}
}
However, not only do the session ids in express and socket.io don't match, the session id in express changes every request:
Server:
let app = require('express')();
let session = require('express-session')({
secret: 'panopticon',
resave: true,
saveUninitialized: true
});
let server = require('http').createServer(app);
let io = require('socket.io')(server);
//session middleware
app.use(session);
io.use(require('express-socket.io-session')(session, {
autoSave: true
}));
let i=0;
app.get('/socket.io', (req, res) => {
console.log(i++, req.session.id);
//0 'ShgnU91kCZzC7xHP9B57ZtsCbwi3XjdB'
//1 'qLsYYpRZXpyoUrcKzF6K7uoAIKtE9oCh'
res.send();
});
io.on('connection', socket => {
console.log(socket.handshake.session.id);
//MRUYZMVstMh6ssNrq9LP-Z4vTaT5SZcs
});
Client:
//connect to socket
let socket = io();
//make two requests to /socket.io
fetch('socket.io').then(() => fetch('socket.io'));
The only way I got this to work was to do an AJAX request first to localhost:3000
:
fetch('http://127.0.0.1:3000', {
credentials: 'include'
});
With the following handler on the response:
app.use('/', (req, res) => {
res.header('Access-Control-Allow-Origin', 'http://127.0.0.1:8080');
res.header('Access-Control-Allow-Credentials', 'true');
res.sendStatus(200);
});