We have a large API written in Express and Typescript, and this is how we handle such scenarios:
We keep the request definitions in one file:
import { Request } from "express"
export interface IGetUserAuthInfoRequest extends Request {
user: string // or any other type
}
And then in the file where we are writing the controller functions:
import { Response } from "express"
import { IGetUserAuthInfoRequest } from "./definitionfile"
app.get('/auth/userInfo', validateUser, (req: IGetUserAuthInfoRequest, res: Response) => {
res.status(200).json(req.user); // Start calling status function to be compliant with Express 5.0
});
Be advised that “user” is not a property that is available natively in the Request object of Express. Make sure that you are using a middleware that adds such property to the request object.