Add properties to the req object in expressjs with Typescript

Viewed 3381

I tried to migrate my express server code from js to typescript and ran into issues when trying to access fields I added to the request object in my own middleware functions.

For example, I am doing something like this:

app.use((req, res, next) => {
    let account = checkAuthentication(req);
    if(account) {
        req.authenticated = true;
        req.account = account;
        next();
    }
});

Now I want to access those properties later on in my other middleware functions, but the .d.ts file from @types/express defines the req object the same way for all middleware functions of course.

Now I came up with two ways to deal with this, but both seem bad:

  1. Use a typeguard in every middleware function. But then I add useless code to the js output because my routes are setup in a way so that I know at "compile" time what shape my req object has in each middleware function.
  2. Use a type assertion in every middleware function. But then I don't get the benefits of typescript, despite writing my code so that all types are know at compile time, because I basically disable typechecking for the req object then.

So my question is: How, if at all, can I utilize typechecking in that scenario? If I can't, does that mean a framework like express is impossible in a statically typed language (like C#)?

1 Answers

You can use module augmentation to extend the Request type defined in the express module

declare global {
    namespace Express {
         export interface Request {
              account: Account;
              authenticaticated: boolean 
         }
    }
}
Related