javascriptnode.jsexpressmiddleware

Passing variables to the next middleware using next() in Express.js


I want to pass some variable from the first middleware to another middleware, and I tried doing this, but there was "req.somevariable is a given as 'undefined'".


//app.js
..
app.get('/someurl/', middleware1, middleware2)
...

////middleware1
...
some conditions
...
res.somevariable = variable1;
next();
...

////middleware2
...
some conditions
...
variable = req.somevariable;
...

Solution

  • Attach your variable to the res.locals object, not req.

    Instead of

    req.somevariable = variable1;
    

    Have:

    res.locals.somevariable = variable1;
    

    As others have pointed out, res.locals is the recommended way of passing data through middleware.