Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maintaining request scope in Express/Node.js

I am using Express to expose a REST API in my Node.js application. When a REST request comes in, I extract the user information from the HTTP headers. I would like this information to be available throughout the life of this request, no matter what function I am in. An obvious but kludgy way is to pass around the user information as parameters to all function calls. Is there a better way? So far I have found the following solutions, but I am not sure if they are ready for prime time:

  1. StrongLoop Zone Library: Docs say "The zone library and documentation are still under development: there are bugs, missing features, and limited documentation."
  2. Continuation-Local Storage: Not sure if this is slated to be part of Node.js. This issue at the end recommends looking at StrongLoop zone.
  3. Node.js Domains: Does not look like this actually took off.
like image 203
Naresh Avatar asked Oct 31 '22 22:10

Naresh


1 Answers

I'm not sure if you're still looking, but a while back I built express-http-context for this very purpose. It's an express middleware that sits on top of cls-hooks (formerly continuation-local-storage).

Full disclosure: this is an npm package that I built and maintain.

like image 78
Steve Konves Avatar answered Nov 15 '22 05:11

Steve Konves