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?
Asked
Active
Viewed 1.6k times
10

Joao
- 268
- 1
- 2
- 9
2 Answers
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.
-
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
-
3lt 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
-
-
-
This is important information for TypeScript users. Link targets can always change, so it is good practice to copy the relevant part into the answer. Would be great if you would do so. – JSchirrmacher Jan 19 '23 at 05:43