What is Koa.js & How to setup your First Koa.js Project.

Sitharakumarasingha
2 min readMay 15, 2022

What is Koa.js?

Koa provides a minimal interface to build applications. It is a very small framework (600 LoC) which provides the required tools to build apps and is quite flexible. It’s an open source framework created and maintained by the same people that created Express.js, the most popular node web framework.

Why Koa.js?

Koa has a large community and is totally pluggable. This also allows us to simply extend Koa and modify it to our own requirements. It’s created using bleeding edge technology (ES6), giving it an advantage over older frameworks like express. It has a small footprint (600 LoC) and is a very thin layer of abstraction over the node to create server side apps.

Environment

To begin building using the Koa framework, you need to have Node and npm installed. Run the following commands in your terminal to verify that node and npm are installed. (Make sure your node version is above 6.5.0.)

$ node --version
$ npm --version

Use npm

To install a package locally, use the same command as above without the −g flag.

$ npm install <package-name>

To create our project step by step:

Step 1 -: Fire up your terminal/cmd, create a new folder named first and cd into it,

Step 2 -: Now to create the package.json file using npm, use the following.

npm init

Next, It’ll ask you [Is this ok?(yes) yes], Just keep pressing enter, and enter your name in the “author name” field.

Step 3 -: Now we have our package.json file set up, we’ll install Koa. To install Koa and add it in our package.json file, use the following command.

$ npm install --save koa

This - -save flag ensures that Koa is added to our package.json as a dependency.

Run the following command to ensure Koa is properly installed.

$ ls node_modules #(dir node_modules for windows)

Next, we’ll install nodemon, a npm utility. This tool automatically restarts our server whenever we make a change to any of our files, we would have to manually restart the server after each file edit. Use the following command to install nodemon.

$ npm install -g nodemon

We’re all set to dive into Koa now!

Hello World

After we’ve set up the development environment, we can begin working on our first Koa project. Create a new file called app.js and type the following in it.

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

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

app.listen(3000, function(){
console.log('Server running on https://localhost:3000')
});

Save the file, go to your terminal and type.

$ nodemon app.js

The server will now be started. To test this app, go to https://localhost:3000 in your browser and you should see the ‘ Hello world! ’ message.

--

--