patternjavascriptexpressCritical
Extend Express Request object using Typescript
Viewed 0 times
typescriptobjectextendrequestusingexpress
Problem
I’m trying to add a property to express request object from a middleware using typescript. However I can’t figure out how to add extra properties to the object. I’d prefer to not use bracket notation if possible.
I’m looking for a solution that would allow me to write something similar to this (if possible):
I’m looking for a solution that would allow me to write something similar to this (if possible):
app.use((req, res, next) => {
req.property = setProperty();
next();
});Solution
You want to create a custom definition, and use a feature in Typescript called Declaration Merging. This is commonly used, e.g. in
Create a file
This will allow you to, at any point in your code, use something like this:
method-override.Create a file
custom.d.ts and make sure to include it in your tsconfig.json's files-section if any. The contents can look as follows:declare namespace Express {
export interface Request {
tenant?: string
}
}This will allow you to, at any point in your code, use something like this:
router.use((req, res, next) => {
req.tenant = 'tenant-X'
next()
})
router.get('/whichTenant', (req, res) => {
res.status(200).send('This is your tenant: '+req.tenant)
})Code Snippets
declare namespace Express {
export interface Request {
tenant?: string
}
}router.use((req, res, next) => {
req.tenant = 'tenant-X'
next()
})
router.get('/whichTenant', (req, res) => {
res.status(200).send('This is your tenant: '+req.tenant)
})Context
Stack Overflow Q#37377731, score: 363
Revisions (0)
No revisions yet.