Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access request context anywhere

I'm using Express and I need to access some data that it is on the request (headers, cookies, etc) every time I use the log to debug and trace my app.

With other languages (ie: Java) I have the "Thread Context" where I can put that data, and so access it whenever I log something. But with NodeJS there is no such thing, as far as I know, because we have only one thread.

I'm trying to avoid passing the req variable in every function so I can log that info.

Is there a node or expressjs feature that let me get the data anywhere?

like image 254
Neuquino Avatar asked Jan 01 '16 13:01

Neuquino


People also ask

What is the context of a request?

The request context keeps track of the request-level data during a request. Rather than passing the request object to each function that runs during a request, the request and session proxies are accessed instead.

What is request context in Java?

public class RequestContext extends Object. Context holder for request-specific state, like current web application context, current locale, current theme, and potential binding errors. Provides easy access to localized messages and Errors instances.


1 Answers

Have a look at Continuation Local Storage, it implements something similar to thread context for asynchronous call chains: https://github.com/othiym23/node-continuation-local-storage

Also there are efforts to build asynchronous local storage as a standardized feature into javascript itself, but they are still at a very early stage: TC39 Zone Proposal https://docs.google.com/presentation/d/1H3E2ToJ8VHgZS8eS6bRv-vg5OksObj5wv6gyzJJwOK0

like image 78
Kristian Hanekamp Avatar answered Oct 13 '22 04:10

Kristian Hanekamp