Berker Kelesoglu
Berker Keleşoğlu
Berker Kelesoglu
Berker KeleşoğluSoftware Developer

Middleware Functions in Node.js

Software

Nov 18, 2023

foto
In development process, many times we are repeating ourselves and we may not be able to notice that. This reminds me the principle “Do not repeat yourself” DRY of software development. To abide by the principle, we can use middleware functions in Node.js.
What is Middleware?
middleware-chart.jpg
As it is lexical meaning, middleware is a software that runs between an operating system and an application and basically it enables communication and data management for applications. Actually its lexical meaning totally defines what it means for us. As I mentioned above, it enables us communication in request-response cycle by having access to request objects, response objects and the next function.
How to Use Async/Await Functions as Middleware Functions
With ECMAScript 2017 we started to use async/await to get rid of getting lost in callback hell but in some point it will throw error and to catch them we are using try catch as you can see below.
personel_try_catch.png
Imagine we have lots of controllers like that so using try catch could be a problem for us in respect of DRY principle. To add some DRY to our code, we can create a middleware function and update code above as you see below;
async_handler.png
Here as it says in comment line, it will pass the error to express.js directly but what if we need another middleware function to handle the error. In some time it will throw error and it will be in HTML format so to handle this we need error handler middleware:
error_handler.png
Besides request, response objects and the next function, it also has an access to error and by error handler middleware, it can return the error as in JSON format when it is used in the server file.
As conclusion, middleware functions help building the application more effectively. The reason why we use middleware functions in Node.js besides general reasons is being able to be used for modifying the request and response objects for tasks like adding response headers, parsing requesting bodies, and so on.