Show Buttons
Share On Facebook
Share On Twitter
Share On Google Plus
Share On Linkdin
Share On Reddit
Share On Stumbleupon
Contact us
Hide Buttons

Understanding expressjs middleware with a visual example

An express mid­dle­ware is noth­ing but a func­tion that you can spec­ify to be exe­cuted between the time when the request reaches the appli­ca­tion to when it reaches your route handler.

expressjs middleware functions

A mid­dle­ware func­tion takes 3 argu­ments as seen below.

function(req, res, next){
    // Your business logic goes here
}

Impor­tant things to remem­ber about middleware.

  • One or more mid­dle­ware func­tions com­prise the mid­dle­ware stack.
  • Order mat­ters. i.e. Each mid­dle­ware func­tion is exe­cuted in the order in which it was defined in your main appli­ca­tion file.
  • In a mid­dle­ware func­tion, invoke the third argu­ment i.e. next() to allow the request to be passed on to the sub­se­quent item in the mid­dle­ware stack(if there are more mid­dle­ware func­tions) or the route han­dler if this was the last mid­dle­ware function.
  • Mid­dle­ware func­tions are most suit­able to han­dle com­mon blan­ket actions like request log­ging, authen­ti­ca­tion etc.

For exam­ple, you could imple­ment a sim­ple request log­ger by defin­ing mid­dle­ware func­tion that does just that.

function(req, res, next){
    // Basic logging for all the routes
    console.log(req.method + ':' + req.originalUrl);
    next();
};

Express uses mid­dle­ware to many impor­tant things like — man­age ses­sion, con­struct the HTTP body etc.

The point about order is per­haps the most impor­tant because its the most eas­ily for­got­ten and can lead you to spend unnec­es­sary time debug­ging things when you expect them to work. So, just always, always keep that in mind.

That’s all there is to it.


Ryan Sukale

Ryan is a UX engineer living in San Francisco, California.

You may also like...