How do I extend the typings of Express.Application to give typings for app.locals

Viewed 311

In our application, we're adding quite a few config objects to app.locals that get used in our middleware.

const app = Express();
app.locals = {
  someConfig: config
}

We currently have custom typings for the Request object that work without fail

declare namespace Express {
  export interface Request {
    featureFlags?: FeatureFlag;
  }
}

I know locals comes from Express.Application so I tried this, and it doesn't work.

declare namespace Express {
  export interface Application {
    locals: {
      someConfig: config;
    };
  }

  export interface Request {
    featureFlags?: FeatureFlag;
  }
}

Has anyone successfully added types to app.locals?

1 Answers

Instead of using a new declaration file, you can go to the original file declaration in node_modules/@types/express-serve-static-core/index.d.ts. And Search for the Application interface. The trick is to define another property on that interface, and all your routes will have access to that, similar to the locals property.

  export interface Application<
    Locals extends Record<string, any> = Record<string, any> 
> extends EventEmitter, IRouter, Express.Application {
    //Make sure to keep all the others properties on the interface
    locals: Locals 
    db: mongoDb.Db //Here is the db key I've added, and all my routes can access it, just like the locals property.

 ];
}

Now you can assign a value to that property with app.db ="whatever you need" with all the autocompletion. And within your routes handler or middleware you can have access to it with req.app.db.

Related