DEV Community

Cover image for Koa.js: A Lightweight Framework for APIs & Web Apps
Mohan Sandesh
Mohan Sandesh

Posted on

Koa.js: A Lightweight Framework for APIs & Web Apps

Koa is a web framework from the Express.js team. It is a lightweight modern middleware framework that lets us use async middleware functions.

Example App

const Koa = require('koa');
const app = new Koa();

app.use(async function(ctx) {
  ctx.body = 'Hello';
});

app.listen(3000);
Enter fullscreen mode Exit fullscreen mode

Here we created a Koa instance, and set a middleware that responds with "Hello" for every request.

Features

  • Modern syntax
  • Supports async/await middleware.
  • Lightweight, only ~570 lines of code.
    • Zero bundled middlewares.
  • Context (ctx) object, in place of (req, res)
    • Middleware signature is middleware(ctx, next)
  • Better error handling

What is a middleware?

A middleware is a function that receives a http request and may respond to the request, within the request/response cycle. It can also call the next middleware in the list. Here is an example.

async function exampleMiddleware(ctx, next) {
  // Read request data from ctx (context)
  // More logic
  // Set ctx.body as response

  // Call next middleware
  await next();

  // After next is called, we can do more, because of the await syntax.
  // For example log the time taken
}

// Set the middleware
app.use(exampleMiddleware);
Enter fullscreen mode Exit fullscreen mode

A middleware framework lets us define multiple middleware functions and executes them in the order they are defined. As you might have noticed the next argument in the above example. It is the function, when called passes the control to the next middleware.

Using async functions lets us use await to do something after a middleware has been executed, in a stack like manner.

next does not need to be called, if further execution is not needed. For instance, think of an authentication middleware. If user is logged-in, call next, or else display login page.

// Authentication Middleware
app.use(async (ctx, next) => {
  if(user){
    // Call next middleware in the list
    await next();
  } else {
    // Display login page
  }
});

// Hello Middleware
app.use(async (ctx) => {
  ctx.body = 'Hello';
});
Enter fullscreen mode Exit fullscreen mode

As you can see, order of the middleware is significant.

Koa Context (ctx)

Each middleware receives two arguments. First one is Context (shortly written as ctx) and next.

ctx contains properties from the request. Additionally it contains setters that can respond to the request.

Here is a list of common properties. You can find a complete list here.

Name Description
ctx.method Current request method
ctx.path Current request path
ctx.query Query String
ctx.body Setter to set response body

How to do common tasks

Add a middleware

Use app.use - docs. Note that the order of the middleware is important.

app.use(middlewareFunction1);
app.use(middlewareFunction2);
app.use(middlewareFunction3);
Enter fullscreen mode Exit fullscreen mode

Start the server

Use app.listen - docs.

app.listen(3000);
Enter fullscreen mode Exit fullscreen mode

Set response body

Use ctx.body setter - docs.

app.use((ctx)=>{
  ctx.body = {
    'hello': 'Koa'
  };
});
Enter fullscreen mode Exit fullscreen mode

Redirect

Use ctx.redirect - docs.

ctx.redirect('/login');
Enter fullscreen mode Exit fullscreen mode

Error Handling

Use ctx.throw - docs.

ctx.throw(400);
Enter fullscreen mode Exit fullscreen mode

How to build a complete app

Koa provides the middleware framework and ctx to use in the middlewares. It does not come bundled with any middlewares.

To build a complete app we need to use middlewares provided by the Koa community. Here is a list of common middlewares.

You can browse Koa GitHub for more available middlewares.

Conclusion

Koa is great lightweight modern web framework for building APIs and web applications. You can read more docs on the Koa website.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay