Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Proposal: Use res.locals (in addition?) #325

Open
FabianKoder opened this issue Mar 7, 2023 · 0 comments
Open

Proposal: Use res.locals (in addition?) #325

FabianKoder opened this issue Mar 7, 2023 · 0 comments

Comments

@FabianKoder
Copy link

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

-

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant