I am re-generating the session-id
after the user logs-in,the new session id gets generated and i am also saving that session-id in mongodb but the issue is how do i send the re-generated session-id back to the user-agent(browser) with the user object.
I have already tried:
res.cookie('sessionId',req.session);
res.json(user);
I am re-generating session-d like this:
let session = req.session;
console.log("printing old session");
console.log(req.sessionID);
req.session.regenerate(function(err) {
if (err) console.log(err);
else{
console.log("printing new session");
console.log(req.sessionID);
let prev_session = session;
//Copying Prev Session Data to current session.
for (let i in prev_session) {
req.session[i] = prev_session[i];
}
req.session.save();
}
})
the above code returns the user object with session-id in header as :
set-cookie: sessionId=j%3A%7B%22cookie%22%3A%7B%22originalMaxAge%22%3A86400000%2C%22
expires%22%3A%222018-07-10T06%3A16%3A16.703Z%22%2C%22secure%22%3Afalse%2C%22httpOnly%22%3Atrue%2C%22
path%22%3A%22%2F%22%7D%2C%22_csrfSecret%22%3A%22fYvLa6exta46VA%3D%3D%22%2C%22passport%22%3A%7B%22
user%22%3A%225b1fcebb293e95fc28cafc97%22%7D%7D; Path=
with this previous sessionid :
set-cookie: sessionId=s%3AZ4HI3m3LzPcxRlp8HVEb4YzIGq3FuZbC.07kibg%2FguTNBTPlO5%2BTfHSkDh7GcQEzenlSqODetvb8;
Path=/; Expires=Tue, 10 Jul 2018 06:16:29 GMT; HttpOnly
still i am unable to see the updated session-id in session cookie of my chrome browser
My backend is powered by express and passport.
can anyone please help me in this...i have already spend a lot in browsing this issue and have'nt got any working solution.
Thanks in adavnce.
I'm not entirely sure why are have sessionId
, req.sessionID
, req.session
in your code, because all of them are different things.
Using cookie-parser
:
Write cookie:
res.cookie('myCookieName',myValue)
Read cookie:
req.cookies.myCookieName
If your new regenerated session ID is in req.sessionID
then use that while setting the cookie and not req.session
I have a basic example that should guide you for your implementation:
const express = require('express'),
cookieParser = require('cookie-parser');
const app = express();
var i =0;
app.use(cookieParser());
app.get('/', (req, res) =>{
console.log("Previous cookie: ",req.cookies.sessionId);
res.cookie('sessionId',{i:++i, maxAge: 900000, httpOnly: true });
res.send('Hello World!')});
app.listen(3000, () => console.log('Example app listening on port 3000!'));
This will print the cookie sent in the request, and then send back a new one. In every request, you will see a different number printed on the node console.