I\'m having a problem with sessions, where sometimes the session variable I just set is undefined on the next page request. I typically have to go through the flow
I filed an issue against Express about github, but figured out what was wrong a few minutes later. Not sure if you're having the same problem, but for completeness:
In my case, I was testing by going to http://localhost:8003 but the OAuth provider was redirecting to http://hostname:8003. Same box/server/webpage, but different domain names means the browser sends different cookies and consequently, express gets different session ids and session data. As soon as I started testing at http://hostname:8003, everything worked just fine.
My code was similar to yours, structurally. In my case, however, my POST operation originated from the JQuery $.post function. I don't know if that makes an appreciable difference, however
What I ended up having to do was send a "junk" response at the end of the POST operation definition in my express routing routine, i.e.
res.send("hoo hee ha ha unimportant junk data");
By including this at the end I was able to trigger a success function (the callback for the AJAX post attempt). I inserted the redirect there, instead of placing it in the express routes.
Use with AJAX Post window.redirect();
Do not use with AJAX Post: $res.redirect("someurl");
This is because browsers apparently will not redirect on AJAX response, so you have to use Javascript, as described here: Express js - can't redirect
Hope that helps someone, it fixed the problem for me, peace.
Just struggled with the same problem and got it resolved. The simple answer is to call
Session.save()
explicitly, if you cannot reply on express-session to call it for you at the end of the response.
Reference
In Connect's session, any handler can set req.session.anything
to any value, and Connect will store the value when your handler calls end()
. This is dangerous if there are multiple requests in flight at the same time; when they finish, one session value will clobber the other. This is the consequence of having such a simple session API (or see the session source directly), which has no support to atomically get-and-set session properties.
The workaround is to try to give the session middleware as few of the requests as necessary. Here are some tips:
express.static
handler above the session middleware.req.session
by saying express.session.ignore.push('/individual/path')
.req.session = null;
before calling res.end();
. Then it won't be re-saved.If only one request does a read-modify-write to the session at a time, clobbering will be less likely. I hope that in the future, Connect will have a more precise session middleware, but of course the API will be more complicated than what we have now.