Global objects in expressjs

I'm developing a school management system. When a teacher sends a post request, in my backend I'm creating a global object inside a route. So when multiple teachers access the server, multiple global objects will be created.... Or every teacher accesses the same object?(will it be the same object owerwritten?)

Upvotes: 0

Views: 58

Answers (1)

Himanshu Singh
Himanshu Singh

Reputation: 1010

I really hope by creating a global object inside a route you mean that you are creating a property on -

1. global object itself - global.myGlobalObj = { some-var: 'some-val' } or

2. process object - process.myGlobalObj = { some-var: 'some-val' } or

3. express-app - maybe something like app.set('myGlobalObj', someOb)

or maybe on some other global object. In that case every request-response cycle will gain access to the same object.

But this practice is strictly not recommended for any type of system that you intend to develop. Primary reasons being -

  1. It is volatile. Once your application crashes, every request that depends upon the current value of your global object won't complete properly as that value was already lost/reset with the crash.

  2. It does not abide the principle of REST architecture which says that every request must be stateless and should contain enough data/params required to complete the request successfully on its own.

  3. Globals is one of the reason of the existence of Object Oriented Programming and Functional Programming paradigm. global variables makes your application more vulnerable, less understandable and hard to test.

Solutions

If the performance pertaining to access of the variable does not matter much, simply store the variable in your DB backed with an index and access it on every request otherwise use in-memory database such as Redis.

Upvotes: 1

Related Questions