Express.js Middleware

What is Middleware?

Middleware is a function that can access request and response objects and can also use next function in the application’s request-response cycle.

In this tutorial, we will learn how to define a middleware function in Node.js Express application and how to make a call to the middleware function.

Middleware Terminology

request – is the HTTP request that reaches the Express application when a client makes HTTP request like PUT, GET, etc. It contains properties like query string, url parameters, headers, etc.

response – object represents the HTTP response that an Express application sends when it gets an HTTP request.

next – next is used to continue with the next middleware in the middleware stack.

request-response cycle – The cycle of operations that get executed starting with a request hitting the Express application till a response leaves the application for the request.

middleware stack – stack of middleware functions that get executed for a request-response cycle.

Define Middleware Function

As we have already mentioned in the definition of middleware function, it has access to request, response objects and next function.

The syntax is same as that of a JavaScript Function. It accepts request, response objects and next function as arguments.

here, logger is the function name, req is the HTTP request object, res is the Node Response Object and next is the next function in request-response cycle.

You can access all the properties and methods of request object req.

Similarly, you can access all the properties and methods of response object res.

Calling next() function inside the middleware function is optional. If you use next() statement, the execution continues with the next middleware function in request-response cycle. If you do not call next() function, the execution for the given request stops here.

Call Middleware

In an Express application, you call middleware using use function on application object.

Express.js Middleware Example

In this example, we will define a middleware called logger which logs the current time and query string to the console.


Start this application and hit the following urls in your browser.

  • http://localhost:8000/
  • http://localhost:8000/hello-page/

The output would be

Express.js Middleware

For each request made to the application listening on 8000, we attached a middleware function. For the url http://localhost:8000/, the url is / and hence the output of logger is current time and ‘/’. Similarly for url '/hello-page/'.