entity-routes logo
Docs

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.

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.

A basic middleware looks like this :

#
typescript
1const logMw = async (ctx, next) => {
2 const start = Date.now();
3 await next();
4 const ms = Date.now() - start;
5 ctx.set("X-Response-Time", `${ms}ms`);
6};
Example taken from https://koajs.com/

Differences with hooks#

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.

Prev
Request Context
Next
Hooks