Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Server Side development with Node.js and Koa.js Quick Start Guide
Server Side development with Node.js and Koa.js Quick Start Guide

Server Side development with Node.js and Koa.js Quick Start Guide: Build robust and scalable web applications with modern JavaScript techniques

Arrow left icon
Profile Icon Omole
Arrow right icon
S$12.99 S$35.99
Full star icon Full star icon Full star icon Full star icon Half star icon 4.5 (2 Ratings)
eBook Nov 2018 132 pages 1st Edition
eBook
S$12.99 S$35.99
Paperback
S$44.99
Subscription
Free Trial
Arrow left icon
Profile Icon Omole
Arrow right icon
S$12.99 S$35.99
Full star icon Full star icon Full star icon Full star icon Half star icon 4.5 (2 Ratings)
eBook Nov 2018 132 pages 1st Edition
eBook
S$12.99 S$35.99
Paperback
S$44.99
Subscription
Free Trial
eBook
S$12.99 S$35.99
Paperback
S$44.99
Subscription
Free Trial

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

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

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.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Get up and running with Koa.js and leverage its power with node.js
  • Get the most out of Koa Async functions and generators
  • Create real time dynamic serverside apps efficiently with Koa.js

Description

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.

Who is this book for?

This book is for serverside developers and JavaScript developers who want to use Koa.js and Node.js to create fast and real time back end applications.

What you will learn

  • Create a simple server in Node.js and Koa
  • Work with custom middleware in Koa
  • Handle errors in Koa
  • Create routes, handle requests, and send responses from APIs
  • Build views and use templates in Koa
  • Authenticate your application and structure it properly in Koa

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Nov 30, 2018
Length: 132 pages
Edition : 1st
Language : English
ISBN-13 : 9781789343663
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Nov 30, 2018
Length: 132 pages
Edition : 1st
Language : English
ISBN-13 : 9781789343663
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just S$6 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just S$6 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total S$ 178.97
Node.js Web Development
S$66.99
Modern JavaScript Web Development Cookbook
S$66.99
Server Side development with Node.js and Koa.js Quick Start Guide
S$44.99
Total S$ 178.97 Stars icon
Banner background image

Table of Contents

7 Chapters
Introducing Koa Chevron down icon Chevron up icon
Getting Started with Koa Chevron down icon Chevron up icon
Koa Core Concepts Chevron down icon Chevron up icon
Handling Errors in Koa Chevron down icon Chevron up icon
Building an API in Koa Chevron down icon Chevron up icon
Building an Application in Koa Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.5
(2 Ratings)
5 star 50%
4 star 50%
3 star 0%
2 star 0%
1 star 0%
Zach James Jan 27, 2019
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This is a good book that is updated for Koa2. Enjoyable to read!
Amazon Verified review Amazon
Greg Tippett Oct 17, 2021
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
This is a great intro to Koa for readers already familiar with Node. The example app is well-organized and the reader is left with a good basic reference.Improvements for a second edition could include discussion of various concepts such as the differences between session and state, the use of session secret keys, and why the method-override middleware is needed.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.