If you have coded in Node Js or Express Js before, I guess you must have come across the word middleware. In this tutorial, I am going to cover the following;
What is a middleware?
Types of middleware
Case of an application-level middleware
What is a middleware in Express?
Middleware is a function that gets executed during the request-response lifecycle of an application. So you got the word function which literally mean middleware are actually functions in your Express application. These middleware functions have access to the request and response objects of the route it is attached to it in the application lifecycle. According to expressjs.com, middleware functions are capable of;
- Executing block of codes,
- Modifying the request and response objects,
- End an apps request and response cycle and
- Call or handover to the next middleware
I would like you to understand that, Express JS is a middleware framework. That is, when coding in Express js, you are writing series of routes and middleware functions.
One of the simplest example is the route handler function;
Medium.com say; “First of all, think of middleware as a simple function that will take a request object and pass control to the next middleware function or send a response to the client.”
Middleware functions can also be seen as the functions placed between the request and response object.
Now, lets look at some various types of middleware;
Types of middleware
According to expressjs.com official website, we have they following;
- Application-level middleware
- Router-level middleware
- Error-handling middleware
- Built-in middleware
- Third-party middleware
Case of an application-level middleware
A route handler is a perfect example of an application-level middleware. Application-level middleware functions are mostly bound to the instance of the app object with either (or both) app.use and app.method where method refers to HTTP method which could be get, put, post and delete.
carefully look at the code below;
The difference between this code and the one above is the introduction of the keyword “next”. As the word implies, this word passes or handover to the next middleware function. If we had another middleware function in this code that we want to execute, then we will practically add another line after the response which is the next () method.
Now, lets run some code in server.js and see how it works.
Run your code, open your browser and navigate to http://localhost:3000. You will see the response we set above.
At the same time on the console you will see the text “I am the first middleware display”. The middleware prints out the text above and then calls the next () middleware.
OUTPUT
Thanks for coding with me. Watch out for a video tutorial on this, and other content on the other types of middleware. Feel free to drop your questions or worries.
Chaow!! ☺
Comments
Post a Comment
Please do not enter any spam link in the comment box.