Getting Started with Koa.js

Thushara Thiwanka
CodeX
Published in
3 min readApr 15, 2021

Basically, Express js is the framework that ruled it as a backend framework a few years back. Also, Koa js is a modern and minimalistic Node.js framework which is created by the creators of Express js. Koa is a bit modern since it uses ES6 syntax and all. If you know Express js you will see that syntax is very similar when comparing with koa and you will pick it up very quickly. Here, we are going to discuss installing koa and creating a server that listens to a certain port.

What is Koa?

A New server-side framework for node.js from the creators of express js. Koa is extremely lightweight when comparing to others and we have the option to extend the framework by adding modules. Also, a very modern framework that uses ES6 and the above syntax which allows you to provide better error handling in the application. This helps developers to create applications that last a long time.

Installing Koa

Before installing koa you have to install the node.js. Then initialize a node project open up the terminal and type the npm init command. Also, by passing -y as an argument you can skip all the questions and fill the project details using default values.

When all the prerequisites are completed we can install the koa framework into our project by using npm install koa/npm i koa. This will create the node_modules folder and package-lock JSON file to keep track of the versions of packages and koa will be kept inside the node_modules folder.

Then we are going to install nodemon which helps with refreshing the server when changes have been made. we can install nodemon global or as a development server dependency. I am going to install this as a dev dependency using npm install nodemon/npm i nodemon then by passing -D or - -save-dev as an argument.

And we have to do one more thing before the star thing up with koa js. We are going to create a script to run this application by nodemon so that we don't have to type nodemon then filename to run the application. I am going to assign that to the npm script inside the package.json file. See the attachment below for a better understanding.

Now we can use npm start command to start up our application. Since we don't have an index.js file let’s go ahead and create that in the root folder.

Creating a server with Koa

First, let’s see how to create a server and listen to a specific port number. Refer to the code below.

Then run the application using the script that we created before. open the browser and go to localhost:3000 to see the output as Hello World. Now we have created a server that returns ‘Hello World’ to all requests.

We also can return JSON data or HTML files. We are not going to talk about that here. If you want to look more into koa js click here to go to the koa documentation page.

--

--