Async/Await with Koa

At the time of this writing (July 2017), KoaJS and most of its popular middleware support ES6 async/await. NodeJS had been supporting them for some time as well. Here we will see a minimal example of koa and koa-router packages using async/await.

Install the packages:

npm i koa koa-router --save

Create a JS file as follows.

var Koa = require('koa');
var router = require('koa-router');

var app = new Koa()
var api = router();

api.get('/hello', async (ctx) => {
    ctx.response.body = await f1()
});

app
  .use(api.routes())
  .use(api.allowedMethods());

app.listen(8080);

async function f1() {
    return new Promise((resolve, reject) => {
        let message = {
            greeting: "Hello",
            planet: "World"
        }

        resolve(message)
    })
}

This shows how to use an async method for routing.

Save and run the file.

Then, run curl to test it out.

curl -v localhost:8080/hello

Verify that the response content type is application/json; charset=utf-8 and the body is:

{"greeting":"Hello","planet":"World"}
Advertisements

Use JSON Web Token with Koa

JSON Web Token (JWT) is used to issue a secure authentication token once the user successfully logs in. In Koa we use the koa-jwt middleware to manage these tokens.

npm install koa-jwt --save

Import the package from your code.

var jwt = require('koa-jwt');

We can use the middleware to guard access to protected URLs. The following will try to decrypt the token sent with the request using the secret key 'pa$$word'. If that does not succeed the processing pipeline will be terminated and the subsequent middlewares will not run. We use the unless escape hatch so that this token validation is skipped for paths starting with "/public".

app.use(jwt({ secret: 'pa$$word' })
    .unless({ path: [/^\/public/] }));

Add the jwt middleware before any routes for it to have any meaningful effect.

A new token is issued using jwt.sign(). You can store identifying information like user ID, name etc. as a payload in the token.

api.get('/public/login', function *(){
    var user = {
      userId: "bibhas",
      name: "Bibhas B"
    }

    this.body = {
      token: jwt.sign(user, "pa$$word")
    }
});

A client is responsible for saving the token and sending it back with every request using the Authorization header. In the example below ABCXYZ is a token issued by the server:

curl -H "Authorization: Bearer ABCXYZ" localhost:8080/protected-stuff

The middleware saves the payload decrypted from the token as the state.user property of the context. So we can easily access that as follows:

api.get('/protected-stuff', function *(){
    var userId = this.state.user.userId //"bibhas"
    var fullName = this.state.user.name //"Bibhas B"
});

Use Angular 2 from an ExpressJS Application

Most Angular 2 starter projects use a development time web server. This will not work well if you are developing the application using Node and Express. An Angular 2 project works best when it is the document root of a web server. This requires a bit of careful planning.

In today’s post I will explore how to create a Express application that uses Angular 2. We will explore two separate approaches:

  • A single project hosting both Node and Angular 2 code.
  • Separate projects for Node and Angular 2 code.

We will use generators and official starter projects whenever possible. This will help you follow along this article and experiment quickly.

Continue reading