Skip to content

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

Open
@FabianKoder

Description

@FabianKoder

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

-

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions