Koa.js, next generation web framework for Node.js

Koa.js, next generation web framework for node

Koa is a new web framework designed by the team behind Express, which aims to be a smaller, more expressive, and more robust foundation for web applications and APIs. Through leveraging generators Koa allows you to ditch callbacks and greatly increase error-handling. Koa does not bundle any middleware within core, and provides an elegant suite of methods that make writing servers fast and enjoyable.

Expressive middleware for node.js using generators via co to make web applications and REST APIs more enjoyable to write.

Only methods that are common to nearly all HTTP servers are integrated directly into Koa’s small ~400 SLOC codebase. This includes things like content-negotiation, normalization of node inconsistencies, redirection, and a few others.

No middleware are bundled with koa. If you prefer to only define a single dependency for common middleware, much like Connect, you may use koa-common.

Get Started

Below is the simple application of Koa, you can freely add any middleware on app.use function. different with Express.js, when you calling another middleware functions, no next() more, using the yield in ES6 JavaScript standard, to making the middleware magic. Koa takes care very well in middleware, with their benchmark, including almost 50 middleware in Koa application, it can have up to 340,260 request per minute. That’s mean you no longer care about the application infrastructure unless your code is not sucks and you are not the Facebook.

var koa = require('koa');
var app = koa();

// logger

app.use(function *(next){
  var start = new Date;
  yield next;
  var ms = new Date - start;
  console.log('%s %s - %s', this.method, this.url, ms);

// response

app.use(function *(){
  this.body = 'Hello World';


Cascading, yield upstream & downstream

Koa treat middleware in Koa Application always simple. Let’s imagine it

All middleware funtions in your application will return a GeneratorFunction and accept andother. When the middleware is run by an upstream middleware, it must yield to downstream middleware

Easy on Error Handle

Koa application offers an event called error, just code like below, your can have your error message without quit the whole application.

app.on('error', function(err){
  log.error('server error', err);

Check it out

Related Articles