Home > Mobile >  Passing global variable to another controller file in Node.js
Passing global variable to another controller file in Node.js

Time:03-02

I have created a global variable (userEmail) which holds the value of current user. Post request handles the authorization and assigns the email of current user to that global variable. Issue comes when exporting that global variable (userEmail) to another file. Another file reads it as 'not assigned', maybe because the module.export runs before the route.post. What can be the solution to have the global variable in another file altered by the route.post assignment to the current user?

var userEmail = 'not assigned';


route.get('/', (req, res) => {
    res.render('signIn');
})

route.post('/', (req, res) => {
    let email = req.body["sign-in-email"];
    let password = req.body["sign-in-password"];

    let errorMessage = '';

    userModel.findOne({ 'email': email }, 'email password balance', function (err, user) {
        if (err) return handleError(err);
        if (email == user.email) {
            if (bcrypt.compareSync(password, user.password)) {   // function returns true if password matched the database hashed password
                userEmail = user.email;
                exports = {userEmail};
                res.render('dashboard', { email: userEmail , balance: user.balance})
                console.log(userEmail)
            } else {
                errorMessage = 'Invalid password'
                res.render('home', { errorMessage: errorMessage });
            };
        } else {
            errorMessage = 'User Not Found'
            res.render('home', { errorMessage: errorMessage });
        }
    });
})

    module.exports = {route, userEmail};

CodePudding user response:

NodeJS has a global variable that you can use to manage global values. Here is a sample for the global variable, If you have a logger class and you want to have its instance globally in your environment, you can do like this,

    global.logger = new Logger()

CodePudding user response:

I have created a global variable (userEmail) which holds the value of current user.

This is your first problem. There is no such thing as the "current user". There can be multiple users who are all making requests to your http server and whose requests are in process.

You cannot keep request-specific state or user-specific state in global variables. Either add that info state to the req object for the request so other parts of processing the request can all access it from there (that's what middleware does), add it to a user-session that is tied to a specific user and accessible from any request from that user or pass that state to any function that might need it while processing the response for a specific request.

You cannot put user-specific state into a global variable. Multiple requests from different users will overwrite the global and state will get mixed up between requests from different users.


Separately, this structure:

module.exports = {route, userEmail};

exports the current value of userEmail at the time the module is initialize (which will be 'not assigned' in your code). As the value of your userEmail variable changes, the export never changes. So, besides the fact that this isn't the right structure for a request-specific variable (as explained above), you also can't export something like this either.


In your specific situation, it appears you want the userEmail value to be available for future requests from that user. There are several ways to do that, but I would recommend using express-session and adding the userEmail to that user's session object. That session object will then be tied to requests from that specific user (via a sessionID stored in a cookie) and the data in the user's session object will be available with all future request from that user (within the configured time limit of the session cookie).

  • Related