Adding property to the request using Node and Express

10,125

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

Share:
10,125
Joao
Author by

Joao

I'm a Game Developer, who likes to explore and discover.

Updated on June 18, 2022

Comments

  • Joao
    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
    Joao almost 8 years
    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?
  • k10der
    k10der almost 8 years
    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.
  • ptoinson
    ptoinson almost 3 years
    Dead link. SO Answer fail.
  • AxDu
    AxDu over 2 years
    @ptoinson sorry.. Just updated the link ! :)