Jab2Tech
Jab2Tech

Reputation: 165

NodeJS: Making routing level variables in expressJS

I am new to express. I am confused on how can I set a variable in a helper function and later use that within the app.get() function.

var authenticate = (req,res,next) => {

// I need to set a user specific variable here
next();

}

app.use(authenticate);

app.get("/",(req,res)=>{

// I need to access the variable here.

});

Please note that the variable value can vary between different browser calls. So the variable should have a scope just for the call. I am confused on how to set it? Anyone can help?

Upvotes: 1

Views: 48

Answers (1)

Alejandro Vales
Alejandro Vales

Reputation: 2937

The best would be to add it to the req scope, here you have some documentation about it http://expressjs.com/en/api.html#req

var authenticate = (req,res,next) => {

    req.authenticatedUser = {name: 'a'}
    next();

}

app.use(authenticate);

app.get("/",(req,res)=>{

    console.log(req.authenticatedUser);

});

Upvotes: 1

Related Questions