You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
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 reqandres.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
-
The text was updated successfully, but these errors were encountered:
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.localsIt'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
andres.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
-
The text was updated successfully, but these errors were encountered: