Adding property to the request using Node and Express
Solution 1
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.
Solution 2
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
Comments
-
Joao almost 2 years
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 almost 8 yearsDoesn'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?
-
k10der almost 8 yearslt 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.
-
ptoinson almost 3 yearsDead link. SO Answer fail.
-
AxDu over 2 years@ptoinson sorry.. Just updated the link ! :)