Skip to content

Instantly share code, notes, and snippets.

@microbial
Created December 4, 2015 04:27
Show Gist options
  • Save microbial/7c709b0a0d7b55a9404d to your computer and use it in GitHub Desktop.
Save microbial/7c709b0a0d7b55a9404d to your computer and use it in GitHub Desktop.
Middleware with access to app instance
var express = require('express');
var app = express();
//Normal way - won't work if function is extracted to a module
app.use(function(req, res, next) {
'use strict';
app.locals.greeting = 'hello';
next();
});
var express = require('express');
var server = express();
//Assuming app will be the server name is bad news
//This won't work
server.use(function(req, res, next) {
'use strict';
app.locals.greeting = 'hello';
next();
});
var express = require('express');
var server = express();
var greet = require('./greet_module_safe');
//Should work fine
server.use(greet(server));
module.exports = function(appInstance) {
'use strict';
//If this module is run with an instance of the current app then
//then the module should work despite the server name and be
//fully independent
return function(req, res, next) {
appInstance.locals.greeting = 'hello';
next();
};
};
module.exports = function(req, res, next) {
'use strict';
//This should violate use strict since app is not defined here
app.locals.greeting = 'hello';
next();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment