Koa.js Cascading - Koa.js

What is koa.js Cascading?

Middleware functions enables to modify the request and response objects for events like adding response headers, parsing request bodies etc. Added feature to the cap, Koa yield ‘downstream’ and flowing control back ‘upstream’, this effect is termed as cascading.

An illustration of middleware function is:

For every request on server, the above mentioned middleware is called and after every request, the message appearing in the console is:

Routes are created in order to restrict the request to a specific route. The middlewares handle the request. For instance,

Time is logged only when requested for any subroute of ‘/request’

How the koa.js middleware calls are ordered?

The order in which the middlewares are written/included and the order in which middlewares are executed, is very important in koa. As the yield statement hits the middleware, it moves to the next middleware and next and reaches the last middleware and move back resuming the functions from yield statements.

For instance, in the below code, the first function executes first till yield, then second till yield and so on. Once reaches last, start moving backwards executing in the reverse order. This is how middlewares are used the Koa way.

When the code runs, the console appears as:

The above example is better explained in the diagram:


What are the most commonly used Koa middleware?

The most commonly used third party middleware are:

  • koa – bodyparser
  • koa-router
  • koa-static
  • koa-compress

All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Koa.js Topics