Address the snack bar problem

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.

Answer №1

After spending hours speculating on a solution, I decided to experiment with adding a delete parameter.

This is how I addressed my issue:

module.exports = function (app) {

    /* GET profile page only if session exists */
    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,
                DeleteSnackbarMessage: delete req.session.snackbarMessage
            });
        }
    });
};

I haven't had the chance to test this fix yet, so I'm not entirely confident in its effectiveness. However, I believe it's a viable workaround for now.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using the 'client-side rendering' and runtime environment variables in Next.js with the App Router

In the documentation for next.js, it's mentioned that runtime environment variables can be utilized on dynamically rendered pages. The test scenario being discussed involves a Next.js 14 project with an app router. On the page below, the environment ...

In AngularJs, use ng repeat and ng switch to dynamically generate and display tables

I need help rendering a table with two columns using angularjs directives. <table> <tr ng-repeat="message in messages" > <td ng-switch-on="message.network" ng-switch when="twitter" ng-controller="TweetController"> <span> ...

Error: Firebase is not recognized as a valid function

I have been attempting to go through the firebase Node tutorial at this URL: Running my node.js app leads to a crash with a "TypeError: Firebase is not a function" error. Here is an excerpt from my index.js file: var Firebase = require("firebase"); var f ...

Is it possible to create a mongoose model that has a self-referencing field?

I've created a model that is structured like this const employeeSchema = new mongoose.Schema({ empFirstName:{ type: String, reuired: true }, empLastName:{ type: String, reuire ...

The error message "SharedArrayBuffer is not defined" occurred when attempting to utilize ffmpeg.wasm

<!DOCTYPE html> <html> <head> <title>TikTok Live Downloader</title> </head> <body> <h1>TikTok Live Downloader</h1> <label for="username">Username:</label> ...

Error: The requested resource does not have the 'Access-Control-Allow-Origin' header. The request is successful, but an error is being triggered

As I am trying to make an Ajax cross domain request, I have come across a strange issue. In the console of Chrome dev tools, I see the following error: "No 'Access-Control-Allow-Origin' header is present on the requested resource" Despite this ...

Guide on utilizing the <source> tag within v-img component in Vuetify.js?

When it comes to using webp images instead of jpg or png, some browsers may not support the webp format. In such cases, we can use the html tag < source > as demonstrated below, ensuring that at least a jpg image is displayed: <picture> < ...

When a user clicks on an element, use jQuery to show a specific

I am looking to extract the Admission ID field within a separate function that triggers when a user clicks on a button. $(document).ready(function () { $.each(data.student, function (i, item){ trHTML += '<tr>'+ ...

Steps to set up datetimepicker with varying date ranges for several input fields

I am having trouble getting a new date range for each text box in my form. It seems to only return the date range from the last textbox, even though I have made the textbox IDs dynamic. I have both start and end dates for each textbox and I have calculated ...

Unable to locate module '.next/server/font-manifest.json'

I'm encountering a frustrating issue while attempting to deploy my nextjs app with server rendering. The app was created using Azure Pipelines and then uploaded to a production server that runs on a Linux operating system. Below is the configuration ...

Attempting to manipulate the selected tab material using a custom directive with two-way data binding

I've been struggling to change the tab using code and can't seem to figure out what's causing the error. It works fine when I use the controller to change the variable, but when trying to bind it through a directive, it breaks. var app = an ...

Showing items in a VueJS component and transferring them to the component

Utilizing VueJS 2.0 and vue-router 2, my goal is to display a template based on route parameters. I have a view called WidgetView where components are dynamically changed. Initially, WidgetComponent is shown which displays a list of widgets. When a user se ...

Receiving a k6 response that includes a JSON object with a lengthy integer value

During a performance test, I encountered an issue where the response contained items like: {"item":{"id":2733382000000000049}} When parsed using k6's response.json(), it appeared as : {"item":{"id":273338200000 ...

What could be causing the error I'm encountering while attempting to utilize Array.includes as the function for Array.filter in my JavaScript code?

During a recent javascript project, I attempted something like the following code snippet. To my surprise, it did not work and instead produced an error message. const test = [1, 2, 3, 4]; const something = [1, 2, 3, 4, ,5, 6, 7, 8].filter(test.includes) ...

Using Regular Expressions in Javascript

I have gone through numerous posts with this title, but so far, none of them have addressed my specific query... My requirement is to utilize regex in the following format: "/^ user provided input $/i". The user can include the special regex character * e ...

Typescript is throwing an error with code TS2571, indicating that the object is of type 'unknown'

Hey there, I'm reaching out for assistance in resolving a specific error that has cropped up. try{ } catch { let errMsg; if (error.code === 11000) { errMsg = Object.keys(error.keyValue)[0] + "Already exists"; } return res.status ...

Next.js throwing an error: TypeError - attempting to read property 'map' of undefined

I am facing an issue with my Next Js project. I have implemented the backend logic to display data, but when I attempt to show all the data using the useEffect hook and the map function, I encounter the following error: TypeError: Cannot read property &apo ...

Is there a way to create a custom column in Tabulator that displays a calculated value for every row?

Can a custom column be added with a calculated value for each row? For example, if col 1 has the value "3" and col 2 has the value "5", then I want a dynamic col 3 with a sum value of 8. I am utilizing Vue Tabulator. Below is my Table.vue component. <t ...

The initial login attempt on the ExpressJS app is successful, but subsequent login history is

I recently created an application using ExpressJS, PassportJS, MongoDB with Mongoose, and JSON web tokens. When implementing the successful login route, I encountered the following code: await user.insertLoginTime(); const token = user.generateJwt(); res ...

I am currently facing some challenges with the http-proxy-middleware functionality

Having two servers in my backend requires me to use the http-proxy-middleware package, but I'm facing some issues. Below is my frontend code running on localhost:3000 axios("/api2/login",data) .then((res) => { }); Here is my backend ...