clifford.duke
clifford.duke

Reputation: 4020

Global variable for expressjs

I'm trying to pass data between functions that may change per request. Is there a way to globally store such details?

My Idea was to have an authCheck function that is handled whenver someone access any routes /*. that function will then check if their token is valid. If it is, the program continues, if it isnt, then it just stops there. If the token is valid, I wanted to set a variable for their ID that can be accessible without having to constantly do an SQL query in each function.

Upvotes: 0

Views: 1989

Answers (1)

Deathspike
Deathspike

Reputation: 8770

You can make a use function that always runs and attach data to req, like this example:

app.use(function (req, res, next) {
    // Just an example...
    db.query('SELECT * FROM tokens WHERE dat = ?', [req.cookies.token], function (err, result) {
        // Check token...
        if (err || results.length === 0) {
            next(err || 'Invalid token');
        } else {
            // Set in req obj for other functions to access
            req.token = results[0].dat;
            next();
        }
    });
});


app.get('/', function (req, res) {
    // Example render template with token attached...
    res.render('test', {token: req.token}); 
});

Upvotes: 4

Related Questions