10

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?

Joao
  • 268
  • 1
  • 2
  • 9

2 Answers2

18

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.

GMachado
  • 791
  • 10
  • 24
k10der
  • 716
  • 1
  • 10
  • 15
  • Doesn't it affect performance? I mean, it would have to reset through each routes, I wanted it to be something like individual, much like user information, is it related to sessions or something like that? – Joao May 09 '16 at 23:05
  • 3
    lt doesn't affect performance much. And you should always remember, that premature optimization is an evil. Request object is being created for each individual request from a client, so you can store client-related information here. If you add this middleware after passport middleware, then you'll get an access to user property, sessions etc. as in every request handler. – k10der May 10 '16 at 03:23
6

To add extra properties to the request and response object you need to extend the response and request interface.

index.d.ts files are used to provide typescript type information about a module that’s written in JavaScript.For express, the index.d.ts is present inside the @types/express folder inside the node_modules folder.

Use this link- https://dev.to/kwabenberko/extend-express-s-request-object-with-typescript-declaration-merging-1nn5

AxDu
  • 139
  • 1
  • 9