---
title: "Getting Started with Koa.js"
description: "Introduction to Koa, the next generation web framework for Node.js using ES6 generators. Practical notes and code examples."
url: "https://h3manth.com/scribe/getting-started-with-koajs/"
canonical_url: "https://h3manth.com/scribe/getting-started-with-koajs/"
markdown_url: "https://h3manth.com/scribe/blog/getting-started-with-koajs.md"
publishDate: "2014-02-09T00:00:00.000Z"
author: "Hemanth HM"
category: "node"
tags: ["node","javascript","koa"]
word_count: 187
reading_time_minutes: 1
x_markdown_tokens: 438
content_signal: "ai-train=yes, search=yes, ai-input=yes"
---

# Getting Started with Koa.js

> Introduction to Koa, the next generation web framework for Node.js using ES6 generators. Practical notes and code examples.

[Koa](http://koajs.com) is the next generation web framework for Node.js brought to us by the wonderful team behind [Express](http://expressjs.com/).

## Hello World Comparison

### Express

```javascript
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](http://wiki.ecmascript.org/doku.php?id=harmony:generators). Use `node --harmony` flag to run.

## Understanding Context

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

```javascript
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.
