Monday, March 17, 2014

Koajs - Getting Started

Koa is the next generation web framework for nodejs. Similar to express.js but smaller because most modules have been seperated out as individual package, for example you will have to use koa-router in your application in order to use app.get() method. Another main feature of Koa is the use of javascript ES6 (still pending) generator.

1. Getting Started

Back to TOC
This tutorial assumed that you are running Linux and have followings installed:

  1. nodejs >0.11.0 (Must have in order to run koajs)
  2. npm
  3. any text editor such as vi
  4. Web browser
  • Create project folder:
mkdir koa-tutorial
cd koa-tutorial
  • Setup package.json for this project.
npm install
 name: (koa-tutorial)
 version: (1.0.0)
 description: (Koa Tutorial)
 entry point: (app.js)
 test command:
 git repository:
 keywords: koa tutorial
 author: (your name)
 license: (BSD)
Is this ok? (yes)

Here’s the explanation of each property:

The name of the project.
Version of the project.
Describe the project.
entry point
The name of the main application js file and it can be any name. Common names are index.js, server.js, app.js, main.js.
test command
Command to run the test scripts.
git repository
The git repository got this project.
Useful when search in npm registry ( if publish there.
The author of the project.
License of the project.

There are more properties available like homepage which specify the project’s homepage.

  • Install Koajs module. The option --save will save the module as a dependency in package.json
npm install koa --save
  • Create a file app.js and write the script below to it:
"use strict"

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

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


Save it as app.js in your project directory.

In your command prompt, run node --harmony app.js to start the server.
Be sure to put --harmony option when you run the node server.

Open the site (localhost:3000) in your web browser, you should see the line “Hello World” shows up.

2. Javascript ES6 Generator

Back to TOC
Notice the new syntax function *(){}. This is the new generator syntax. In Koa, all middlewares are generators and app.use() must have a generator argument. A middleware generator has a function signature function *(next){}. The next in the function argument is of type generator.

3. Custom middleware: Request Logger

Back to TOC
Middleware can be anything. It can be a filter that will gzip you final response before sending out; it can also be a logger to track the request information. There are lots of middleware available for Koa such as gzip, refresh, formidable etc.

We will create a simple middleware that will show log information of each request made to the server and show their HTTP method and path.

  • In app.js, declare the generator function after the line app = koa();.
function *reqlogger(next){
  console.log('%s - %s %s',new Date().toISOString(), this.req.method, this.req.url);
  yield next;
  • The function does 2 things:
    1. Log request’s method (GET/PUT/POST/DELETE) and url (‘/’) and output to console.
    2. After the log, yield next generator.

And then the application will use the middleware by calling app.use(). We only need to pass in the middleware name.

  • The final work for app.js.
"use strict"

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

//Middleware: request logger
function *reqlogger(next){
  console.log('%s - %s %s',new Date().toISOString(), this.req.method, this.req.url);
  yield next;

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

  • Restart your server (node --harmony app.js) and open the site in browser again. Looking at the server command prompt, you will see a log like this:
2014-01-01T12:15:34.688Z - GET /

4. Download

Back to TOC
You can visit go here for the code used in this tutorial.

Copyright © 2014 All Rights Reserved. No part of this website may be reproduced without’s express consent.

No comments: