Introduction to Backend Development with Koa

John Au-Yeung
May 25, 2020 · 4 min read
Image for post
Image for post
Photo by Craig Lovelidge on Unsplash

Koa is a small framework that lets us create backend apps that run on the Node.hs platform.

In this article, we’ll look at how to create a simple back end app with Koa.

Getting Started

npm i koa

Then we can create our first by writing the following code:

const Koa = require('koa');
const app = new Koa();
app.use(async ctx => {
ctx.body = 'Hello';
});
app.listen(3000);

In the code above, we instantiate the Koa app with the Koa constructor. Then we called app.use with an async function that takes the ctx object.

The async function is called middleware. It’s the basic building block of a Koa app. It runs like a stack-like manner upon request. It’s similar to other frameworks like Express which runs a chain of middlewares in order to process incoming requests.

The ctx object is the context object, which is used for many things. In the code above, we set the value of the body property to set the 'Hello' to return the 'Hello' string as the response.

It’s also used for setting response headers, cookies, and getting the request payload and the responses.

The ctx has the following properties:

ctx.req

ctx.res

ctx.request

Setting the Response with ctx.response

For instance, we can set the content-type response header by setting it as follows:

const Koa = require('koa');
const app = new Koa();
app.use(async ctx => {
ctx.response.type = 'text/plain; charset=utf-16';
ctx.body = 'Hello';
});
app.listen(3000);

In the code above, we set the ctx.response.type property to ‘text/plain; charset=utf-16’; .

When we run the code above, we’ll see that the Content-Type header is set to ‘text/plain; charset=utf-16’ as its value.

Setting State with ctx.state

const Koa = require('koa');
const app = new Koa();
app.use(async (ctx, next) => {
ctx.state.foo = 'foo';
await next();
});
app.use(async ctx => {
ctx.body = ctx.state.foo;
});
app.listen(3000);

In the code above, we have the next parameter, which is a function that we use to call the next middleware that’s attached to our app.

We set the ctx.state property by setting a custom property foo with the value 'foo' .

Then we called next to call the next middleware. And in the 2nd middleware, we get the ctx.state.foo and set that as the value of ctx.body .

Therefore, when we run our app, we get the text ‘foo’ displayed.

Get Request Cookie Header Value with ctx.cookies.get

const Koa = require('koa');
const app = new Koa();
app.use(async (ctx, next) => {
ctx.body = ctx.cookies.get('foo');
});
app.listen(3000);

In the code above, we get cookie’s foo key’s value by calling the ctx.cookies.get method.

Then we set that as the value of ctx.body and show that on the screen when we run our app if we set the Cookie header’s to something like foo=bar .

Therefore, we’ll see bar displayed on the screen if we make the request to our with the Cookie header with the key foo .

Image for post
Image for post
Photo by Rai Vidanes on Unsplash

Set Response Cookie Header Value with ctx.cookies.set

For instance, we can do that as follows:

const Koa = require('koa');
const app = new Koa();
app.use(async (ctx, next) => {
ctx.cookies.set('bar', 'baz');
ctx.body = 'foo';
});
app.listen(3000);

In the code above, we set the response cookie with the key 'bar' and the value 'baz' . It also takes a third argument with various options.

They include:

  • maxAge — max-age of the cookie in milliseconds
  • signed — sign the cookie value
  • expires — the expiry date of the cookie
  • path — cookie path, which defaults to /
  • domain — cookie domain
  • secure — secure cookie
  • httpOnly — make the cookie server accessible
  • overwrite — a boolean to indicate if we want to overwrite previously set cookies

We can pass in some options as follows:

const Koa = require('koa');
const app = new Koa();
app.use(async (ctx, next) => {
ctx.cookies.set('bar', 'baz', {
expires: new Date(2020, 12, 31)
});
ctx.body = 'foo';
});
app.listen(3000);

In the code above we set the expiry date of our cookie to December 31, 2020.

Conclusion

The Startup

Medium's largest active publication, followed by +752K people. Follow to join our community.

John Au-Yeung

Written by

Web developer. Subscribe to my email list now at http://jauyeung.net/subscribe/. Email me at hohanga@gmail.com

The Startup

Medium's largest active publication, followed by +752K people. Follow to join our community.

John Au-Yeung

Written by

Web developer. Subscribe to my email list now at http://jauyeung.net/subscribe/. Email me at hohanga@gmail.com

The Startup

Medium's largest active publication, followed by +752K people. Follow to join our community.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store