I’m trying to create a keyGenerator function for express-rate-limit that uses user.id as the key:
import rateLimit from 'express-rate-limit';
rateLimit({
limit: ...,
windowMs: ...,
message: ...,
keyGenerator: (req: Request) => req.user.id, // TS error
})
TS says:
Property 'user' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'.
So, I tried extending Request with a custom type:
type AuthRequest = Request & {
user: {
id: string
}
}
rateLimit({
limit: ...,
windowMs: ...,
message: ...,
keyGenerator: (req: AuthRequest) => req.user.id, // Still error
})
But now I get:
Type '(req: AuthRequest) => string' is not assignable to type 'ValueDeterminingMiddleware<string>'.
Types of parameters 'req' and 'request' are incompatible.
Type 'Request<...>' is not assignable to type 'AuthRequest'.
How am I supposed to correctly type req.user for my keyGenerator?
import { rateLimit } from 'express-rate-limit'