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

eBook
NZ$26.99 NZ$38.99
Paperback
NZ$48.99
Subscription
Free Trial

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
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 : 9781789345391
Languages :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Nov 30, 2018
Length: 132 pages
Edition : 1st
Language : English
ISBN-13 : 9781789345391
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 NZ$7 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 NZ$7 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total NZ$ 192.97
Node.js Web Development
NZ$71.99
Modern JavaScript Web Development Cookbook
NZ$71.99
Server Side development with Node.js and Koa.js Quick Start Guide
NZ$48.99
Total NZ$ 192.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

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.