I use NodeJS and express-session
to store session information on the database, per Log user out of previous sessions . The relevant code is in the main script file:
const session = require('express-session');
const MongoDBStore = require('connect-mongodb-session')(session);
// Initialize mongodb session storage to remember users.
const store = new MongoDBStore({
uri: config.mongoUri,
// The 'expires' option specifies how long after the last time this session was used should the session be deleted.
// Effectively this logs out inactive users without really notifying the user. The next time they attempt to
// perform an authenticated action they will get an error. This is currently set to 3 months (in milliseconds).
expires: max_session_ms,
});
// Enable sessions using encrypted cookies
app.use(cookieParser(config.secret));
app.use(
session({
cookie: {
// Specifies how long the user's browser should keep their cookie, probably should match session expiration.
maxAge: max_session_ms
},
store: store,
secret: config.secret,
signed: true,
resave: true,
saveUninitialized: true,
httpOnly: true, // Don't let browser javascript access cookies.
secure: config.secureCookies, // Only use cookies over https in production.
})
);
and in the routes file:
passport.use('user-otp', new CustomStrategy(
// code to validate one-time password.
));
The problem is that this method also stores cookies on the browser for users not logged in. Here is an example for a visit to a public page:
I want to store cookies only after creating an account or logging in, where the user consented to cookie policies, and not on public pages to avoid the "cookie consent box" required by GDPR.
How can I store cookies only after a browser logs in?
update
I followed the suggestions in the answer and eliminated two cookies. I stop the server, eliminate localhost
's cookies, start the server, make a public page request, and I still have one cookie on public pages. This is the session data on the server's database:
> db.sessions.find().pretty()
{
"_id" : "DObp-FFNJGLD5c5kLKWfkCaEhfWHtWpo",
"expires" : ISODate("2022-03-03T19:41:29.807Z"),
"session" : {
"cookie" : {
"originalMaxAge" : 7776000000,
"expires" : ISODate("2022-03-03T19:41:29.807Z"),
"secure" : null,
"httpOnly" : true,
"domain" : null,
"path" : "/",
"sameSite" : null
},
"flash" : {
}
}
}
and the browser shows this cookie:
I get the same results when I remove PassportJS
from the app and when I set sameSite
to "strict"
.
second update
As the database session has an empty flash
field, I suspected it was due to flash messages. I removed this code:
const flash = require("express-flash");
app.use(flash());
and now the server does not store a cookie for visits to public pages. I use flash messages in notifications for users who login and also for public page visitors, e.g. when a page is no longer available.
So the question becomes: is it possible to use flash messages server-side only, from one handler to another, and not store a cookie?