Implement Middleware

Learn what middleware is, and practice how to use it.

In the previous lesson, we used a middleware function, express.static(), to serve static files to the client. We can use middleware functions for various tasks, such as logging, authentication, parsing data, and so on.


Middleware functions are those that alter the request (req) and response (res) objects in the request-response cycle of an application.

New HTTP Request \large\Rightarrow Middleware Functions \large\Rightarrow Route Handlers

Middleware functions should accept three parameters: req, res, and next. They’re executed in a specific order. When the current middleware function is done, it passes control to the next middleware function in the stack by calling next().

If we don’t call next() inside a middleware function, the route handlers that come after the middleware function won’t run.

Task 9: Implement application-level middleware

Let’s create a simple logging middleware to print information about every incoming request. Add the following middleware before the route handlers in the src/index.js file:

Get hands-on with 1200+ tech skills courses.