Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 970
Joao Avatar asked May 09 '16 14:05

Joao


1 Answers

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.

like image 128
k10der Avatar answered Oct 18 '22 21:10

k10der