expresspropertiesrequestmean

Adding property to the request using Node and Express


I have a MEAN application, and I'm handling authentication using passport. What I want to do is exactly what happens to the user on the passport, which can be accessed from the request like req.user. I have not found any solutions to reach that result. Can you give me any advice?


Solution

  • You can add properties to the request or response objects by creating a middleware and using it in your app. E.g.

    // Defining middleware
    function myMiddleware(req, res, next) {
      req.myField = 12;
      next();
    }
    // Using it in an app for all routes (you can replace * with any route you want)
    app.use('*', myMiddleware)
    

    Now all your request objects in your handlers will have myField property.