Creating a basic site with Koa

Koa.js — A next generation web framework for node.js

Adam Bickford
6 min readApr 17, 2014

8/29/2017 Disclaimer: This tutorial is well out of date nowadays, so please do your own research to verify which parts of this article you end up using or learning from so you don’t run into too much trouble down the road. I’m so glad to see this still gets views from time to time, and I hope it has helped those of you who found yourselves here.

I’ll preface this by saying I’m still new to backend development, but I have done a little bit of work with Node and would like to document my experience with Koa.js, a newer framework for Node from the team behind the Express.js framework.

I’m currently using Koa to refactor our marketing site for Piggybank. It’s awesome because it’s extremely lightweight, and extremely modular. It has a lot of capabilities that are easily customized by just requiring the tools you need.

Prerequisite — Updating Node

First things first, Koa needs to run in Node’s “harmony” mode, so you’ll need to upgrade to version 0.11.9 or newer. I suggest using the Node Version Manager from creationix. Updating (or installing for the first time, if you don’t have Node yet) with nvm allows you to install different versions without uninstalling your current version. This way you can switch back and forth between versions should some of your current projects not work with this newer version of Node. It’s as easy as running the nvm install script…

$ sudo curl https://raw.github.com/creationix/nvm/v0.5.1/install.sh | sh

// You can find the most current version at
// https://github.com/creationix/nvm

and then installing 0.11.9…

$ nvm install 0.11.9

then telling nvm to use version 0.11.9.

$ nvm use 0.11.9

After that you can list all the versions of Node you have installed with:

$ nvm ls
//outputs something like:
.nvm
v0.10.8
-> v0.11.9 //arrow indicates that we're already using v0.11.9

You can also set a default version with:

$ nvm alias default 0.10.8

So you can easily switch back to that version by inputting:

nvm use default

Handy! You can actually set as many aliases as you want with the command:

nvm alias [name] [version]

(Thanks to Gergely Nemeth (@nthgergo) for the `nvm alias` tip).

Now lets get started with Koa

Create a new directory where your project will be, and from the terminal run `npm init`. This will setup your package.json file. For the purposes of this demo you can just hit enter through all of it. Now to install Koa, in your project directory run:

$ npm install koa --save

Notice that save tag at the end. If you are not already familiar with it, it will tell npm to automatically add the npm module you are installing to the dependencies in your package.json file. Since Koa is a collection of small modules, you’ll more than likely be installing a fair amount of them. So, that functionality comes in extra handy, saving you the steps of adding it yourself and figuring out which version you need. It is the “Node PACKAGE manager”, why not let it manage our packages for us?

Next lets create our app. In your project directory, create a file such as server.js, and set up the basics—

//We're using koa, so lets require it, (duh).
var koa = require('koa');
//and initialize it with
var app = koa();
//and then give it a port to listen for
app.listen(8008);
console.log('Koa listening on port 8008');

But as it sits, this app doesn’t do shit, so let’s make it handle some basic pages.

Adding some of Koa’s middleware

Koa’s middleware makes up all of the modular building blocks of Koa, which allow us to include only what we need. We could have done the most absolute barebones ‘Hello World’ example and made the app respond when you hit the port, but why don’t we check out some of koa’s middleware to setup some basic routes! In the terminal let’s install the `koa-route` module which will let us handle routes in Koa.

$ npm install koa-route --save

Then we can add a little onto our server.js file.

var koa = require('koa');
var route = require('koa-route'); //require it
var app = koa();//and we'll set up 2 routes, for our index and about me pages
app.use(route.get('/', index));
app.use(route.get('/about', about));
app.listen(8008);
console.log('Koa listening on port 8008');

Using the koa-route middleware is pretty straightforward. `app.use()` tells our Koa app to use whatever middleware we pass to it. The 2 arguments that we passed to our `route.get()` method are the route and a generator function (that we have yet to define) which tells that route what to do. So, we’ll have to define an `*index()` generator and an `*about()` generator.

Here’s a short description of JavaScript generators from MDN

“Generators are functions which can be exited and later re-entered. Their context (variable bindings) will be saved across re-entrances.”

Generators are still pretty fresh to JavaScript and still pretty fresh to me. So, instead of me trying to expand on that and possibly confusing you, I’d suggest perusing the many “What are JavaScript generators?” articles (such as this one from tobyho.com) that are all over the web for more information.

Back to setting up our simple generators so our app can actually do something when we hit the ‘/’ and ‘/about’ routes that we setup. We won’t be changing anything, so in the context of this demo they will behave pretty much like a regular function. You might think, “If we’re not using them like a generator then couldn’t we just pass a regular function?” Well, not quite. `route.get()` seems to be expecting a generator, and will throw a 500 error if you try and give it a regular function.

//The asterisk is key, designates a function as a generator.
function *index() {
this.body = "<h1>Hello! This is my home page!</h1>";
}

function *about() {
this.body = "<h2>My name is Adam and I like JavaScript</h2>";
}

Within these generators `this` refers to the Koa context. From the Koa.js docs —

A Koa Context encapsulates node’s request and response objects into a single object which provides many helpful methods for writing web applications and APIs. These operations are used so frequently in HTTP server development that they are added at this level instead of a higher level framework, which would force middleware to re-implement this common functionality.

A Context is created per request, and is referenced in middleware as the receiver, or the `this` identifier.

Startin’ her up

So with our comments stripped out, our little Koa app should look something like this:

var koa = require('koa');
var route = require('koa-route');
var app = koa();app.use(route.get('/', index));
app.use(route.get('/about', about));
function *index() {
this.body = "<h1>Hello! This is my home page!</h1>";
}
function *about() {
this.body = "<h2>My name is Adam and I like JavaScript</h2>";
}
app.listen(8008);
console.log('Koa listening on port 8008');

Not bad at all! Around 20 lines and we’ve got a barebones Koa app running. Almost. We should probably run it and make sure it all works, yeah?

Go back to your terminal and punch in:

$ node --harmony server.js

There’s that harmony mode I mentioned at the beginning. There are ways to get around typing that every time but I’ll go over that in part 2. You’ll see that “Koa listening on port 8008” print to your terminal and then in your browser you can navigate to ‘localhost:8008’.

fig. 1 — Home page

How about that? We’ve gotten a response from our Koa server and have a simple home page. Let’s also test our “about” page. Navigate to “localhost:8008/about”.

fig. 2 — About page

Great, now we have a separate page where we can describe ourselves!

Credits:
I first learned about NVM from marcusoft.net’s Koa tutorial, and I have also learned a ton from the Koa.js docs and their examples hosted on GitHub.

--

--