Hemanth's Scribes

node

Getting Started with Koa.js

Author Photo

Hemanth HM

Thumbnail

Koa is the next generation web framework for Node.js brought to us by the wonderful team behind Express.

Hello World Comparison

Express

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

app.use(function(req, res, next){
  res.send('Hello World');
});

app.listen(3000);

### Koa
javascript
var koa = require('koa');
var app = koa();

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

app.listen(3000);

If you’re wondering what function *(){} is - they are generators. Use node --harmony flag to run.

Understanding Context

A Koa Context encapsulates node’s request and response objects into a single object:

app.use(function *(){
  this;          // is the Context
  this.request;  // is a koa Request
  this.response; // is a koa Response
  this.req;      // nodejs request
  this.res;      // nodejs response
});

## With Routing
javascript
var koa = require('koa');
var app = koa();
var route = require('koa-route');

app.use(route.get('/', function *() {
  this.body = 'Hello World';
}));

Middleware Flow

With generators, each yield next makes control flow “downstream” and then back “upstream”:

mw1 -> mw2 -> mw3 -> mw3 -> mw2 -> mw1

The generator suspends, passes flow downstream, then resumes on the way back.

#node#javascript#koa
Author Photo

About Hemanth HM

Hemanth HM is a Sr. Machine Learning Manager at PayPal, Google Developer Expert, TC39 delegate, FOSS advocate, and community leader with a passion for programming, AI, and open-source contributions.