Search code examples
javascriptnode.jsexpressbackendexpress-router

(Express)How to pass a value from function to another one in express.Router().get


How I can pass value from function to another one at router.get

router.get('/someurl', (req, res, next) => {
const token = req.headers.authorization.split(' ')[1] //jwtToken
const jwt = jwt.verify(
    token,
    jwtSecret
)
...do something to pass value to the next function
}, )

Solution

  • You can use res.locals to do that

    An object that contains response local variables scoped to the request, and therefore available only to the view(s) rendered during that request / response cycle (if any).

    So in your case

    router.get(
      "/someurl",
      (req, res, next) => {
        const token = req.headers.authorization.split(" ")[1]; //jwtToken
        const jwt = jwt.verify(token, jwtSecret);
        // pass to res.locals so I can get it in next() middleware
        res.locals.token = token;
        next();
      },
      (req, res, next) => {
        // inside the next() middleware
        // get token from res.locals
        const previousToken = res.locals.token;
      }
    );