At this point, you may be thinking, "Why exactly should I use Koa, amid the myriad of Node.js frameworks available? What exactly makes Koa special or different?" That would be an excellent question. We will cover the answer to that in this section and list some reasons why Koa is a great choice for your next web development project.
As mentioned earlier, Koa is highly unopinionated, which makes its capabilities limited only by the developer's imagination. It is a framework that provides a light and highly configurable base for developers to quickly get started building out their web applications in JavaScript. Some of the things that make Koa a great choice include the following:
- Embraces modern standards: Koa embraces the more modern JavaScript ES6 syntax and encourages its use. The more modern syntax brings with it some advantages as the language evolves with every iteration.
- Very light: Koa is one of the lightest frameworks out there with around 2K LOC. It only comes with the bare minimum. This shows developers that the framework is simply there to help do the bare minimum needed for them to quickly develop their apps and not more or less.
- Highly unopinionated: Koa tries as much as possible not to restrict developers. It does not come with any middleware out of the box, not even for routing. Koa's aim is to allow developers to be even more expressive. Koa encourages developers to either develop any middleware they need or take advantage of the publicly available ones. The Koa core team has developed a number of middlewares that are available for developers to plug into their application if so needed.
- Ease of creating custom middleware: Middleware functions are functions that sit between requests and responses in an application. They can usually manipulate both the request and responses in an application. A key factor in middleware function definition is also calling the next middleware to be executed. Koa's middleware cascading pattern is also one of the reasons Koa is recommended. The cascading pattern makes implementing and understanding the flow of middleware in your applications very easy. Simple middleware in Koa can be defined and registered in as few as three lines, as seen in the following code snippet:
app.use(async (context, next) => {
console.log(`Time: ${Date.now()}`);
await next();
});
This code snippet is simple middleware for logging the time when a request is made to the server in Koa.
- Community support: As a result of its increase in popularity, a lot of plugins and middleware have been built and made publicly available. There are also a lot of JavaScript developers available to help answer questions and discuss issues related to the framework on popular forums.
- Ease to get started with: One of the things JavaScript developers who are familiar with Express love about the framework is how easy it is to get started with it. Koa also embraces that simplicity and makes it very easy for developers to get started with it. Little configuration has to be done to cascade a simple Koa application. To illustrate how easy it is to get started with Koa, here is a Koa Hello World app, as seen on the Koa official website:
// ./server.js
const Koa = require('koa');
const app = new Koa();
app.use(asyncctx => {
ctx.body = 'Hello World';
});
app.listen(3000);
- Flexible: Koa does not enforce folder and file structure; hence, developers can use their preferred file structures when developing applications in Koa.
- Ease of error handling: Koa's embrace of the async… await JavaScript ES6 syntax makes error handling much easier. It is also easy to define middleware in Koa to handle errors thrown at different points in your application.
- Database and ORM agnostic: Developers can create web applications that will use their database and Object Relation Mapper (ORM) of choice. They are not forced to stick to a particular database or ORM as defined by the framework. Databases such as MySQL, MongoDB, and PostgreSQL can be used with Koa. ORMs such as Mongoose, Sequelize,and Knex are also easy to integrate with the Koa framework.
- The similarity to Express: If you are like many Node developers, you have at one point or the other worked with Express. This familiarity with Express proves to be an asset when working with Koa, as it makes it easier to get accustomed to Koa and its philosophy. This also works the other way around too. If you get familiar with Koa before Express, it becomes easier for you to pick up Express projects and understand them.
- Concise code: Writing code in Koa is generally more concise than in other Node.js frameworks. This is because it ditches the use of callbacks and encourages the modern ES6 syntax. It also has a number of HTTP utilities bundled with it to make writing web applications an easier experience.
- Escape callback hell: As a result of Koa's reliance on modern standards in JavaScript development, we are able to avoid dealing with nested callbacks and the phenomenon known as callback hell when developing our applications. To illustrate this, here is an example of how an endpoint to retrieve all of the products in a category from a database would look in Express with the use of callbacks:
// ./express-route.js
app.get('/category/:slug', (req, res, next)) => {
const { slug } = req.params;
Category.findOne({ slug }, (err, category) => {
if (err) {
return next(err);
}
Product.find({ category: category.id }, (err, products)
=> {
if (err) {
return next(err);
}
res.send(products);
});
});
});
The same endpoint can be written in Koa, as seen in the following code snippet:
// ./koa-route.js
app.get('/category/:slug', async ctx => {
const { slug } = ctx.params;
const category = await Category.findOne({ slug });
const products = await Product.find({ category: category.id });
ctx.body = products;
});
From these examples, we can see clearly how much more readable the code written in Koa is. We can avoid nested callbacks with the use of promises and the async… await syntax.