Middleware
#
IntroductionLight 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 MiddlewareThere are three different ways you can inject a middleware into a request handler.
- Method specific - By passing it into a
GET
,POST
, etc function - Route specific - By using the
useMiddleware
function exported bycreateRoute
- 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:
- A middleware is a function
- 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 thenext
function in Express middleware) In the majority of cases, you will want to awaitfn
in the following step to get the intended response and then mutate if you so choose. - 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. - 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.