How to write middleware for Express.js

Before telling you about anything, I will show you the middleware

This will tell you about middleware

  • Middleware is a function.
  • It has access to response and request object.
  • It has access to the next middleware function in request-response life cycle.
  • Execute any code.
  • Make changes to the request and the response objects.
  • End the request-response cycle.
  • Call the next middleware function in the stack.

Simple to understand the middleware, right?
Now lets look at how to implement the following middleware chain. I am going to define two middleware and route handler

Now run your server

Open the http://localhost:3000 from your browser
You will see this output in your server terminal

  • app.use: This is how you define your middleware. A function with a signature of (req, res, next) is passed to this app.use function. First paramater is request, second parameter is response and the third one is next. next() is used to call the next middleware in the chain or route handler
  • First middleware hello just print the “Hello there !” and call the next middleware logger
  • Second middleware logger just print the “I am inside logger” and call the route handler

Leave a Reply

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