Koa Middlewares
A base understanding about the use of middleware in a koa environment
I think the base of nodejs backend development frameworks is the use of middlewares. Intercepting a request, do something with that, update response or treat incoming datas.
In Koa, middlewares is promise based and works using Onion Model. Basically you can use async/wait in each middleware, wait for the next middleware to resolve, then execute the rest of your middleware code.
Example:
A time logger function to calculate the time amount your app consume to execute all procedures between request and response.
app.use(async (ctx, next) => {
const start = Date.now();
await next(); // api logic
const ms = Date.now() - start;
console.log('API response time:' + ms);
});
To calcule that using express would require a much more longer and confuse code logic.
This work that way…
because Koa use koa-compose to unify all middlewares in one recursive function, which will iterate over all middlewares by its positions on koa’s middleware array, and return a promise in the end.
My Conclusions
I have been using koa for a couple of months, and on multiples differents tech environments like graphql, rest api, serverless functions and in my opinion this framework shines with its middleware’s usage.
References
The elegance of asynchronous middleware chaining in Koa.js
[ReadingKoa] Day One — How Koa middleware works
Photo by Safar Safarov on Unsplash