I've been a fan of Node.js for a very long time, and I have been using Typescript since the 1.x days. Actually, I wrote my first ever HTTP server in Node.js. It was an API for a simple browser game. I remember writing it in vanilla Node, and most of the resources online were using plain examples with no framework dependencies. Shortly after that, the Express.js framework got so popular, Node.js became synonymous with Express.

Express is really awesome — in fact, most of my Node.js projects use express — however, there quite a few other options out there that we should consider when starting a new project. We might find that some of the modern Node.js frameworks better fit our needs.

I'm planning to write a series of posts on these frameworks to make it a bit more accessible for developers wanting to play around.

In this post we're going to build a quick Koa starter. Here's a short introduction taken from their website:

Koa is a new web framework designed by the team behind Express, which aims to be a smaller, more expressive, and more robust foundation for web applications and APIs. By leveraging async functions, Koa allows you to ditch callbacks and greatly increase error-handling. Koa does not bundle any middleware within its core, and it provides an elegant suite of methods that make writing servers fast and enjoyable.

Pretty awesome, right? Let's dive in.

Project setup

TL;DR you can find the repository with the code here.

We're going to need a project directory, with two directories inside it. One we can call src (this is where we'll create the Typescript files) and the other one build (this is where Typescript will transpile into).

Next step is to make sure we have Typescript installed, so we're just going to install it globally.

npm i -g typescript

We're also going to need a tsconfig.json file, that is responsible for configuring the compiler. Create it in your project directory and use the values below.

{
  "compilerOptions": {
    "outDir": "./build",
    "lib": [ "es5", "es6" ],
    "module": "commonjs",
    "target": "es6",
    "sourceMap": true
  },
  "exclude": [
    "node_modules"
  ]
}

Alright, now onto the Koa project, let's type a few commands into our terminal (make sure you're in your project directory)

We're going to initiate a new Node.js project typing

npm init -y

And let's install some packages related to Koa

npm i -S koa koa-router koa-bodyparser koa-json koa-logger 

We'll also add type definitions for these, like so

npm i -D @types/koa @types/koa-router @types/koa-bodyparser @types/koa-json  @types/koa-logger

Okay, we should be all set up, now it's time to add some actual code.

Create an Index.ts file in the src directory, and paste the code below into it.

import * as Koa from "koa";
import * as Router from "koa-router";

import * as logger from "koa-logger";
import * as json from "koa-json";

import * as bodyParser from "koa-bodyparser";


const app       = new Koa();
const router    = new Router();
const PORT      = 3000;



/** Middlewares */
app.use( json() );
app.use( logger() );
app.use( bodyParser() );



/** Routes */
app.use( router.routes() ).use( router.allowedMethods() );


router.get( '/', async (ctx: Koa.Context, next: () => Promise<any>) => {

    ctx.body = { message: "This is your GET route" };

    await next();
});


router.post( '/data', async (ctx: Koa.Context, next: () => Promise<any>) => {

    ctx.body = { message: "This is your POST route, attached you can find the data you sent", body: ctx.request.body };
    
    await next();
});


app.listen( PORT, () => console.log( "Server started." ) );

You'll find a basic example of a GET route and a POST route in there. The POST route will return the data being sent to the server.

Now, let's add this snippet, instead of the scripts section in our package.json file and we should be good to go ✔️

  
  "scripts": {
    "start": "tsc && node ./build/Index.js"
  },
  

Great. Now you can run npm start in your terminal, and your server should be running on port 3000.

Congratulations, your first Koa server is live! 🎉

BONUS TIP: You can find the request, response, along with most things you'll need on the ctx (context) object!