Categories
Koa Nodejs

Introduction to Backend Development with Koa

Spread the love

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

To get started, we first install the Koa package by running:

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

This is the Node’s request object

ctx.res

Node’s response object. We shouldn’t use this to manipulate the response. So res.statusCodee , res.writeHead() , res.write() , and res.end() to set the status code and to write the response header and body.

ctx.request

This is Koa’s request object. We should use this to get the request data in Koa apps.

Setting the Response with ctx.response

This is Koa’s response object. We can use this to set the response headers and other data.

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

The ctx.state is used to set data that are used to pass data between middlewares. For instance, we can use it as follows:

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

The ctx.cookies property lets us get and set cookies. We can call get by writing the following code:

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 .

Set Response Cookie Header Value with ctx.cookies.set

We can call ctx.cookies.set to set the response’s Cookie header value.

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

We can create a simple Koa app with one function. Most of the manipulation is done with the context object in the function, which includes manipulate response and getting request data.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.