Middlewares#
Middlewares are functions that process the request, chained one by one, which make them very easy to re-use. Using middlewares you can handle authentication, logging, permissions, etc.
A middleware has access to the req
and the
res
objects from the
Node http module. If using afterCtxMiddlewares
, you also get access to the route
RequestContext
.
Learn more about them from Koa's documentation or from Express's documentation
Usage#
You can add middlewares to an EntityRouter
by passing them in the
EntityRouteOptions
, which means that you can both register a local middleware for a
specific EntityRouter
or register global middlewares by passing them to the
makeEntityRouters
.
The implementation itself of a middleware will depend of the maker
used.
- If you use Koa, you can use the
makeKoaEntityRouters
maker
. - If you use Express or a compatible API (Next, Nuxt, etc.), you can use the
makeExpressEntityRouters
maker
.
A basic middleware looks like this :
If you want to intervene at some point of the request handling (and potentially alter part), you might want to check hooks rather than using middlewares.
They differ from middlewares since they do not receive the context/req/res arguments but rather just the relevant parts of what they are dedicated to.
Middlewares are more powerful, they can for example end the request handling and send a response, whereas hooks can at most alter their part.