express Writing Express Middleware

30% OFF - 9th Anniversary discount on Entity Framework Extensions until December 15 with code: ZZZANNIVERSARY9

Syntax

  1. Specify the instance of express you want to use. This is commonly app.
  2. Define the HTTP method for which the function applies. In the example, this is get.
  3. Define the path to which the function applies. In the example, this is '/'.
  4. Define as a function with the function keyword.
  5. Add the required parameters: req, res, next. (See note in remarks section)
  6. Put some code in the function to do whatever you want

Parameters

ParameterDetails
reqThe request object.
resThe response object.
nextThe next() middleware call.

Remarks

A middleware function is a function with access to the request object (req), the response object (res), and the next() middleware function in the application's request-response cycle. The next() middleware function is commonly denoted by a variable named next.

Middleware functions are designed to perform the following tasks:

  • Execute any code.
  • Make changes to the request and response objects. (See the requestTime example)
  • End the request-response cycle.
  • Call the next middleware in the stack. (By calling the next() middleware)

Note: It doesn't have to be named next. But if you use something else no one will know what you mean and you will be fired. And your code won't work. So, just name it next. This rule applies to the request and response object. Some people will use request and response instead of req and res, respectively. That's fine. It wastes keystrokes, but it's fine.



Got any express Question?