Middleware

Introduction

Light middleware is slightly different compared to other kinds of middleware in node frameworks. Middleware allow you to wrap a request completely and run code, before the request, after the request, and also mutate the response. It is similar to Higher Order Components (HOCs) in React.

Using a Middleware

There are three different ways you can inject a middleware into a request handler.

  1. Method specific - By passing it into a GET, POST, etc function
  2. Route specific - By using the useMiddleware function exported by createRoute
  3. Global - TODO

A middleware is a function that takes in a fn and returns another function that takes in a context and a valid response.

While that is the official definition of a light plugin, it is quite confusing so lets break it down:

  1. A middleware is a function
  2. The parameter sent to the middleware is another function (called fn). fn is the actual route handler that is defined in the http method functions. (Think of it like the next function in Express middleware) In the majority of cases, you will want to await fn in the following step to get the intended response and then mutate if you so choose.
  3. The middleware should return another function that takes in a context and returns a response. You will want to use the previous fn that was provided to get the intended response and mutate if you so choose.
  4. Make sure to either return a value at the end of your plugin or end the request with send.

A typical middleware looks like this.

Make a request to the URL above and take a look at the logs. You can see that we were able to start a timer before the rest of the code, and then console.log the difference after.