0

I'm creating an API using Express, and I want to know if there is a way to create a global variable (something like a global store) that only keeps data for the duration of the request.

I understand that because Node.js handles all requests in the same thread, any global variable I create will persist across requests. So I wonder if there's a clean way to achieve what I want to.

Does Node.js or Express provide a way where I could clean up this global state at the end of each request? Like an event or something similar. Or is there a package that already does this?

Maybe I could get way leveraging closures, but I'm looking for something more flexible.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Raul
  • 515
  • 1
  • 6
  • 13
  • Why would you do this anyway? – Konrad Jul 03 '22 at 18:02
  • @KonradLinkowski There are cases in which you'd like to have a non-persistent cache in your app. Like for example, fetching user specific data. True, you could pass that data to your functions, but you can end up creating them with lots of parameters. I think it's cleaner to access a global object in these cases. For example, you could call the same `getData` function anywhere. The first call goes to the DB, but subsequent calls are cached. I think it's similar to the things we see client-side in React, with react-query and useSWR. I know the browser is a different monster, though. – Raul Jul 03 '22 at 18:22
  • Why was this question marked as duplicate? They are similar, but what i'm asking is a bit different. The other question is more about sharing data across middlewares. – Raul Jul 03 '22 at 18:28
  • I would create global object like this `const catche = {}` then I would add data to It for user `cache[user] = data` or for any parameter. There are also libraries that do cache for you. – Konrad Jul 03 '22 at 19:20

0 Answers0