In my quest to create a custom snackbar, I have encountered a minor issue with setting and deleting session variables in Node.js. While using global or local variables works well for accessing data on the client side, there is a chance of issues when multiple users interact with the site simultaneously, such as during login.
To tackle this, I switched to using req.session to store user login information along with the snackbar message. The initial setup looked like this:
req.session.snackbarMessage = "You're logged in!";
However, when it came time to delete the snackbarMessage, I faced some challenges. The following attempt did not yield the desired result:
delete req.session.snackbarMessage;
This led me to wonder if the problem was related to the placement of the delete statement within the code. Specifically, I suspected that the issue might lie within my profile route function, where I intended to clear the snackbarMessage upon successful login:
module.exports = function (app) {
/* GET profile page unless a session does not exist */
app.get('/profile', function(req, res) {
if (req.session.userInfo == undefined) {
res.redirect('/login');
} else {
res.render('pages/profile', {
user: req.session.userInfo,
snackbarMessage: req.session.snackbarMessage
});
/* Clearing the message to avoid repeating */
delete req.session.snackbarMessage;
}
});
};
As part of the login flow, just before redirecting to /profile, I set the snackbarMessage for the user:
req.session.snackbarMessage = "You're logged in!";
If anyone can offer guidance on resolving this issue or point me in the right direction, I would greatly appreciate it.