Categories
Nodejs TypeScript Answers

How to extend Express request object using Typescript?

Spread the love

Sometimes, we want to extend Express request object using Typescript.

In this article, we’ll look at how to extend Express request object using Typescript.

How to extend Express request object using Typescript?

To extend Express request object using Typescript, we can declare our own type definition for the request object.

For instance, we write

custom.d.ts

declare namespace Express {
  export interface Request {
    tenant? : string
  }
}

to add the tenant property to the type definition of the request object.

Then we include custom.d.ts in tsconfig.json so the TypeScript compiler will pick up the type.

Finally, we can add the tenant property to the request without TypeScript errors like

router.use((req, res, next) => {
  req.tenant = 'tenant'
  next()
})

router.get('/who', (req, res) => {
  res.status(200).send(req.tenant)
})

Coclusion

To extend Express request object using Typescript, we can declare our own type definition for the request object.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *