I see something very strange with node sessions. I use express-session and connect-mongo to save the session.
My session setup is as follows (all requests exceed https):
var session = require('express-session'); var MongoStore = require('connect-mongo/es5')(session); var sess = {}; app.use(session({ secret: 'xxxx', saveUninitialized: false, store: new MongoStore({ mongooseConnection: mongoose.connection, ttl: 60 * 30
I have a route that creates an image with a node canvas:
app.get('/api/canvas', function(req, res) { sess = req.session; console.log('in canvas and sess is ', sess);
Elsewhere in the application, you can set things like background colors. Then I have a route to clear them:
app.get('/api/clear', function(req, res) { sess = req.session; if (sess.colors) { delete sess.colors; } sess.save(function(err) { console.log('saved sess is now ', sess);
helper.sendJsonResponse()
just responds with a 200 HTTP code and an empty body.
You can see that I am using the callback for session.save()
, as I only want to respond to the request when I KNOW that the session has been edited and saved.
However, this does not always work. If I set the colors in the session, then clear them (calling the api / clear route), then call the route to create the image (by calling the api / canvas route), the session on the api / canvas. The route session sometimes still has set colors.
This is similar to the case if I do it quickly. If I wait a few seconds, the colors will be cleared for the api / canvas route.
Note. I do not allow calls to these routes at the same time - I use promises and have a counter in the user interface that covers the entire screen until the requests are completely completed.
When this happens, the logs look like this:
saved sess is now { cookie: { path: '/', _expires: null, originalMaxAge: null, httpOnly: true }, canvasHeight: 500, canvasWidth: 591 }
And when I make an api / canvas request:
in canvas and sess is { cookie: { path: '/', _expires: null, originalMaxAge: null, httpOnly: true }, canvasHeight: 500, canvasWidth: 591, colors: { color1: 'red', color2: 'green' } }
so you can see, the colors property is still set. This occurs in approximately 50% of cases. The rest of the time, on the second request, the colors property was removed.
What could be wrong? I donβt understand how sessions work?
EDIT
This is getting weirder. If I link the calls in the user interface called the api / clear route, and then in the Promise then () method, call the api / canvas route, it ALWAYS works. If I call to make requests individually, the results are completely random - sometimes the session will be updated, sometimes it will not.
I checked req.sessionID
and it is always the same for different requests.
EDIT Using the regeneration method works correctly, but not perfect, since I am losing everything in the session.