Objectives - Express Middleware

Objective 1: Explain What Middleware Is and the Different Types

There are different types of middleware; for our purposes, we'll group them into three different categories:

  1. Built-in middleware
  2. Third-party middleware
  3. Custom middleware

Built-in Middleware

Built-in middleware is included with Express but not added to the application automatically. Like the other types, we need to opt-in to using it in our application.

We saw an example of built-in middleware when we added support for parsing JSON content out of the request body using server.use(express.json());.

Every type of middleware works in the same way. We tell Express about the middleware we want to turn on for our application by making a call to .use() on our server and passing .use() the piece of middleware we want to apply.

Third-party Middleware

Third-party middleware are npm modules that we can install and then import into our applications using require(). There are thousands of middleware modules we can use.

Some popular middleware modules are:

  • morgan - HTTP request logger middleware
  • cors - Enable CORS (Cross-Origin Resource Sharing)
  • helmet - Helps secure Express apps with various HTTP headers

Custom Middleware

Custom middleware is functions we write to perform specific tasks. We'll learn more about how to write and use them in the next section.

Objective 2: Write Custom Middleware

Writing custom middleware is a two-step process:

  1. Write a function that will receive three or four arguments
  2. Add it to the middleware queue

Example: Request Logger

Let's write middleware that logs information about every request that comes into our server:

function logger(req, res, next) {
  console.log(
    `[${new Date().toISOString()}] ${req.method} to ${req.url} from ${req.get('Origin')}`
  );
  next();
}

Middleware Parameters

A middleware function takes three parameters:

  1. the request object
  2. the response object
  3. a function that points to the next middleware in the queue

By convention, we name the third parameter next. Please stick to that convention in your code.

Important Notes

  • Any middleware in the queue CAN modify both the request and response objects, but it's NOT required
  • Any middleware in the queue can stop the request and send a response back to the client
  • Calling the next() function signals to Express that the middleware has finished
  • If next() is not called and a response is not sent back to the client, the request will hang

Additional Resources