Adding property to the request using Node and Express Adding property to the request using Node and Express express express

Adding property to the request using Node and Express


You can add properties to request or response objects by creating a middleware and using it in your app. E.g.

// Defining middlewarefunction 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.


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