Typescript Error: Property 'user' does not exist on type 'Request'
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.
req is probably of type Request from "express" package and user does not exist there. You have to either extend Request with own router handler or cast it to type any or object.
try res.json(req['user'])
or res.json( (<any>req).user )
You may also use module/global augmentation
import { Request } from "express"
declare module "express" {
export interface Request {
user: any
}
}
You can also make your own handler wrapper (instead of extending Router functionality in ExpressJs).
import * as express from 'express';
interface IUserRequest extends express.Request {
user: any
}
function myHandler(handler: (req: IUserRequest, res: express.Response, next?: express.NextFunction) => any) {
return (req: express.Request, res: express.Response, next: express.NextFunction) => {
try {
validateUser(req, res, (err) => { // your validateUser handler that makes a user property in express Request
if(err)
throw err;
let requestWrapper: IUserRequest = <IUserRequest>req;
handler(requestWrapper, res, next);
})
}
catch (ex) {
next(ex);
}
}
}
let app = express();
// init stuff for express but this.validateUser handler is not needed
app.use('/testuser', myHandler((req, res) => {
res.json(req.user);
}));