Maintaining request scope in Express/Node.js
Asked Answered
S

1

7

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.
Sienkiewicz answered 31/7, 2015 at 13:2 Comment(4)
So you're looking for "requestable context"? So that whenever you need context that wasn't passed in directly, you can request it somehow?Goodbye
You can attach variables to req directly.Try adding the line req.myObject = { color: "red" }Cabob
Well, in that case I will need to pass req around to all layers of the app, which is exactly what I am trying to avoid.Sienkiewicz
Any solutions yet?Streamline
T
5

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.

Tympanites answered 10/3, 2018 at 22:18 Comment(1)
Thanks, Steve. I am no longer looking for this solution, but I will keep express-http-context in mind.Sienkiewicz

© 2022 - 2024 — McMap. All rights reserved.