sasha sasha - 1 year ago 110
Node.js Question

ExpressJS > router middleware > passing variable via redirect not working

Let's say I have this:

a) 2 routes with 1 middleware function each and a callback function:'/foo', fooCtrl, function(req, res)

router.get('/bar', barCtrl, function(req, res)

b) 2 middleware function expressions

fooCtrl = function(req, res, next)
{ = 'foo';


barCtrl = function(req, res, next)
console.log(; // output is 'undefined'


As you can see, in the fooCtrl I'm setting a variable - and in this scope it is set than... but I'm not able to call this variable in the barCtrl-scope.

Isn't the req object passed by reference?

Any suggestions or best practices?

The purpose of this is to pass a token after login from the login-controller to an admin-controller .. something like that.

Answer Source

That is the expected behaviour. req object is created anew for each new request and your redirection i.e. res.redirect('/bar') results in a new request.

Solution: You may use some package e.g.connect-flash which stores variables in a temporary session object, which can be used only once. You need to set required values in your flash objects before redirecting. Then after redirection, you will be able to get the saved values from the flash object itself.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download