Using Koa.js to write server-side code

Amila Devin
7 min readMay 9, 2022
koa.js

Introduction

Koa is a new web framework designed by the team behind Express, which aims to be a smaller, more expressive, and more robust foundation for web applications and APIs. By leveraging async functions, Koa allows you to ditch callbacks and greatly increase error-handling. Koa does not bundle any middleware within its core, and it provides an elegant suite of methods that make writing servers fast and enjoyable.

Features of Koa

Some of the features of the Koa framework include:

  • Designed as a lightweight and flexible framework for Node.js
  • Support for ECMAScript 6 (/ES2015) by default
  • Developers can use generators as functions to stop and resume the code execution
  • Simplifies the use of Error handling by using middleware more effectively
  • Identifies and understands all HTTP methods
  • Even before Express, Koa had support for async/await

Requirements

To use this framework, the only two requirements for runing the code examples below is to have Node.js installed in your local machine along with npm to access and install it as a dependency. The second requirement is to have a general understanding of JavaScript as a programming language.

Getting Started

You must first install Koa before you can use it as a server-side framework. Create a directory in which all project-related files will be stored. We’ll start by setting it up as a Node.js project.

npm init -y

This will assist us in creating a package. a json file that keeps track of all the dependencies we add to our project via npm. I’m using the -y parameter to bypass the npm questionnaire. When it’s finished, you’ll receive a similar outcome.

The next step is to make Koa a local dependence. I’m confident you understand what a local reliance is. If not, consult the documentation.

npm install -S koa

So far, everything has gone well. Now we can begin developing our application. However, you must have a Node.js version equal to or greater than _v7.6.0_ to utilize Koa on your local workstation or to deploy any server-side project that requires it.

Let’s Create Our First Koa App

First of all we should create an entry point file called index.js it is confrom in package.json.

"main": "index.js",

if you want to change that name you must edit your package.json file also.

Then, import the Koa library into our index.js file. Next, we create an instance named app that will have access to all of Koa’s API functions like use() and listen (). The middleware method is specified as app.use(). This middleware function is being used as a route. The app.listen() method tells the server to execute on a specific port, such as 5000.

Then you can run the server and see the output 😊

node index.js
First Koa App

What is ctx? : We are using ctx as an argument to the asynchronous middleware function. It is called Context in Koa and it encapsulates request and response objects into a single object. Unlike ExpressJS, that requires request and response as separate objects passed as arguments. In Koa, a context is created for every request that comes to the server and it always referenced as a middleware.

Installing Nodemon

Before I start on REST APIs, I’d want to provide a terrific tip for constructing a Node.js application. I use nodemon as a dependency during development mode, regardless of the framework I’m using, to listen for file changes and restart the program automatically. This avoids the need to repeatedly perform the node [filename].js command. You can completely skip this step and proceed to the next, where I demonstrate how to construct a REST API.

“ This simple program has had such an influence on my workflow that it has saved hours of effort. ”

npm install nodemon --save-dev

--save-dev or -D flag is used to tell npm to install the current dependency as a devDependency.

Once, nodemon is installed, append the package.json file and an npm script.

"scripts":{  "dev": "nodemon index.js"}

Now in terminal you can run this command

npm run dev

After that, to check you can do some changes (ex: rename the Hello World to another word or sentence and save it. then see the output. So, you can see the changes. beacuse the server restart automatacally when we do some changes 😍)

Note: File is a CommonJS module; it may be converted to an ES module.

Sourse Code up to now >>

Building the REST API

Now we need to install some dependencies for the API to work.

  • koa-router — is the routing middleware that provides ExpressJS style routing using HTTP verbs. It has methods that you can directly use in the application Such as app.get(), app.post(), etc.
  • koa-bodyparser — is a body-parser middleware. It supports urlencoded, multi-part and json request bodies. Basically, it helps to create and respond to HTTP POST requests which are available as a form field, or a file upload, etc. It tells the server that the incoming request from the client has a body of data.
  • koa-json — is a JSON pretty-printed response middleware. Also converts node object streams to binary.
npm i koa-router koa-bodyparser koa-json

Note: I will be mocking data in this application for the sake of brevity and clear understanding of framework’s concepts. If you want to, you can use the database of your choice. The structure of data is not complex.

ex: If your are using mongoDB you can use koa-mongo

After the install dependencies, You may have to import koa-bodyparser and koa-json to the ìndex.js .

Ànd tell to koa meddleware to use it.

After that, I am using another two file to describe the routes and it’s controllers to separate the code for clear understanding. Create two new file called userRouter.js and userController.js .

Another thing is we need store our data. For that I using Map() ànd I am using a another file to keep that data called userData.js .

Your not famillier with Map() read this Document.

First of all in userData.js we have to create new map for the users and export it.

Then i am going to create two functions, one for add data to the map and another one is read all data from the map.

  1. First of all we need to import the user map from the userData.js .
  2. Then create two functions addData and readAllData (i’m using Arrow functions for that) and export.
  3. Then we need to assign a parameter called ctx what we talked about befrore creating our first koa.js app
  4. Then inside the Functions body we need to execuute what to do.
  • Using ctx.request , We can request any type of data. (examples: ctx.request.body, ctx.request.params.email, ctx.request.headers)
  • Using ctx.body , We can assign any type of data as a response.
  • Using ctx.status , We can assign the response HTTP status.

After that we have to create api routes for each and every functions.

  1. We need to import our Controller file to the userRouter.js wthing exported objects.
  2. And import the koa-router and create a ne object for that (Also, you can pass a prefix inside koa-router object)
  3. Then, we can create HTTP methods.
  4. After that export the koa-router object.

After that, we need to call that routes file inside our app main file called index.js .

Now you can check outputs 😎.(for that, I’m using postman)

add data in postman
read all data in postman

Sourse Code up to now >>

Creating Middlewares

To create a middleware we need to use argument called next(). This is often used in middleware functions. Any middleware function invokes to another function to indicate the current middleware function has suspended running and the next middleware function available must be invoked.

For better explaing I’m try to use in our application, assign an authentication to read own user data.

For that I using JWT token and create a token using email and when user details adding create a JWT token and send it as a response. Then if user want to get user’s own data user must be a authentication user.

For do that,

1. we need to install dependencie called jsonwebtoken .

npm i jsonwebtoken

2. Create a file called config.js and create a constant ACCESS_TOKEN_SECRET and export it.

3. import jsonwebtoken and config.js file to the userController.js and create a function called createAccessToken to genarete a token.

3. Then in addData function call the createAccessToken function and pass the generated token as a response check the output

generate a web token

4. create a file called userAuth.js to create a middleware to authenticate a user.

5. cretae a function to get a user details in userController.js

6. Add a route to get user function and before the getUser function call the auth function what we define in userAuth.js

7. Let’s check the Output

autn get user details

Sourse Code up to now >>

Other Usefull Koa Dependencies

and you can use any other dependencies.

--

--

Amila Devin

BSc (Hons) in Information Technology Specialising in Software Engineering undergraduate at SLIIT