Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you insert middleware in an Node.JS Express app

Is there a way to inject middleware in an Express stack? What I mean is I want to have my app.js setup the main middleware chain, and then call other modules passing the app instance and they may want to insert more middleware (e.g. an authentication module that wants to add passport in at the correct place)

like image 657
MrPurpleStreak Avatar asked Dec 03 '12 20:12

MrPurpleStreak


People also ask

Can we use middleware in node JS?

With Node. js middleware, you can run any code and modify the request and response objects. You can also call for the next middleware in the stack when the current one is completed. The example below will help you with the process of creating your Node.

Does Express supports middleware?

Express provides a built in middleware function express. static . Static files are those files that a client downloads from a server. It is the only middleware function that comes with Express framework and we can use it directly in our application.

Which middleware are used by an Express application?

An Express application can use the following types of middleware: Application-level middleware. Router-level middleware. Error-handling middleware.


Video Answer


1 Answers

You can certainly pass your app object to other modules and call use there. Of course, middleware functions are executed in the order they are added, so you have to take great care to ensure that you call use in the correct order.

app.js

var app = express();
// ...

app.use(express.logger()); // first middleware function

var someOtherModule = require('./mod.js');
someOtherModule.init(app);

app.use(express.static()); // last middleware function)

mod.js

exports.init = function(app) {
    app.use(function(req, res, next) {

    });
};

As far as actually injecting a middleware function in the middle of the stack (after you've already called app.use with a set of middleware functions), there's no documented way to do it. use only adds a function to the end of the stack.

use is actually supplied by Connect in proto.js:

app.use = function(route, fn){

  ...

  this.stack.push({ route: route, handle: fn });

  return this;
};

Technically, you could fiddle with app.stack yourself, but I would not do this. You'd be messing with an undocumented implementation detail, which is liable to change. In other words, it's possible a future update to either Connect or Express could break your app.

like image 152
josh3736 Avatar answered Oct 21 '22 09:10

josh3736