Start Building Web Apps with KoaJS and TypeScript!

Russell Briggs
Netscape
Published in
4 min readSep 9, 2017

Since the early days of NodeJS, Express has been the de-facto standard web framework for NodeJS developers. However, JavaScript has come a long way in the last few years, and features like promises and async functions have made it possible to build smaller and much more robust web frameworks.

Koa is such a framework. It has been built by the team behind Express to take advantage of the latest JavaScript and NodeJS features, specifically async functions.

Unlike Express, Koa handlers are simply async functions, and do not require you to call res.send(). This removes a huge potential source of difficult-to-trace errors and server hangs and makes the framework very easy to pick up for new developers.

In this article I’ll take you through how to get started with a new web application project using Koa and TypeScript

Getting Set Up

Koa requires a version of Node with async function support, so before starting make sure you have Node 8.x (or above) installed. Node 8 will become the new Long Term Support release in October 2017, so it is an excellent choice for starting a new project.

We’ll now create a new node project with the following installed:

  • Koa
  • Koa Router
  • TypeScript
  • TS-Node & Nodemon for auto-build & restart during development

Create a new folder for your project, then execute the following commands:

npm init   # and follow the resulting prompts to set up the project
npm i koa koa-router
npm i --save-dev typescript ts-node nodemon
npm i --save-dev @types/koa @types/koa-router

Now in the root of your project, create a new tsconfig.json file and add the following content:

{
"compilerOptions": {
"module": "commonjs",
"target": "es2017",
"noImplicitAny": true,
"outDir": "./dist",
"sourceMap": true
},
"include": [
"./src/**/*"
]
}

Note above that we configure TypeScript to transpile to ES2017 — this ensures that we take advantage of Node’s native async / await functionality.

Creating the Server

As Koa is a microframework at its core, it is very straightforward to get it up and running.

In your project directory, create a src folder, and inside it create a new file: server.ts with the following contents:

Running the server with Nodemon and TS-Node

During development, it can be a pain to remember to restart the server every time you make a change, so I like to set up my server-side projects to automatically restart on code changes.

To do this, we’ll add a watch-server npm script to our project. To do this, add the following to the “scripts” section of your package.json:

"scripts": {
"watch-server": "nodemon --watch 'src/**/*' -e ts,tsx --exec ts-node ./src/server.ts"
}

Now to start your new TypeScript Koa project, just execute the following:

npm run watch-server

You should see the below output:

Now you should be able to access http://localhost:3000/ in your browser :)

Building the Application — Adding Middleware

The main Koa library consists of just the basic HTTP functionality. To build a full web application we’ll want to add appropriate middleware, such as for Logging, Error Handling, CSRF Protection, etc.

In Koa, middleware is essentially a stack of functions, created via app.use(). When a web request is received, it is passed to the first function in the stack. That function can process the request, then optionally pass it on to the next middleware function.

Lets extend our example above to include a middleware function that logs the URL of each web request to the console:

In the example above we now define two middleware functions:

  • The first middleware function takes the Url from the request context (ctx.url) and outputs it to the console using console.log()
  • The function then does await next() which tells Koa to pass the request down to the next middleware function in the stack
  • The second middleware function comes from koa-router — it uses the url of the request to match the route we configured via router.get()

Now when you access http://localhost:3000/ in a browser you should see output similar to the following:

Standard Middleware

Obviously, you don’t really want to be reinventing the wheel for your web apps. Depending on the types of app you want to create, the following middleware could be useful:

Starter Project

I have created a basic TypeScript & Koa project, which is available here for those interested :)

--

--

Russell Briggs
Netscape

CTO at Junari Ltd, the leading provider of customised management software for business — junari.com