Installation
Koa requires node v7.6.0 or higher for ES2015 and async function support.
You can quickly install a supported version of node with your favorite version manager:
-$ nvm install 7
+$ nvm install 7
$ npm i koa
$ node my-koa-app.js
Async Functions with Babel
To use async
functions in Koa in versions of node < 7.6, we recommend using babel's require hook.
-require('babel-core/register');
+require('babel-core/register');
// require the rest of the app that needs to be transpiled after the hook
const app = require('./app');
To parse and transpile async functions,
you should at a minimum have the transform-async-to-generator
or transform-async-to-module-method plugins.
For example, in your .babelrc
file, you should have:
-{
+{
"plugins": ["transform-async-to-generator"]
}
You can also use the env preset with a target option "node": "current"
instead.
Application
@@ -34,7 +34,7 @@ Application
no middleware are bundled.
The obligatory hello world application:
-const Koa = require('koa');
+const Koa = require('koa');
const app = new Koa();
app.use(async ctx => {
@@ -73,7 +73,7 @@ Application
middleware to execute downstream, the stack will unwind and each middleware is resumed to perform
its upstream behaviour.
-const Koa = require('koa');
+const Koa = require('koa');
const app = new Koa();
// x-response-time
@@ -133,15 +133,15 @@ app.listen(...)
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
:
-const Koa = require('koa');
+const Koa = require('koa');
const app = new Koa();
app.listen(3000);
The app.listen(...)
method is simply sugar for the following:
-const http = require('http');
+const http = require('http');
const Koa = require('koa');
const app = new Koa();
http.createServer(app.callback()).listen(3000);
This means you can spin up the same application as both HTTP and HTTPS
or on multiple addresses:
-const http = require('http');
+const http = require('http');
const https = require('https');
const Koa = require('koa');
const app = new Koa();
@@ -159,17 +159,17 @@ app.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 = ['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:
-ctx.cookies.set('name', 'tobi', { signed: true });
app.context
+ctx.cookies.set('name', 'tobi', { signed: true });
app.context
app.context
is the prototype from which ctx
is created from.
You may add additional properties to ctx
by editing app.context
.
This is useful for adding properties or methods to ctx
to be used across your entire app,
which may be more performant (no middleware) and/or easier (fewer require()
s)
at the expense of relying more on ctx
, which could be considered an anti-pattern.
For example, to add a reference to your database from ctx
:
-app.context.db = db();
+app.context.db = db();
app.use(async ctx => {
console.log(ctx.db);
@@ -182,10 +182,10 @@ Error Handling
By default outputs all errors to stderr unless app.silent
is true
.
The default error handler also won't outputs errors when err.status
is 404
or err.expose
is true
.
To perform custom error-handling logic such as centralized logging you can add an "error" event listener:
-app.on('error', err => {
+app.on('error', err => {
log.error('server error', err)
});
If an error is in the req/res cycle and it is not possible to respond to the client, the Context
instance is also passed:
-app.on('error', (err, ctx) => {
+app.on('error', (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
@@ -200,7 +200,7 @@
Error Handling
A Context
is created per request, and is referenced in middleware
as the receiver, or the ctx
identifier, as shown in the following
snippet:
-app.use(async ctx => {
+app.use(async ctx => {
ctx; // is the Context
ctx.request; // is a koa Request
ctx.response; // is a koa Response
@@ -226,7 +226,7 @@ ctx.response
A koa Response
object.
ctx.state
The recommended namespace for passing information through middleware and to your frontend views.
-ctx.state.user = await User.find(id);
ctx.app
+ctx.state.user = await User.find(id);
ctx.app
Application instance reference.
ctx.cookies.get(name, [options])
Get cookie name
with options
:
@@ -251,10 +251,10 @@ ctx.throw([status], [msg], [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:
-ctx.throw(400);
+ctx.throw(400);
ctx.throw(400, 'name required');
ctx.throw(400, 'name required', { user: user });
For example ctx.throw(400, 'name required')
is equivalent to:
-const err = new Error('name required');
+const err = new Error('name required');
err.status = 400;
err.expose = true;
throw err;
Note that these are user-level errors and are flagged with
@@ -263,12 +263,12 @@
ctx.throw([status], [msg], [properties
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.
-ctx.throw(401, 'access_denied', { user: user });
koa uses http-errors to create errors.
+ctx.throw(401, 'access_denied', { user: user });
koa uses http-errors to create errors.
ctx.assert(value, [status], [msg], [properties])
Helper method to throw an error similar to .throw()
when !value
. Similar to node's assert()
method.
-ctx.assert(ctx.state.user, 401, 'User not found. Please login!');
koa uses http-assert for assertions.
+ctx.assert(ctx.state.user, 401, 'User not found. Please login!');
koa uses http-assert for assertions.
ctx.respond
To bypass Koa's built-in response handling, you may explicitly set ctx.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.
@@ -357,10 +357,10 @@ request.originalUrl
Get request original URL.
request.origin
Get origin of URL, include protocol
and host
.
-ctx.request.origin
+ctx.request.origin
// => http://example.com
request.href
Get full request URL, include protocol
, host
and url
.
-ctx.request.href;
+ctx.request.href;
// => http://example.com/foo/bar?q=1
request.path
Get request pathname.
request.path=
@@ -386,25 +386,25 @@ request.URL
Get WHATWG parsed URL object.
request.type
Get request Content-Type
void of parameters such as "charset".
-const ct = ctx.request.type;
+const ct = ctx.request.type;
// => "image/png"
request.charset
Get request charset when present, or undefined
:
-ctx.request.charset;
+ctx.request.charset;
// => "utf-8"
request.query
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'
}
request.query=
Set query-string to the given object. Note that this
setter does not support nested objects.
-ctx.query = { next: '/login' };
request.fresh
+ctx.query = { next: '/login' };
request.fresh
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.
-// freshness check requires status 20x or 304
+// freshness check requires status 20x or 304
ctx.status = 200;
ctx.set('ETag', '123');
@@ -445,7 +445,7 @@ request.is(types...)
If there is no request body, null
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
+// With Content-Type: text/html; charset=utf-8
ctx.is('html'); // => 'html'
ctx.is('text/html'); // => 'text/html'
ctx.is('text/*', 'text/html'); // => 'text/html'
@@ -457,7 +457,7 @@ request.is(types...)
ctx.is('html'); // => false
For example if you want to ensure that
only images are sent to a given route:
-if (ctx.is('image/*')) {
+if (ctx.is('image/*')) {
// process
} else {
ctx.throw(415, 'images only!');
@@ -476,7 +476,7 @@ request.accepts(types)
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
+// Accept: text/html
ctx.accepts('html');
// => "html"
@@ -506,46 +506,46 @@ request.accepts(types)
ctx.accepts('json', 'html');
// => "json"
You may call ctx.accepts()
as many times as you like,
or use a switch:
-switch (ctx.accepts('json', 'html', 'text')) {
+switch (ctx.accepts('json', 'html', 'text')) {
case 'json': break;
case 'html': break;
case 'text': break;
default: ctx.throw(406, 'json, html, or text only');
}
request.acceptsEncodings(encodings)
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
+// Accept-Encoding: gzip
ctx.acceptsEncodings('gzip', 'deflate', 'identity');
// => "gzip"
ctx.acceptsEncodings(['gzip', 'deflate', 'identity']);
// => "gzip"
When no arguments are given all accepted encodings
are returned as an array:
-// Accept-Encoding: gzip, deflate
+// Accept-Encoding: gzip, deflate
ctx.acceptsEncodings();
// => ["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
.
request.acceptsCharsets(charsets)
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
+// Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5
ctx.acceptsCharsets('utf-8', 'utf-7');
// => "utf-8"
ctx.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
+// Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5
ctx.acceptsCharsets();
// => ["utf-8", "utf-7", "iso-8859-1"]
request.acceptsLanguages(langs)
Check if langs
are acceptable, returning
the best match when true, otherwise false
.
-// Accept-Language: en;q=0.8, es, pt
+// Accept-Language: en;q=0.8, es, pt
ctx.acceptsLanguages('es', 'en');
// => "es"
ctx.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
+// Accept-Language: en;q=0.8, es, pt
ctx.acceptsLanguages();
// => ["es", "pt", "en"]
request.idempotent
Check if the request is idempotent.
@@ -667,7 +667,7 @@ Stream
For example, you may not want this when setting the body as an HTTP stream in a proxy as it would destroy the underlying connection.
See: https://github.com/koajs/koa/pull/612 for more information.
Here's an example of stream error handling without automatically destroying the stream:
-const PassThrough = require('stream').PassThrough;
+const PassThrough = require('stream').PassThrough;
app.use(async ctx => {
ctx.body = someHTTPStream.on('error', ctx.onerror).pipe(PassThrough());
@@ -675,23 +675,23 @@ Stream
The Content-Type is defaulted to application/json. This includes plain objects { foo: 'bar' }
and arrays ['foo', 'bar']
.
response.get(field)
Get a response header field value with case-insensitive field
.
-const etag = ctx.response.get('ETag');
response.set(field, value)
+const etag = ctx.response.get('ETag');
response.set(field, value)
Set response header field
to value
:
-ctx.set('Cache-Control', 'no-cache');
response.append(field, value)
+ctx.set('Cache-Control', 'no-cache');
response.append(field, value)
Append additional header field
with value val
.
-ctx.append('Link', '<http://127.0.0.1/>');
response.set(fields)
+ctx.append('Link', '<http://127.0.0.1/>');
response.set(fields)
Set several response header fields
with an object:
-ctx.set({
+ctx.set({
'Etag': '1234',
'Last-Modified': date
});
response.remove(field)
Remove header field
.
response.type
Get response Content-Type
void of parameters such as "charset".
-const ct = ctx.type;
+const ct = ctx.type;
// => "image/png"
response.type=
Set response Content-Type
via mime string or file extension.
-ctx.type = 'text/plain; charset=utf-8';
+ctx.type = 'text/plain; charset=utf-8';
ctx.type = 'image/png';
ctx.type = '.png';
ctx.type = 'png';
Note: when appropriate a charset
is selected for you, for
@@ -704,7 +704,7 @@
response.is(types...)
manipulate responses.
For example, this is a middleware that minifies
all HTML responses except for streams.
-const minify = require('html-minifier');
+const minify = require('html-minifier');
app.use(async (ctx, next) => {
await next();
@@ -721,12 +721,12 @@ response.is(types...)
The string "back" is special-cased
to provide Referrer support, when Referrer
is not present alt
or "/" is used.
-ctx.redirect('back');
+ctx.redirect('back');
ctx.redirect('back', '/index.html');
ctx.redirect('/login');
ctx.redirect('http://google.com');
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:
-ctx.status = 301;
+ctx.status = 301;
ctx.redirect('/cart');
ctx.body = 'Redirecting to shopping cart';
response.attachment([filename])
Set Content-Disposition
to "attachment" to signal the client
@@ -740,10 +740,10 @@
response.lastModified
response.lastModified=
Set the Last-Modified
header as an appropriate UTC string.
You can either set it as a Date
or date string.
-ctx.response.lastModified = new Date();
response.etag=
+ctx.response.lastModified = new Date();
response.etag=
Set the ETag of a response including the wrapped "
s.
Note that there is no corresponding response.etag
getter.
-ctx.response.etag = crypto.createHash('md5').update(ctx.body).digest('hex');
response.vary(field)
+ctx.response.etag = crypto.createHash('md5').update(ctx.body).digest('hex');
response.vary(field)
Vary on field
.
response.flushHeaders()
Flush any set headers, and begin the body.
diff --git a/pug-options.js b/pug-options.js
index 012ff2e..a674905 100644
--- a/pug-options.js
+++ b/pug-options.js
@@ -22,7 +22,7 @@
runkitContext.activated = false;
- return "" + escaped + "
" + script;
+ return "" + escaped + "
" + script;
};
renderer.html = function(text) {