When you mention creating a global object inside a route, are you referring to 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
- possibly like app.set('myGlobalObj', someOb)
or perhaps on another global object. This would allow every request-response cycle to access the same object.
However, it is not advisable for any system you plan to develop. The main reasons include:
It is unstable. In the event of your application crashing, any request
relying on the current value of your global object will not complete properly since that value was lost/reset with the crash.
This approach does not follow the principles of REST architecture, which emphasizes statelessness and self-sufficiency in requests.
Globals go against Object Oriented Programming and Functional Programming paradigms. Global variables can make your application more vulnerable, less clear, and difficult to test.
Possible Solutions
If variable access performance is not critical, consider storing the variable in your database with an index and retrieving it for each request. Alternatively, use an in-memory database
like Redis
.