Search code examples
node.jsexpressnode.js-connect

Assigning default values to the request object in express js


How would I go about ensuring that a particular object is available to every request I handle in express?

var somethingImportant = "really important";
var app = express();

// This is just a hypothetical example of what I'm after...
app.mixThisInWithRequest({
    somethingImportant: somethingImportant
});

app.use(function (request, response, next) {
   console.log(request.somethingImportant);
});

Given the example above, is there a facility akin to the mixThisInWithRequest function?


Solution

  • Add it to the request object in middleware, as early in the app.use chain as you need it:

    var somethingImportant = "really important";
    var app = express();
    
    app.use(function (request, response, next) {
        request.somethingImportant = somethingImportant;
        next();
    });
    app.use(function (request, response, next) {
       console.log(request.somethingImportant);
    });