The Magic of Middleware 785X391

The Express.js Web Framework revolves around processing and routing, and since it has almost no functionality of its own, it is referred to as Middleware. When creating an application, making use of Middleware enables you to shorten the entire creation process, as you will be using less code but getting the same result.

The functions of Middleware enable an application to access requests and respond to objects as well as cycles. As Express.js is in the middle of the application, it can be found in between the raw request and the route that was intended. To better understand the magic of middleware and its relation to Express.js fundamentals, it is advisable to use a living example.

Below is the coding for the creation of a basic express.js application. But before getting into this you may also check out new features of Express.js to get started in Express.js development.

app.get('/', function(req, res) {
  res.send(Good Morning!');
app.get('/help', function(req, res) {
  res.send('Sorry.. Move Forward');

When you request something from this basic app, you will receive one of two responses: The first shall be Good morning if you simply make a request for /, and if you request for /help, then the response you will see is Sorry….Move Forward.

From this example, it is possible to relate middleware to functions that are invoked within a routing layer by Express.js. This happens prior to the last request handler being made.

Now that you understand this, you can review how middleware saves you time. When you make a request from your application, you have the option of recording your request every time. This can be tremendously time consuming and laborious. Alternatively, you can have this automatically done by making use of Middleware. The coding would then appear as follows: –

app.use(function(req, res, next) {
  console.log('%s %s', req.method, req.url);
app.get('/', function(req, res, next) {
  res.send(Good Morning!');
app.get('/help', function(req, res, next) {
  res.send('Sorry.. Move Forward');

You have added a new dimension to your requests with app.use (), which is a function that enables you to invoke every request.

Types of Middleware

For added flexibility, it is possible to make a choice from one of five different types of middleware for the Express application. These are as follows: –

  • Application-level middleware – With this middleware, you use app,use () and app.METHOD functions. When you do so, the required function can be executed each time that an application receives a request. It is possible for the middleware to have no route path, as well as to be mounted for various function requests and executions.
  • Error-handling middleware – Where the other types of middleware have three arguments for error handling, Express.js middleware has four. These four can be identified using their signatures which are err, res, next and req.
  • Third-party middleware – When you want to add more functions to an express app using a third party, then this is the middleware that you will use. It is only functional on the Node.js module, so this will need to be present in your system.
  • Built-in middleware – There is one function that has been built in to the Express.js, and that is express.static. It has the responsibility of serving assets which are static within the express application.
  • Router-level middleware – This has similar functionality as the application level middleware. The key difference is that it has been bound to an instance of express.router().

Next () Argument

With Middleware, you are accepting request and response objects. There is also the next function, which holds significant importance. When you want the middleware to respond to an object, you need to use the next callback. That way, you ensure that what you have placed to appear in the browser will be visible. Express.js will not know whether you have completed your operation in order to move onto the next one without the next () argument. That is why this argument is called.

Things to Bear in Mind when Using Middleware

To ensure that you get the best experience with express.js and magic of middleware, these are the points that you need to bear in mind.
1. Do not override properties
Middleware deals with request and response objects. All middleware will have the same instances of these objects, which means that you should prevent using two different types of middleware to modify one object. Doing so can result in considerable errors within your application. When you are making any modification to your middleware, take extra precautions to ensure that these modifications are included in the properties. Doing so will guarantee that your application runs smoothly.

2. Order matters a lot: Middleware is always invoked in the order in which it has been added. See the example below:

app.get('/', function(req, res) { res.send('hello'); });
app.use(function(req, res, next) {
});'/', function(req, res) { res.send('bye'); });

In the above example, middleware will not execute for GET requests but will execute for POST requests by changing their order first.

3. Never forget to call next ()
When adding middleware, the next () argument is vital and should not be forgotten. You will know that there is something wrong when your page fails to respond or hangs. Express.js is simply unable to pinpoint what the problem is, so you will end up stuck with no way of moving forward until you personally identify the issue.

You can also use NEXT argument in case you want to skip the middleware.

The Importance of Middleware

You should not underestimate the importance of middleware and the role that Express.js can play when you are creating applications. Middleware creates beneficial connections between applications or functions, making communication easier, faster and more efficient. In addition, if there is a need to keep certain systems disconnected from one another, middleware is able to do this as well.

Using middleware makes it easier to identify errors, and is also less complex when it comes to correcting these errors. As it helps eliminate unnecessary code, creating apps becomes easier, both in the process and the understanding. The Magic of Middleware on Express.js ensures that routing is possible through an excellent web framework.