KoaJS

Ayeshka Abeysinghe
1 min readMay 22, 2021

KoaJS is an open source framework developed by the developer of Express.js, where Express.js is a one of the most popular node web framework. It is a smaller and robust foundation for web applications and APIs. Furthermore, KoaJS greatly increase the error handling.

Async function

In order to use async functions in koa, the node version should be greater than 7.6

To parse and transpile async functions, you must have the transform-async-to-generator;

{
"plugins": ["transform-async-to-generator"]
}

Example

const Koa = require('koa');
const app = new Koa();

app.use(async ctx => {
ctx.body = 'Hello Koa';
});

app.listen(3000);

Error Handling

Koa implements a default error handler, which is one of the main benefits of using koa. It’s basically middleware with a try…catch block at the top of the Koa middleware stack. Unless some other error handlers are defined, it will always run the default error handler.

The default handler uses the status code of err.status, if not it uses 500 status which is Internal Server Error.

It also sends back err.message as the response if err.expose is set to true.

Context

A Koa Context is a single object that encapsulates a node’s request and response objects and offers several useful methods for writing web applications and APIs.

A context is created for each request, and is referred to as the receiver or the ctx identifier in middleware.

app.use(async ctx => {
ctx;
ctx.request;
ctx.response;
});

Some ctx requests;

  • ctx.header
  • ctx.headers
  • ctx.method

Some ctx responses;

  • ctx.set()
  • ctx.append()
  • ctx.remove()

--

--