Why express session sometimes does and sometimes doesn't make cookies? - node.js

I am using cookies like this on my express server :
app.use(
session({
secret: "someStringForSecretKey",
resave: false,
store: new redisstore({ client: RL }),
saveUninitialized: false,
cookie: {
maxAge: 1000 * 60 * 60 * 24,
httpOnly: true,
secure: true,
sameSite: "none",
},
})
);
and sending back the data via axios like this :
axios.defaults.withCredentials = true;
axios.post(`${import.meta.env.VITE_HOSTNAME}/auth`, {
username: userRef.current.value,
password: passwordRef.current.value,
}).then(function (response) .......
I am setting the session as such :
req.session.user = req.body.username;
req.session.save(()=>{
if(req.session.user ){
res.status(200).json({
foo : true
});
}
Now to my surprise the cookie is sometimes set and sometimes isn't. There is no pattern.
Why express session sometimes does and sometimes doesn't make cookies?

httpOnly: true,
Creates undesirable behavior in which it sometimes creates the cookie and sometimes doesn't.
httpOnly: false,
Solved the issue.

Related

I'm trying to connect to redis.com but I'm unable to

I created a redis database at redis.com, but I'm unable to connect to it to store my sessions in nodejs.
Here's what I did:
var redisClient = redis.createClient('redis://<db-name>:<host>:<port>');
app.use (
session ({
store: redisClient ? new RedisStore({
client: redisClient
}) : null,
secret: "x",
resave: false,
saveUninitialized: true,
// proxy: true,
// rolling: true,
cookie: {
expires: new Date(Date.now() + (30*24*3600000)),
secure: true
}
})
);
I get the error Error: The client is closed
`Does anyone know why?

Express Session lose data before cookie expires

I'm using express-session with redis in my NodeJS Backend.
let redisClient = redis.createClient(6380, process.env.REDISCACHEHOSTNAME, {auth_pass: process.env.REDISCACHEKEY, tls: {servername: process.env.REDISCACHEHOSTNAME}});
app.use(session({
store: new RedisStore({ client: redisClient }),
saveUninitialized: false,
secret: process.env.secret,
resave: true,
cookie: {
maxAge: 1 * 1 * 60 * 60 * 1000
}
}));
On login I store some user details in the session:
req.session.user = result;
And I build a middleware, which log my current session and refresh it on each request:
isOnline = (req, res, next) => {
console.log(req.session);
if (!req.session.user) {
return res.status(401).json({ result: 'Keine Session vorhanden', status: 'failure' });
}
req.session.touch();
next();
};
The extending of my cookie is working well. The cookie expiration datetime is everytime reset to 60 minutes from the request time. Which I can see by the console.log:
Session {
cookie: {
path: '/',
_expires: 2022-03-07T18:46:30.727Z,
originalMaxAge: 120000,
httpOnly: true
},
user: { ... }
}
The issue is, that my user data are lost after 60 minutes. So the cookie itself refreshs, but not the data. So how I can avoid this?

Express-session with MySQL storage does not save user

I'm using express-session for handling user session in Node.js application. The problem is after rewriting it for MySQL storage it seems like after changing route all information disappears and my middleware redirects me for login page again.
My code:
let options = {
host: "localhost",
user: "root",
port: 3306,
password: "",
database: "cursova"
}
var sessionStore = new MySQLStore(options, con);
app.use(session({
key: 'myCookie',
secret: 'secret12345',
store: sessionStore,
resave: false,
saveUninitialized: false,
cookie: {
originalMaxAge: 1000 * 60 * 5,
maxAge: 60000 * 5,
secure: true,
path: '/',
}
}));
console results:
Try initializing the session:
app.use((req, res, next) => {
req.session.init = "init";
next();
});
For session, I have this:
const options = {
host: config.db.host,
port: config.db.port,
user: config.db.user,
password: config.db.password,
database: config.db.database
};
const sessionStore = new MySQLStore(options);
const expiryDate = new Date(Date.now() + 24 * 60 * 60 * 1000); // 1 hour
app.use(session({
store: sessionStore,
secret: process.env.SESSIONSECRET,
resave: false,
saveUninitialized: false,
cookie: {
//secure: true,
//httpOnly: true,
expires: expiryDate
}
}));
I am not passing the connection and do not have a key. I add in the HTTP and secure once I know it works.
Most likely the issue is because of "secure: true" from cookie. This means the cookie is saved only if you use HTTPS. Try setting it to false

nodejs session cookie browser storage

Server is nodejs with express-session, passport, express
I want to avoid saving a cookie when the user is not authenticated, is this possible?
var sessionStore = new session.MemoryStore;
app.use(session({
cookie: { maxAge: null,
httpOnly: true,
secure: true,
},
store: sessionStore,
resave: 'false',
secret: 'somthing',
name: "id",
saveUninitialized: false
}));
Is it somehow possible to only store the cookie when the user did successfully login? Thanks!
You have to create an express-session: https://www.npmjs.com/package/express-sessions
and then store the session like this:
let session = require("express-session");
app.use(session({
secret: "secret",
resave: false,
saveUninitialized: true,
cookie: {secure: true,
httpOnly: true,
maxAge: 1000 * 60 * 60 * 24
}
}));
This session will be stored during your visit on the webpage. If you want to set values to the cookie, simply request the cookie in a request and set somekind of value:
router.route("/login")
.post(function(req, res) {
req.session.Auth = req.body.user // => user values?
})
OR
You can use cookie-session(https://www.npmjs.com/package/cookie-session)
If you use cookie session then if you made any changes to session variable or from server side, then no need to restart server.
app.use(cookieSession({
name: 'session',
keys: ['key1', 'key2']
}))
app.get('/', function (req, res, next) {
// Update views
req.session.views = (req.session.views || 0) + 1
// Write response
res.end(req.session.views + ' views')
})

NodeJS | How to be logined after closing browser using passport and express?

I use in my project express and passport for working with session and it works fine instead of one problem. When i close browser my session deserialized and this is fine, but i need to be logined after connecting again. Should i save information in cookies or use another package in npm? A little bit about my code:
app.use(session({
secret:'secret',
maxAge: new Date(Date.now() + 3600000),
httpOnly: true,
cookie: { path: '/', httpOnly: true, maxAge: null},
store: new MongoStore(
{mongooseConnection:mongoose.connection},
function(err){
console.log(err || 'connect-mongodb setup ok');
})
}));
app.use(passport.initialize());
app.use(passport.session());
As you can see i use a common passport+express program. Just give me any good tips for searching.
Solution is change cookie: { path: '/', httpOnly: true, maxAge: null} to cookie: { path: '/', httpOnly: true, maxAge: 36000000}

Resources