The Bridges That Are Express Middleware


Middleware the intricately spun web of functions activated by routes/paths in your server, and chained to each other by the calling of next().

If you’re new to server routing and have always wondered what happens next after you type a url with a path this is for you.

So what is middleware?

Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle.

app.get('/login', Middleware, function (req, res) {
res.send('index.html');
});

As the description in expressjs.com puts it-

Middleware functions can perform the following tasks:

  • Execute any code.
  • Make changes to the request and the response objects.
  • End the request-response cycle.
  • Call the next middleware function in the stack.

If the current middleware function does not end the request-response cycle, it must call next() to pass control to the next middleware function. Otherwise, the request will be left hanging.

So How to Construct a Middleware Function?

Middleware has any functionality you want you can do something as useful as giving your user a cookie before you res.send them the index.html or it can do something as useless as adding 2+2 (which you probably won’t be doing ;) )

Ultimately middleware is an intermediate step before you serve up a file.

Middleware also allows you to keep your code modularized instead of having to put all your login in the function that follows a path

Let’s use the example that we showed above,

app.get('/login', Middleware, function (req, res) {
res.send('index.html');
});

it looks clean and the middleware function between the path and the anonymous function lives happily in some other doc.

let’s see a mock middleware function:

function Middleware (req, res, next){
console.log(req);
res.name = "username";
next();
}

Looks pretty normal right?

The only special things about middleware are you it takes in req, res and next as arguments and it can do things like add key values to the response object or even look at the request object.

One important detail in all middleware is to always call the next( ); function so that it goes on the function available.

If the middleware function is that last stop on the train though don’t forget to End the request-response cycle with a res.end( );

Like this:

function Middleware (req, res, next){
console.log(req);
res.name = "username";
res.end();
}

Have fun spinning the webs of middleware and hopefully you don’t get too tangled along the way!