positron
positron

Reputation: 3693

Sharing one class instance in Express application

I have an application where I'd like to share a singleton class - at the start of application singleton is created, user specific data is set and used throughout the application. This works well now, but I am not sure how this approach will behave when multiple users access the application. I am thinking that this is not thread safe and cause shared data to be overwritten by different processes that use it. Is this correct?

Upvotes: 1

Views: 928

Answers (1)

Heiko Theißen
Heiko Theißen

Reputation: 16728

I am thinking that this is not thread safe and cause shared data to be overwritten by different processes that use it.

That is correct.

What do you mean by "used throughout the application"?

  • Data related to the user that remains even if the user logs off and logs on again later? That would require a database.
  • Or data that is needed only between logon and logoff?

In the latter case you need session handling where data is associated with one browser session (technically a session cookie that is deleted when the browser is closed). An example is the express-session package that allows you to write all session-related data into the req.session object and this object will be re-used by all requests made with the same session cookie (that is, all requests the user's browser makes to your application until the browser is closed).

The req.session object must be serializable by JSON, however, so it cannot be a class instance. See this example in the package documentation.

Alternatively, if the data are needed only during one request (shared by several middleware functions), you can write them into res.locals. This can even hold class instances.

Upvotes: 1

Related Questions