Aghyul Kyoku
Aghyul Kyoku

Reputation: 1060

Node.js variables for current request only?

I am very new to Node.js, and I was wondering if that, except for session(), I could use a "storage" to store variables for the current request?

I have an API which is based on an Authorization header, and a pool of valid tokens stored in Redis.

Therefore I don't have a session and don't want to.

But I would like to store variables for further use during this request. For example, I would like to store the user_id corresponding to the token found in Redis, so that I can use it wherever I want.

If I do something like:

app = express(); app.user_id = 1;

Is it ok, or will my user_id become global to all requests handled by the app? (in short: is the app instanciated for each request handled by the server, or is it persistent?)

If this is not ok, how could I achieve something like this without sessions?

Thank you for any help :)

Upvotes: 1

Views: 1899

Answers (1)

dylants
dylants

Reputation: 23360

The app handles all requests, and would only be created once on startup, but req lives for only the lifetime of the request. Keep in mind that the req in Express is just an object, and as such, can be assigned values. So if you wanted to allow the controller to have access to some value (similar to sessions), you could do something like this:

var express = require('express');
var app = express();

// middleware that assigns a value '123' to 'req.user_id'
app.use(function(req, res, next) {
    req.user_id = 123;
    next();
});

// controller which responds with the 'req.user_id'
app.get('/hello', function(req, res){
  res.send('req.user_id: ' + req.user_id);  // responds with req.user_id: 123
});

app.listen(3000, function() {
    console.log('Listening on port 3000');
});

In the above example, the middleware that I created assigns a value to the request, called user_id. This value lives for the life of the request. You could do a similar thing to assign a dynamic value to the req so that you can access it via your controllers.

Upvotes: 6

Related Questions