Skip to content

Instantly share code, notes, and snippets.

@hpoom
Forked from anonymous/gist:4055232
Created November 11, 2012 21:29
Show Gist options
  • Save hpoom/4056329 to your computer and use it in GitHub Desktop.
Save hpoom/4056329 to your computer and use it in GitHub Desktop.
How to set a property in express scoped to each request
// When setting up your application define what you need using
// http://expressjs.com/api.html#app.use
// In this case we are creating an instance of 'Bar'
app.use(function( req, res, next ) {
res.locals.foo = 1;
next();
});
// Later on in your routes you have access to the instance of 'Bar'
// This saves on having to include the Bar 'class' in each route file etc
app.get( '/', function( req, res ) {
// res.locals.foo is our instance of 'Bar'
res.locals.foo++;
// Is foo always 2 here? or does it keep rising with each request?
res.send('hello world');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment