I am looking to create a custom property on the request as early in the request lifecyle as possible, the use case for this is so that I can store the users profile (fetched from the DB) and store this in the request so that in my controller methods I can access it easily without having to inject the ProfileService and fetching it in the controller.
I am hoping to just fetch it from the Req() req instead. (i.e. req.profile.
I thought that an option would be to set this property in my JWT Strategy:
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor() {
super({
passReqToCallback: true,
secretOrKeyProvider: passportJwtSecret({
cache: true,
rateLimit: true,
jwksRequestsPerMinute: 5,
jwksUri: `https://${process.env.AUTH0_DOMAIN}/.well-known/jwks.json`,
}),
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
audience: `https://${process.env.AUTH0_AUDIENCE}`,
issuer: `https://${process.env.AUTH0_DOMAIN}/`,
});
}
validate(request: Request, payload: JwtPayload) {
// SET A CUSTOM REQUEST PROPERTY HERE FOR PROFILE
return payload;
}
}
I guess I have two questions:
- Is this the right way? Any pros/cons to this?
- How to save a custom property on the request object for use later on? I've attempted
request.profile = 'test'but this throws errors?
Express's
Requestdoesn't have aprofileproperty, nor does it have a general[index: string]: anytype so that you can tack on whatever you want. To get around this, you can create a custom type that extends theRequesttype with the properties you need.