Connect, and so on ‑ however a key design decision was made to
provide high level "sugar" at the otherwise low‑level middleware
layer. This improves interoperability, robustness, and makes
writing middleware much more enjoyable.
This includes methods for common tasks like content‑
negotiation, cache freshness, proxy support, and redirection
among others. Despite supplying a reasonably large number of
helpful methods Koa maintains a small footprint, as no
middleware are bundled.
The obligatory hello world application:
const Koa = require('koa');
const app = new Koa();
app.use(ctx => {
ctx.body = 'Hello World';
});
app.listen(3000);
Cascading
Koa middleware cascade in a more traditional way as you may be
used to with similar tools ‑ this was previously difficult to make
user friendly with node's use of callbacks. However with async
functions we can achieve "true" middleware. Contrasting
Connect's implementation which simply passes control through
series of functions until one returns, Koa invoke "downstream",
then control flows back "upstream".
The following example responds with "Hello World", however first
the request flows through the x-response-time and logging
middleware to mark when the request started, then continue to
yield control through the response middleware. When a
middleware invokes next() the function suspends and passes