auth0 / express-jwt

connect/express middleware that validates a JsonWebToken (JWT) and set the req.user with the attributes

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Proposal: Use `res.locals` (in addition?)

Fabb111 opened this issue · comments

commented

Describe the problem you'd like to have solved

It's hard to work with the req.auth approach when working with TypeScript - I either have to globally pollute my req object and destroy the type safety for all routes that don't use the middleware, or I have to declare my own type which gets really tedious if you have multiple middlewares and middleware combinations that all directly write into the req object.

Describe the ideal solution

Luckily, there is a solution baked into express since a long time called res.locals: https://expressjs.com/en/api.html#res.locals

This property is useful for exposing request-level information such as the request path name, authenticated user, user settings, and so on to templates rendered within the application.

It's the perfect use-case, even per the documentation. Per default the locals field is Record<string, any> so it allows access without needing to explicitly specify a type. But if you want type-safety, it's possible to easily give the locals object a type with generics (no need to overwrite the inbuilt Request type or any of that nonsense).

It's also possible to keep the compatibility without introducing a breaking change by just adding it to req and res.locals.

Alternatives and current work-arounds

As already mentioned, globally polluting the type, manually creating overwritten types or doing (req as any).auth (🤢).

Additional context

-