How to use Koa Js for backend

Tharuka Gayashan
4 min readMay 15, 2022

--

What is Koa JS ?

Koa is a web application development framework. This was developed by the same people who created the express framework. The main reason for creating this framework is to provide opportunities to create a small and robust base API and web application.

Pros and Cons in Koa Js

Pros

  • Light weight framework.
  • Have a proven report to the development team.
  • Use to create Rest API
  • Async/Await functions
  • Generator Supported

Cons

  • Small community
  • Incompatible generators

KOA JS features

  • Modern and futuristic framework
  • It has a small footprint
  • Uses Es 6 handling
  • It uses a context object

Now we are going to see how to make an API from koa. First we have to know a little bit about the npm module. Let’s see where we use them.

Hello world Program with koa.

1. you need to install the node on the computer. => https://nodejs.org

Step 01

2. First we need to create a folder to create the Koa API. You can create it in an easy path. If you have a windows computer you can create a folder by right click the mouse or using the following command in your terminal.

mkdir Koa-API

The name of the folder i am creating here is Koa-API.

3. Now we need to change the directory to already created folder. To do this, Use the cd command on the terminal. Let’s look at it bellow.

cd Koa-API

4. Now we have to initialize the node project. To do so, use the following command on the terminal.

npm init –y

5. After running this command you will create a package.json file with default configurations.

6. Now our project is done. Now we need to install the koa module which is the npm module we want.

npm install koa

Step 02

· Now create a JS file named server for you to code.

· Let us now see how to write a “Hello World” program.

The above code creates a program that runs on port number 8000. Now we have to run the program. To do so, Use the code bellow.

node server.js

and visit on application on http://localhost:8000, you can see “Hello World” on the browser.

Step 03

Work with koa router

  • To use koa routes, you must first install the @koa/router module and the koa-bodyparser module.

npm install @koa/router koa-bodyparser

  • Usually routes use a database to insert data. Since this is a sample, I use an array to save the data.

Let us now see how to write create, update, read and delete routes from the diagrams below.

Get Route = Read all the data

Post Route = Insert new data

Put Route = Update a existing data

Delete Route = Delete a data

Use the postman to see if your CRUD operations are successfully working.

In today’s blog I talked about koa.js, a very popular backend development framework and its CRUD(Create,Read,Update,Delete) operations. So I think these points will be important for someone who is new to Koa.js.

Thank you.

--

--