Koa 0.5.0

TJ Holowaychuk
2 min readFeb 20, 2014

We’ve had three minor releases since the last blog post so let’s see what has changed!

Formatted JSON responses

In 0.4.0 we removed the app.jsonSpaces setting — a setting used to specify the formatting of a JSON response. The default values were to pretty-print in development, and compress JSON in other environments. The main issue here is that this can cause unexpected results when running tests in other environments unless the user is aware of this behaviour, so we’ve removed it!

The behaviour is now to always respond with compressed JSON. If you want pretty-printed JSON you may use the koajs/json middleware, which also allows you to optionally specify a query-string parameter such as ?pretty to allow users to opt-in.

Dynamic middleware names

Koa and associated tooling such as the koa-compose module use the JavaScript function .name property for debug output, and while this works great there are issues when middleware are dynamically generated — since JavaScript does not allow re-defining this property.

For this reason we’ve added support for ._name as well. This is a tiny feature but one that you may never know without reading this ☺. A good example use-case is routers which accept handler functions.

Instead of writing something like the following to provide a name, one may be generated dynamically.

app.get(‘/users’, function *getUsers(){
this.body = users;
})

Now the router could assign fn._name to something like “GET /users” — you no longer have to gouge your eyes out!

app.get(‘/users’, function *(){
this.body = users;
})

Less confusing accessors

One of our first breaking changes so far changes how delegation of a few Context properties. Previous to 0.5.x the ctx.length and ctx.type getters delegated to the Request object, while both ctx.length= and ctx.type= setters delegated to the response.

At the time this made sense to me, because the most common use-case was to interpret the request, and act on the response, however one of the users pointed out that this was confusing in cases where you wanted to act on the response in upstream middleware. Because of this ctx.length and ctx.type getters now delegate to the response.

The general rule of thumb will now be that if it there’s an getter or setter of the same name, that they will act on the same object. If you favour verbosity over slight ambiguity you may of course always just reference ctx.response.type and so on directly.

General changes

  • improve response.body= html sniffing
  • ctx.throw() accepts Error instances now
  • add ctx.host= delegate
  • add req.host=
  • add req.charset
  • add res.charset and ctx.charset delegate
  • add res.charset= and ctx.charset= delegate

FIN

Overall a pretty bland set of releases, but that’s not such a bad thing! Just means we’re still on track with stabilizing the API. If you’ve been using Koa for projects and have any feedback let us know!

--

--