Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i store request-level variables in node.js?

Tags:

for data that only needs to be available during an individual request, where should it be stored? i am creating new properties on the req and res objects so i dont have to pass that data from function to function.

req.myNewValue = 'just for this request' 

is the process object an option? or is it shared globally across all requests?

like image 834
Paul Avatar asked Jun 11 '12 15:06

Paul


2 Answers

In Express 4, the best practice is to store request level variables on res.locals.

An object that contains response local variables scoped to the request, and therefore available only to the view(s) rendered during that request / response cycle (if any). Otherwise, this property is identical to app.locals.

This property is useful for exposing request-level information such as the request path name, authenticated user, user settings, and so on.

app.use(function(req, res, next){   res.locals.user = req.user;   res.locals.authenticated = ! req.user.anonymous;   next(); }); 

The process object is shared by all requests and should not be used per request.

like image 85
pxwise Avatar answered Oct 11 '22 19:10

pxwise


If you are talking about the variable passed like here:

http.createServer(function (req, res) {     req.myNewValue = 'just for this request';     res.writeHead(200, {'Content-Type': 'text/plain'});     res.end('Hello World\n'); }).listen(1337, '127.0.0.1'); 

then it is perfectly fine what you are doing. req stores the request data, you can modify it as you want. If you are using some framework like Express, then it should be fine as well (keep in mind that you may overwrite some built-in properties of req object).

If by "process object" you are refering to the global variable process, then absolutely not. The data here is global and shouldn't be modified at all.

like image 43
freakish Avatar answered Oct 11 '22 18:10

freakish