1

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?

2
  • 1
    Is the import correct? From the docs, it should be: import { rateLimit } from 'express-rate-limit' Commented Sep 23 at 15:30
  • @Rasul It works either way. We recommend the named import because "naked" imports have a few weird edge cases, but that's not the issue here. Commented Oct 17 at 15:52

1 Answer 1

0

This is just TypeScript being TypeScript. You know that it's an AuthRequest with a .user property added to it, but TypeScript doesn't and express-rate-limit doesn't. Try this:

rateLimit({
  limit: ...,
  windowMs: ...,
  message: ...,
  keyGenerator: (req: Request) => (req as AuthRequest).user.id,
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.