Understanding expressjs middleware with a visual example

An express middleware is nothing but a function that you can specify to be executed between the time when the request reaches the application to when it reaches your route handler.

expressjs middleware functions

A middleware function takes 3 arguments as seen below.

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

Important things to remember about middleware.

  • One or more middleware functions comprise the middleware stack.
  • Order matters. i.e. Each middleware function is executed in the order in which it was defined in your main application file.
  • In a middleware function, invoke the third argument i.e. next() to allow the request to be passed on to the subsequent item in the middleware stack(if there are more middleware functions) or the route handler if this was the last middleware function.
  • Middleware functions are most suitable to handle common blanket actions like request logging, authentication etc.

For example, you could implement a simple request logger by defining middleware function that does just that.

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

Express uses middleware to many important things like – manage session, construct the HTTP body etc.

The point about order is perhaps the most important because its the most easily forgotten and can lead you to spend unnecessary time debugging 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 Sukale

Ryan is just a regular guy next door trying to manage his life and finances.

You may also like...

Leave a Reply

Your email address will not be published.