There are a few nodeJs web frameworks, and one of the most popular ones is express.js. I want to explain why I decided to move from express.js to koa, when writing server code.

To understand this article, you should know about:

javascript

– what is a promise

– how to write promises with async/await

– what is a promise – how to write promises with async/await nodeJs

– how to setup up a simple express.js server

– what is an express middleware

TL;DR

With NodeJS version 7 came the support of async/await function.

Koa just plays more naturally with them ➡️ use Koa.

Express

We will write a simple route that will:

query a database to get some stuff pass the result to a second database call then send the final result as the response

node style callbacks

Here, we will use the nodeJs style callback signature:

A callback function with error as the first argument & result as the second.

So far so good.

Luckily, our database object also supports promises.

promises

The following will do the same as the code above but:

we can flatten our code

we don’t duplicate anymore the error control

the catch will not handle synchronous errors

So far so good.

And luckily, since we use nodeJS >= 7 we can use async/await.

async/await

The following will do the same as the code above but:

we have a less cumbersome code

we still don’t duplicate the error control

any error inside the try/catch will be handled

So far so good.

But it will get a little messier if we add more routes:

You see?

We write again and again try {} catch(error){ next(error) } Not a big deal but quite boring at the end…

But luckily we can write a wrapper function for that!

better async/await

So let’s write our wrapper:

A more detailed article about that was written by Alex Bazhenov

Finally, let's use it in our code:

So far so good. But, we still have to write some boilerplate to handle that…

Here comes KOA!

KOA

What is KOA?

In brief, it’s the same team behind express.js that have written a web framework using the recent additions in the JavaScript language.

At its core it’s using promises with async/await

You can find the full introduction here

Setting up a server with Koa is very straightforward.

For the routing, as nothing is provided by default, we will use koa-router

Setting up the router and error middleware

This snippet should be enough:

Writing our routes

And this is how we will write our application code:

Which appears to me more leaner 😀

no duplicated try/catch

no need to write an async middleware

no need to wrap all our route handlers into that middleware

handle both sync/async errors

About Koa ecosystem

As for now, Koa hasn’t as much middleware as express.js.

This can be an issue in migrating.

But the must have middlewares are already here, and writing your own is quite easy.

I never found myself in a situation that I couldn’t achieve what I wanted with Koa.