Middlewares in Express Js

Express Js application has a series of middleware function calls. Middlewares are also function, but with some difference, like middleware functions have access to request and response object, they can call the next middleware function. The middleware function takes 3 arguments req, res and next. It is necessary to either end the response in the middleware or call the next middleware function using next(). Otherwise the request will be left hanging.


Why should we use middlewares?

  1. We can handle the authentication and authorization part in the middlewares.
  2. We can also use third party middleware like cookie-parser to handle cookies.
  3. We can divide the tasks between multiple middlewares.
  4. We can also manipulate req and res object inside the middlewares, like setting the headers of the response object.

Leave a Reply

Your email address will not be published. Required fields are marked *