next generation web framework for node.js


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. Through leveraging generators Koa allows you to ditch callbacks and greatly increase error-handling. Koa does not bundle any middleware within core, and provides an elegant suite of methods that make writing servers fast and enjoyable.


Koa currently requires node 0.11.x for the --harmony flag which exposes generators to your script. If you're running an earlier version of node you may install n, a node version manager to quickly install 0.11.x:

$ npm install -g n
$ n 0.11
$ node --harmony my-koa-app.js


A Koa application is an object containing an array of middleware generator functions which are composed and executed in a stack-like manner upon request. Koa is similar to many other middleware systems that you may have encountered such as Ruby's Rack, Connect, and so on - however a key design decision was made to provide high level "sugar" at the otherwise low-level middleware layer. This improves interoperability, robustness, and makes writing middleware much more enjoyable.

This includes methods for common tasks like content-negotiation, cache freshness, proxy support, and redirection among others. Despite supplying a reasonably large number of helpful methods Koa maintains a small footprint, as no middleware are bundled.

The obligatory hello world application:

var koa = require('koa');
var app = koa();

app.use(function *(){
  this.body = 'Hello World';



Koa middleware cascade in a more traditional way as you may be used to with similar tools - this was previously difficult to make user friendly with node's use of callbacks. However with generators we can achieve "true" middleware. Contrasting Connect's implementation which simply passes control through series of functions until one returns, Koa yields "downstream", then control flows back "upstream".

The following example responds with "Hello World", however first the request flows through the x-response-time and logging middleware to mark when the request started, then continue to yield control through the response middleware. When a middleware invokes yield next the function suspends and passes control to the next middleware defined. After there are no more middleware to execute downstream, the stack will unwind and each middleware is resumed to perform its upstream behaviour.

var koa = require('koa');
var app = koa();

// x-response-time

app.use(function *(next){
  var start = new Date;
  yield next;
  var ms = new Date - start;
  this.set('X-Response-Time', ms + 'ms');

// logger

app.use(function *(next){
  var start = new Date;
  yield next;
  var ms = new Date - start;
  console.log('%s %s - %s', this.method, this.url, ms);

// response

app.use(function *(){
  this.body = 'Hello World';



Application settings are properties on the app instance, currently the following are supported:


A Koa application is not a 1-to-1 representation of a HTTP server. One or more Koa applications may be mounted together to form larger applications with a single HTTP server.

Create and return an HTTP server, passing the given arguments to Server#listen(). These arguments are documented on nodejs.org. The following is a useless Koa application bound to port 3000:

var koa = require('koa');
var app = koa();

The app.listen(...) method is simply sugar for the following:

var http = require('http');
var koa = require('koa');
var app = koa();

This means you can spin up the same application as both HTTP and HTTPS or on multiple addresses:

var http = require('http');
var koa = require('koa');
var app = koa();


Return a callback function suitable for the http.createServer() method to handle a request. You may also use this callback function to mount your koa app in a Connect/Express app.


Add the given middleware function to this application. See Middleware for more information.


Set signed cookie keys.

These are passed to KeyGrip, however you may also pass your own KeyGrip instance. For example the following are acceptable:

app.keys = ['im a newer secret', 'i like turtle'];
app.keys = new KeyGrip(['im a newer secret', 'i like turtle'], 'sha256');

These keys may be rotated and are used when signing cookies with the { signed: true } option:

this.cookies.set('name', 'tobi', { signed: true });

Error Handling

By default outputs all errors to stderr unless NODE_ENV is "test". To perform custom error-handling logic such as centralized logging you can add an "error" event listener:

app.on('error', function(err){
  log.error('server error', err);

If an error in the req/res cycle and it is not possible to respond to the client, the Context instance is also passed:

app.on('error', function(err, ctx){
  log.error('server error', err, ctx);

When an error occurs and it is still possible to respond to the client, aka no data has been written to the socket, Koa will respond appropriately with a 500 "Internal Server Error". In either case an app-level "error" is emitted for logging purposes.


A Koa Context encapsulates node's request and response objects into a single object which provides many helpful methods for writing web applications and APIs. These operations are used so frequently in HTTP server development that they are added at this level instead of a higher level framework, which would force middleware to re-implement this common functionality.

A Context is created per request, and is referenced in middleware as the receiver, or the this identifier, as shown in the following snippet:

app.use(function *(){
  this; // is the Context
  this.request; // is a koa Request
  this.response; // is a koa Response

Many of the context's accessors and methods simply delegate to their ctx.request or ctx.response equivalents for convenience, and are otherwise identical. For example ctx.type and ctx.length delegate to the response object, and ctx.path and ctx.method delegate to the request.


Context specific methods and accessors.


Node's request object.


Node's response object.

Bypassing Koa's response handling is not supported. Avoid using the following node properties:


A koa Request object.


A koa Response object.


The recommended namespace for passing information through middleware and to your frontend views.

this.state.user = yield User.find(id);


Application instance reference.

ctx.cookies.get(name, [options])

Get cookie name with options:

koa uses the cookies module where options are simply passed.

ctx.cookies.set(name, value, [options])

Set cookie name to value with options:

koa uses the cookies module where options are simply passed.

ctx.throw([msg], [status], [properties])

Helper method to throw an error with a .status property defaulting to 500 that will allow Koa to respond appropriately. The following combinations are allowed:

this.throw('name required', 400);
this.throw(400, 'name required');
this.throw('something exploded');

For example this.throw('name required', 400) is equivalent to:

var err = new Error('name required');
err.status = 400;
throw err;

Note that these are user-level errors and are flagged with err.expose meaning the messages are appropriate for client responses, which is typically not the case for error messages since you do not want to leak failure details.

You may optionally pass a properties object which is merged into the error as-is, useful for decorating machine-friendly errors which are reported to the requester upstream.

this.throw(401, 'access_denied', { user: user });
this.throw('access_denied', { user: user });

koa uses http-errors to create errors.

ctx.assert(value, [msg], [status], [properties])

Helper method to throw an error similar to .throw() when !value. Similar to node's assert() method.

this.assert(this.user, 401, 'User not found. Please login!');

koa uses http-assert for assertions.


To bypass Koa's built-in response handling, you may explicitly set this.respond = false;. Use this if you want to write to the raw res object instead of letting Koa handle the response for you.

Note that using this is not supported by Koa. This may break intended functionality of Koa middleware and Koa itself. Using this property is considered a hack and is only a convenience to those wishing to use traditional fn(req, res) functions and middleware within Koa.

Request aliases

The following accessors and alias Request equivalents:

Response aliases

The following accessors and alias Response equivalents:


A Koa Request object is an abstraction on top of node's vanilla request object, providing additional functionality that is useful for every day HTTP server development.



Request header object.


Request header object. Alias as request.header.


Request method.


Set request method, useful for implementing middleware such as methodOverride().


Return request Content-Length as a number when present, or undefined.


Get request URL.


Set request URL, useful for url rewrites.


Get request original URL.


Get full request URL, include protocol, host and url.

// => http://example.com/foo/bar?q=1


Get request pathname.


Set request pathname and retain query-string when present.


Get raw query string void of ?.


Set raw query string.

Get raw query string with the ?.


Set raw query string.


Get host (hostname:port) when present. Supports X-Forwarded-Host when app.proxy is true, otherwise Host is used.


Get hostname when present. Supports X-Forwarded-Host when app.proxy is true, otherwise Host is used.


Get request Content-Type void of parameters such as "charset".

var ct = this.request.type;
// => "image/png"


Get request charset when present, or undefined:

// => "utf-8"


Get parsed query-string, returning an empty object when no query-string is present. Note that this getter does not support nested parsing.

For example "color=blue&size=small":

  color: 'blue',
  size: 'small'


Set query-string to the given object. Note that this setter does not support nested objects.

this.query = { next: '/login' };


Check if a request cache is "fresh", aka the contents have not changed. This method is for cache negotiation between If-None-Match / ETag, and If-Modified-Since and Last-Modified. It should be referenced after setting one or more of these response headers.

this.set('ETag', '123');

// cache is ok
if (this.fresh) {
  this.status = 304;

// cache is stale
// fetch new data
this.body = yield db.find('something');


Inverse of request.fresh.


Return request protocol, "https" or "http". Supports X-Forwarded-Proto when app.proxy is true.


Shorthand for this.protocol == "https" to check if a request was issued via TLS.


Request remote address. Supports X-Forwarded-For when app.proxy is true.


When X-Forwarded-For is present and app.proxy is enabled an array of these ips is returned, ordered from upstream -> downstream. When disabled an empty array is returned.


Return subdomains as an array.

Subdomains are the dot-separated parts of the host before the main domain of the app. By default, the domain of the app is assumed to be the last two parts of the host. This can be changed by setting app.subdomainOffset.

For example, if the domain is "tobi.ferrets.example.com": If app.subdomainOffset is not set, this.subdomains is ["ferrets", "tobi"]. If app.subdomainOffset is 3, this.subdomains is ["tobi"].


Check if the incoming request contains the "Content-Type" header field, and it contains any of the give mime types. If there is no request body, undefined is returned. If there is no content type, or the match fails false is returned. Otherwise, it returns the matching content-type.

// With Content-Type: text/html; charset=utf-8
this.is('html'); // => 'html'
this.is('text/html'); // => 'text/html'
this.is('text/*', 'text/html'); // => 'text/html'

// When Content-Type is application/json
this.is('json', 'urlencoded'); // => 'json'
this.is('application/json'); // => 'application/json'
this.is('html', 'application/*'); // => 'application/json'

this.is('html'); // => false

For example if you want to ensure that only images are sent to a given route:

if (this.is('image/*')) {
  // process
} else {
  this.throw(415, 'images only!');

Content Negotiation

Koa's request object includes helpful content negotiation utilities powered by accepts and negotiator. These utilities are:

If no types are supplied, all acceptable types are returned.

If multiple types are supplied, the best match will be returned. If no matches are found, a false is returned, and you should send a 406 "Not Acceptable" response to the client.

In the case of missing accept headers where any type is acceptable, the first type will be returned. Thus, the order of types you supply is important.


Check if the given type(s) is acceptable, returning the best match when true, otherwise false. The type value may be one or more mime type string such as "application/json", the extension name such as "json", or an array ["json", "html", "text/plain"].

// Accept: text/html
// => "html"

// Accept: text/*, application/json
// => "html"
// => "text/html"
this.accepts('json', 'text');
// => "json"
// => "application/json"

// Accept: text/*, application/json
// => false

// Accept: text/*;q=.5, application/json
this.accepts(['html', 'json']);
this.accepts('html', 'json');
// => "json"

// No Accept header
this.accepts('html', 'json');
// => "html"
this.accepts('json', 'html');
// => "json"

You may call this.accepts() as many times as you like, or use a switch:

switch (this.accepts('json', 'html', 'text')) {
  case 'json': break;
  case 'html': break;
  case 'text': break;
  default: this.throw(406, 'json, html, or text only');


Check if encodings are acceptable, returning the best match when true, otherwise false. Note that you should include identity as one of the encodings!

// Accept-Encoding: gzip
this.acceptsEncodings('gzip', 'deflate', 'identity');
// => "gzip"

this.acceptsEncodings(['gzip', 'deflate', 'identity']);
// => "gzip"

When no arguments are given all accepted encodings are returned as an array:

// Accept-Encoding: gzip, deflate
// => ["gzip", "deflate", "identity"]

Note that the identity encoding (which means no encoding) could be unacceptable if the client explicitly sends identity;q=0. Although this is an edge case, you should still handle the case where this method returns false.


Check if charsets are acceptable, returning the best match when true, otherwise false.

// Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5
this.acceptsCharsets('utf-8', 'utf-7');
// => "utf-8"

this.acceptsCharsets(['utf-7', 'utf-8']);
// => "utf-8"

When no arguments are given all accepted charsets are returned as an array:

// Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5
// => ["utf-8", "utf-7", "iso-8859-1"]


Check if langs are acceptable, returning the best match when true, otherwise false.

// Accept-Language: en;q=0.8, es, pt
this.acceptsLanguages('es', 'en');
// => "es"

this.acceptsLanguages(['en', 'es']);
// => "es"

When no arguments are given all accepted languages are returned as an array:

// Accept-Language: en;q=0.8, es, pt
// => ["es", "pt", "en"]


Check if the request is idempotent.


Return the request socket.


Return request header.


A Koa Response object is an abstraction on top of node's vanilla response object, providing additional functionality that is useful for every day HTTP server development.



Response header object.


Request socket.


Get response status. By default, response.status is not set unlike node's res.statusCode which defaults to 200.


Set response status via numeric code:

NOTE: don't worry too much about memorizing these strings, if you have a typo an error will be thrown, displaying this list so you can make a correction.


Get response status message. By default, response.message is associated with response.status.


Set response status message to the given value.


Set response Content-Length to the given value.


Return response Content-Length as a number when present, or deduce from this.body when possible, or undefined.


Get response body.


Set response body to one of the following:

If response.status has not been set, Koa will automatically set the status to 200 or 204.


The Content-Type is defaulted to text/html or text/plain, both with a default charset of utf-8. The Content-Length field is also set.


The Content-Type is defaulted to application/octet-stream, and Content-Length is also set.


The Content-Type is defaulted to application/octet-stream.


The Content-Type is defaulted to application/json.


Get a response header field value with case-insensitive field.

var etag = this.get('ETag');

response.set(field, value)

Set response header field to value:

this.set('Cache-Control', 'no-cache');


Set several response header fields with an object:

  'Etag': '1234',
  'Last-Modified': date


Remove header field.


Get response Content-Type void of parameters such as "charset".

var ct = this.type;
// => "image/png"


Set response Content-Type via mime string or file extension.

this.type = 'text/plain; charset=utf-8';
this.type = 'image/png';
this.type = '.png';
this.type = 'png';

Note: when appropriate a charset is selected for you, for example response.type = 'html' will default to "utf-8", however when explicitly defined in full as response.type = 'text/html' no charset is assigned.


Very similar to this.request.is(). Check whether the response type is one of the supplied types. This is particularly useful for creating middleware that manipulate responses.

For example, this is a middleware that minifies all HTML responses except for streams.

var minify = require('html-minifier');

app.use(function *minifyHTML(next){
  yield next;

  if (!this.response.is('html')) return;

  var body = this.body;
  if (!body || body.pipe) return;

  if (Buffer.isBuffer(body)) body = body.toString();
  this.body = minify(body);

response.redirect(url, [alt])

Perform a [302] redirect to url.

The string "back" is special-cased to provide Referrer support, when Referrer is not present alt or "/" is used.

this.redirect('back', '/index.html');

To alter the default status of 302, simply assign the status before or after this call. To alter the body, assign it after this call:

this.status = 301;
this.body = 'Redirecting to shopping cart';


Set Content-Disposition to "attachment" to signal the client to prompt for download. Optionally specify the filename of the download.


Check if a response header has already been sent. Useful for seeing if the client may be notified on error.


Return the Last-Modified header as a Date, if it exists.


Set the Last-Modified header as an appropriate UTC string. You can either set it as a Date or date string.

this.response.lastModified = new Date();


Set the ETag of a response including the wrapped "s. Note that there is no corresponding response.etag getter.

this.response.etag = crypto.createHash('md5').update(this.body).digest('hex');


Vary on field.


Community links to discover third-party middleware for Koa, full runnable examples, thorough guides and more! If you have questions join us in IRC!