Middleware and Callback in Node app

In this tutorial, we are gonna learn about the use of middleware functions, their types, and how they are used. Along with this, we will see the working of a callback function and what is known as callback hell.

What are Middlewares in Node?

Middlewares are the functions that act as a barrier stage between the user/client request and the response on the server. It takes the basic three parameters in the functions they are request, response, and next respectively.

Request handles the user/client request like getting a post or delete.

Response sends the allocated response when all the in-between conditions of middleware are cleared.

Next function triggers the next function whether it is another middleware or callback or response.   

Need of Middlewares

  1. Middleware functions are developed for the process to be carried out by the application in between request and response process of server and client.
  2. Multiple middlewares are used in a single request call this is called a middleware chain.
  3.  The middleware functions are used to verify the conditions or accessing purpose or to even load a static file for the web application.

Types of Middleware

  • Application-level middleware
    • Ex:- Auth middleware etc
  • Router-level middleware
    • EX:- router.use
  • Built-in middleware
    • EX:- express.static
  • Error handling middleware
  • Third-party middleware

CallBack in Node App

⇒The callback is a function that is called when a given task is completed. The node js use callback functions very vastly.

⇒Every request made and process through that request are carried out by the user client are finished by a callback function.

⇒ The callback can be nested within the functions and that is known as callback hell. 

Code explaining callback and middleware.

Note:- This code is from the previous tutorial explaining the use of middleware and callback.