Home Web Development Server Side development with Node.js and Koa.js Quick Start Guide

Server Side development with Node.js and Koa.js Quick Start Guide

By Olayinka Omole
books-svg-icon Book
eBook $25.99 $17.99
Print $32.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $25.99 $17.99
Print $32.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
About this book
Every developer wants to build modular and scalable web applications. Modern versions of JavaScript have made this possible in Node.js, and Koa is a Node.js framework that makes it easy. This book is the ideal introduction for JavaScript developers who want to create scalable server side applications using Node.js and Koa.js. The book shows you how Koa can be used to start projects from scratch, register custom and existing middleware, read requests, and send responses to users. We will explore the core concepts in Koa, such as error handling, logging, and request and response handling. We will dive into new concepts in JavaScript development, and see how paradigms such as async/await help with modern Node.js application development. By the end of this book, you will be building robust web applications in Koa using modern development paradigms and techniques of Node.js development.
Publication date:
November 2018
Publisher
Packt
Pages
132
ISBN
9781789345391

 

Introducing Koa

Node.js, which was introduced in 2009, has become very popular for building applications and APIs on the web. One of the major factors that influenced its increase in popularity is the fact that developers can now use a single language for developing their applications, both on the server side and client side. JavaScript developers who usually only worked on client-side applications in the past could now work on server-side applications with the same development stack. This increase in popularity and adoption has led to a lot of community enthusiasm and support, which by extension has caused a lot of frameworks and plugins being developed to optimize scripting and software development in Node.js.

Many of these frameworks are focused on different ideologies and functionalities. Express.js, with over four million weekly downloads as at the time of writing, is one of the more popular frameworks for Node.js. It was built to be a very simple and unopinionated framework for quickly building out web applications in Node.js. Koa.js was built to be an improvement on Express.js, with the same underlying philosophy.

Since its introduction, JavaScript has continually evolved and every iteration brings with it advantages and upgrades. Koa leverages on a lot of new and shiny things in the newer JavaScript versions, such as the async... await syntax. These features are part of what makes Koa a fast and easy-to-use web development tool.

The topics that will be covered in this chapter are the following:

  • What is Koa?
  • What can you do with Koa?
  • Why choose Koa?
  • When you should not use Koa
  • Introducing Koa2
  • Koa versus Express
  • How can this book help you understand Koa better?

 

Technical requirements

To follow along with this chapter, you need the following installed locally:
Node.js (>= v7.6.0) and NPM: You can find download and installation instructions for this on the Node.js official website (https://nodejs.org/en/).

If you use macOS, you can make use of the Homebrew package manager to install Node.js easily.

The code files of this chapter can be found on GitHub:
https://github.com/PacktPublishing/Server-Side-development-with-Node.js-and-Koa.js-Quick-Start-Guide/tree/master/Chapter01

Check out the following video to see the code in action:
http://bit.ly/2BH8gz0

 

What is Koa?

Koa is a newly popular Node.js framework created by the team at Express. It was built to be a more expressive, minimalist, and modern version of its predecessor. As a matter of fact, because of its embrace of modern development techniques in JavaScript, it has been referred to by some people as Express 5.0 in spirit.

Development on the Koa framework started sometime in late 2013 by the same team behind Express. It was decided that adding too many breaking changes to Express would be undesirable; hence, the team decided to take the new ideas it had to create a new framework, while development continued on Express itself in parallel. Koa was initially written to leverage the async goodness of the then-newly introduced JavaScript generators. Since then, Koa has been rewritten using the more modern async...await, making the code base even cleaner.

With around 2K LOC (lines of code), Koa can boast a very minimalistic code footprint. Koa is also very unopinionated; in fact, it does not ship with any middleware out of the box. Instead, it leaves these decisions to the developers. Developers can choose to either build out the middleware they need or take advantage of the ones built by other developers that are publicly available online.

By making use of the modern JavaScript async… await syntax, Koa allows developers to escape callback hell and handle errors better. Its futuristic approach to development in JavaScript makes it a choice for developers who enjoy trying out new things. If you are unfamiliar with what async… await is, not to worry, we will be covering it in following chapters.

 

What can you do with Koa?

So, you have heard about Koa, and are trying to decide whether you should get into it. What could be the deciding factor is the use case you have in mind. After all, in the world of software development tools and frameworks, what really matters is what you are capable of doing with these tools and frameworks.

If you want to build scalable web applications and APIs in JavaScript, then Koa is a good fit. Koa can be used to create a range of web applications such as forums, e-commerce websites, and social networks. You can use Koa to build something as simple as a to-do list application or something as complicated as an e-commerce website.

Koa is also great for building services such as Representational State Transfer (REST) APIs that could provide data to be used by frontend applications. REST APIs that are built in Koa are a good choice for frontend applications written in plain JavaScript, Angular, React, Vue.js, or any other User Interface (UI) framework.

 

Why choose Koa?

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.

 

When you should not use Koa

Although Koa is a great choice for building HTTP services and web applications, it is not always the best option for all projects. Just like with every framework, language, and even design pattern, the very things that are advantages become drawbacks when dealing with certain use cases. It is best to judge the use of Koa on a case by case basis and make use of it only when it is a good fit for the particular project.

Generally, Koa will not be a great choice for you if you are not willing to try out the newer JavaScript ES6 syntax. Koa was built for the modern web. If, for some reason, your project has a strict requirement to use an older version of JavaScript, Koa would not be suitable.

If you would also prefer a framework with a lot of boilerplate code and a defined structure, you might have to look at other frameworks such as hapi.js and AdonisJs. Koa, much like Express, prides itself on minimalism and allowing developers to be expressive. Having a lot of boilerplate and a strict code structure are not philosophies Koa embraces.

It is also important to note that Koa is a framework built on top of JavaScript and Node.js. As Koa inherits the advantages of Node, such as being fast at performing network and asynchronous operations, it also inherits some of the drawbacks and limitations that are present in Node. Koa would not be an ideal choice for a project where JavaScript is not the language of choice.

 

Koa versus Express

Koa and Express share a lot of similarities, as the development of the two frameworks was kickstarted by the same team. While a lot of the underlying philosophies between Koa and Express are the same, clear differences exist as the creators of the frameworks attempted to do things in a different way with the release of Koa.

A major difference is in the philosophy of the two frameworks. Whereas Express complements Node, Koa attempts to fix and replace many things in it. The major difference is the fact that Koa tries to completely ditch callbacks and avoid callback hell by making use of promises and async functions.

Unlike Express, which augments Node's request (req) and response (res) objects with additional parameters and methods, Koa provides its own ctx.request and ctx.response objects. According to the Koa documentation, the following is true:

"Koa can be viewed as an abstraction of Node.js's http modules, whereas Express is an application framework for Node.js."

Koa tries to fix some of the things wrong with Node and provides a simple, lightweight, and unopinionated framework for building out HTTP services.

Some other differences between Koa and Express include the following:

  • Router: Koa does not include a router out of the box; instead, external middleware is available to be used as routers such as koa-router and koa-route. Express, on the other hand, comes bundled with a router out of the box.
  • Templating: Express has support for various popular templating engines out of the box, including Jade, Pug, EJS,and Mustache. In contrast, Koa requires installing an external plugin/middleware to support templating engines. A popular plugin for templating in Koa is koa-views.
  • Convenience utilities: Express includes some convenience utilities (https://expressjs.com/en/resources/utils.html) to help programmers handle regular tasks such as file streaming and URL parsing. Koa does not include these utilities.
  • Promise-based control flow: Koa has the advantage of ditching callbacks and avoiding callback hell by making heavy use of promises, unlike its predecessor, Express. This ensures that errors are easier to handle without many try... catch statements.
  • Cascading middleware pattern of flow in Koa.js: This allows middleware to take action exactly twice for each request whereas express middleware allows for only single execution per request. This flexibility allows Koa middleware developers to use the patterns established in other languages and systems such as Ruby's Rack.

Here is a table from the Koa documentation, comparing it to Express:

Feature Koa Express
Middleware Kernel
Routing
Templating
Sending files
JSONP

 

How can this book help you understand Koa better?

This book takes a practical approach to teach JavaScript developers how to understand the Koa framework. In the course of this book, we will examine important concepts in Koa, such as the request, response, and context objects. We will also look at other concepts that will be helpful for building real-world applications such as request and error handling.

We will build two applications to reinforce the concepts we learned about Koa. These applications will include a REST API and a fully-fledged web application.

As we build the REST API, we will learn how to create routes, handle requests, and send responses from their APIs. We will also learn practically how the context object works for API creation. We will build an API that will have CRUD (Create, Read, Update, and Delete) functionality; hence, we will also be interacting with a database. Building a real-life application will also afford us the chance to learn about how you can decide to structure your Koa applications.

Building the fully-fledged web application will allow us to learn how to build an application in Koa with views and templates. We will also learn how to authenticate, handle forms, handle sessions, and so on, in the framework.

 

Summary

In this chapter, we introduced Koa and talked about its benefits for server-side web development. We talked about what developers can build with Koa and established some of its many advantages. We were also able to talk about cases when using Koa might not be ideal.

Finally, we talked about how this book is structured and how it will help you learn and understand the Koa framework better.

The next chapter will cover getting started with Koa. In the next chapter, we will learn how to get started with server-side development with Koa. We will learn how to install Koa, create a simple server, and build the obligatory Hello World app. The chapter will introduce us to some hands-on work in Koa, and we will begin to explore why Koa is so highly recommended.

About the Author
  • Olayinka Omole

    Olayinka Omole is a software engineer currently based in London who grew up in Lagos, Nigeria. He is self-taught and primarily enjoys building with JavaScript, Python, PHP, and Java. He has written a lot about these technologies in multiple blogs and publications, including Sitepoint, and Scotch.io. He spends most of his time doing the usual fun thingswriting code, learning how to write more code, and watching TV shows. His background in electrical and electronic engineering ensures that his passion for embedded engineering and DIY projects is also kept alive.

    Browse publications by this author
Server Side development with Node.js and Koa.js Quick Start Guide
Unlock this book and the full library FREE for 7 days
Start now