File: Readme.md
Expressive HTTP middleware framework for node.js to make web applications and APIs more enjoyable to write. Koa's middleware stack flows in a stack-like manner, allowing you to perform actions downstream then filter and manipulate the response upstream.
Only methods that are common to nearly all HTTP servers are integrated directly into Koa's small ~570 SLOC codebase. This
includes things like content negotiation, normalization of node inconsistencies, redirection, and a few others.
Koa is not bundled with any middleware.
Installation
Koa requires node v18.0.0 or higher for ES2015 and async function support.
npm install koaHello Koa
const Koa = require('koa');
const app = new Koa();
// response
app.use(ctx => {
ctx.body = 'Hello Koa';
});
app.listen(3000);Getting started
- Kick-Off-Koa - An intro to Koa via a set of self-guided workshops.
- Guide - Go straight to the docs.
Middleware
Koa is a middleware framework that can take two different kinds of functions as middleware:
- async function
- common function
Here is an example of logger middleware with each of the different functions:
___async___ functions (node v7.6+)
app.use(async (ctx, next) => {
const start = Date.now();
await next();
const ms = Date.now() - start;
console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
});Common function
// Middleware normally takes two parameters (ctx, next), ctx is the context for one request,
// next is a function that is invoked to execute the downstream middleware. It returns a Promise with a then function for running code after completion.
app.use((ctx, next) => {
const start = Date.now();
return next().then(() => {
const ms = Date.now() - start;
console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
});
});Koa v1.x Middleware Signature
The middleware signature changed between v1.x and v2.x. The older signature is deprecated.
Old signature middleware support has been removed in v3
Please see the Migration Guide from v2.x to v3.x for information on upgrading from v2.x to v3.x, and the Migration Guide from v1.x to v2.x for information on upgrading from v1.x to v2.x.
Context, Request and Response
Each middleware receives a Koa Context object that encapsulates an incoming
http message and the corresponding response to that message. ctx is often used
as the parameter name for the context object.
app.use(async (ctx, next) => { await next(); });Koa provides a Request object as the request property of the Context.
Koa's Request object provides helpful methods for working with
http requests which delegate to an IncomingMessage
from the node http module.
Here is an example of checking that a requesting client supports xml.
app.use(async (ctx, next) => {
ctx.assert(ctx.request.accepts('xml'), 406);
// equivalent to:
// if (!ctx.request.accepts('xml')) ctx.throw(406);
await next();
});Koa provides a Response object as the response property of the Context.
Koa's Response object provides helpful methods for working with
http responses which delegate to a ServerResponse
.
Koa's pattern of delegating to Node's request and response objects rather than extending them
provides a cleaner interface and reduces conflicts between different middleware and with Node
itself as well as providing better support for stream handling. The IncomingMessage can still be
directly accessed as the req property on the Context and ServerResponse can be directly
accessed as the res property on the Context.
Here is an example using Koa's Response object to stream a file as the response body.
app.use(async (ctx, next) => {
await next();
ctx.response.type = 'xml';
ctx.response.body = fs.createReadStream('really_large.xml');
});The Context object also provides shortcuts for methods on its request and response. In the prior
examples, ctx.type can be used instead of ctx.response.type and ctx.accepts can be used
instead of ctx.request.accepts.
For more information on Request, Response and Context, see the Request API Reference,
Response API Reference and Context API Reference.
Koa Application
The object created when executing new Koa() is known as the Koa application object.
The application object is Koa's interface with node's http server and handles the registration
of middleware, dispatching to the middleware from http, default error handling, as well as
configuration of the context, request and response objects.
Learn more about the application object in the Application API Reference.
Documentation
Troubleshooting
Check the Troubleshooting Guide or Debugging Koa in
the general Koa guide.
Running tests
$ npm testReporting vulnerabilities
To report a security vulnerability, please do not open an issue, as this notifies attackers of the vulnerability. Instead, please email dead_horse, jonathanong, and niftylettuce to disclose.
Authors
See AUTHORS.
Community
- KoaJS Slack Group
- Badgeboard and list of official modules
- Examples
- Middleware list
- Wiki
- Reddit Community
- Mailing list
- ไธญๆๆๆกฃ v1.x
- ไธญๆๆๆกฃ v2.x
- #koajs on freenode
Backers
Support us with a monthly donation and help us continue our activities.
Sponsors
Become a sponsor and get your logo on our README on Github with a link to your site.
License
File: docs/api/context.md
Context
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 ctx identifier, as shown in the following
snippet:
app.use(async ctx => {
ctx; // is the Context
ctx.request; // is a Koa Request
ctx.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.
API
Context specific methods and accessors.
ctx.req
Node's request object.
ctx.res
Node's response object.
Bypassing Koa's response handling is not supported. Avoid using the following Node properties:
res.statusCoderes.writeHead()res.write()res.end()
ctx.request
A Koa Request object.
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
Application instance reference.
ctx.app.emit
Koa applications extend an internal EventEmitter. ctx.app.emit emits an event with a type, defined by the first argument. For each event you can hook up "listeners", which is a function that is called when the event is emitted. Consult the error handling docs for more information.
ctx.cookies.get(name, [options])
Get cookie name with options:
signedthe cookie requested should be signed
Koa uses the cookies module where options are simply passed.
ctx.cookies.set(name, value, [options])
Set cookie name to value with options:
maxAge: a number representing the milliseconds fromDate.now()for expiry.expires: aDateobject indicating the cookie's expiration date (expires at the end of session by default).path: a string indicating the path of the cookie (/by default).domain: a string indicating the domain of the cookie (no default).secure: a boolean indicating whether the cookie is only to be sent over HTTPS (falseby default for HTTP,trueby default for HTTPS). Read more about this option.httpOnly: a boolean indicating whether the cookie is only to be sent over HTTP(S), and not made available to client JavaScript (trueby default).partitioned: a boolean indicating whether to partition the cookie in Chrome for the CHIPS Update (falseby default). If this is true, Cookies from embedded sites will be partitioned and only readable from the same top level site from which it was created.priority: a string indicating the cookie priority. This can be set to'low','medium', or'high'.sameSite: a boolean or string indicating whether the cookie is a "same site" cookie (falseby default). This can be set to'strict','lax','none', ortrue(which maps to'strict').signed: a boolean indicating whether the cookie is to be signed (falseby default). If this is true, another cookie of the same name with the.sigsuffix appended will also be sent, with a 27-byte url-safe base64 SHA1 value representing the hash of cookie-name=cookie-value against the first Keygrip key. This signature key is used to detect tampering the next time a cookie is received.overwrite: a boolean indicating whether to overwrite previously set cookies of the same name (falseby default). If this is true, all cookies set during the same request with the same name (regardless of path or domain) are filtered out of the Set-Cookie header when setting this cookie.
Koa uses the cookies module where options are simply passed.
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, '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');
err.status = 400;
err.expose = true;
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.
ctx.throw(401, 'access_denied', { user: user });Koa uses http-errors to create errors. status should only be passed as the first parameter.
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.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.
Request aliases
The following accessors and alias Request equivalents:
ctx.headerctx.headersctx.methodctx.method=ctx.urlctx.url=ctx.originalUrlctx.originctx.hrefctx.pathctx.path=ctx.queryctx.query=ctx.querystringctx.querystring=ctx.hostctx.hostnamectx.freshctx.stalectx.socketctx.protocolctx.securectx.ipctx.ipsctx.subdomainsctx.is()ctx.accepts()ctx.acceptsEncodings()ctx.acceptsCharsets()ctx.acceptsLanguages()ctx.get()
Response aliases
The following accessors and alias Response equivalents:
ctx.bodyctx.body=ctx.has()ctx.statusctx.status=ctx.messagectx.message=ctx.length=ctx.lengthctx.type=ctx.typectx.vary()ctx.headerSentctx.redirect()ctx.attachment()ctx.set()ctx.append()ctx.remove()ctx.lastModified=ctx.etag=ctx.writable
File: docs/api/index.md
Installation
Koa requires node v18.0.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 22
$ npm i koa
$ node my-koa-app.jsApplication
A Koa application is an object containing an array of middleware 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:
const Koa = require('koa');
const app = new Koa();
app.use(async ctx => {
ctx.body = 'Hello World';
});
app.listen(3000);Cascading
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 async functions we can achieve "true" middleware. Contrasting Connect's implementation which
simply passes control through series of functions until one returns, Koa invoke "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 yields control through the response middleware. When a middleware invokes 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.
const Koa = require('koa');
const app = new Koa();
// logger
app.use(async (ctx, next) => {
await next();
const rt = ctx.response.get('X-Response-Time');
console.log(`${ctx.method} ${ctx.url} - ${rt}`);
});
// x-response-time
app.use(async (ctx, next) => {
const start = Date.now();
await next();
const ms = Date.now() - start;
ctx.set('X-Response-Time', `${ms}ms`);
});
// response
app.use(async ctx => {
ctx.body = 'Hello World';
});
app.listen(3000);Settings
Application settings are properties on the app instance, currently
the following are supported:
app.envdefaulting to the NODE_ENV or "development"app.keysarray of signed cookie keysapp.proxywhen true proxy header fields will be trustedapp.subdomainOffsetoffset of.subdomainsto ignore, defaults to 2app.proxyIpHeaderproxy ip header, defaults toX-Forwarded-Forapp.maxIpsCountmax ips read from proxy ip header, defaults to 0 (means infinity)app.compose- function to handle middleware compositionapp.asyncLocalStoragepasstrueor an instance ofAsyncLocalStorageto enable async local storage. See below for details.
You can pass the settings to the constructor:
const Koa = require('koa');
const app = new Koa({ proxy: true });or dynamically:
const Koa = require('koa');
const app = new Koa();
app.proxy = true;app.listen(...)
A Koa application is not a 1-to-1 representation of an 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:
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 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 https = require('https');
const Koa = require('koa');
const app = new Koa();
http.createServer(app.callback()).listen(3000);
https.createServer(app.callback()).listen(3001);app.callback()
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.
app.use(function)
Add the given middleware function to this application.
app.use() returns this, so is chainable.
app.use(someMiddleware)
app.use(someOtherMiddleware)
app.listen(3000)Is the same as
app.use(someMiddleware)
.use(someOtherMiddleware)
.listen(3000) See Middleware for
more information.
app.keys=
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 = ['OEK5zjaAMPc3L6iK7PyUjCOziUH3rsrMKB9u8H07La1SkfwtuBoDnHaaPCkG5Brg', 'MNKeIebviQnCPo38ufHcSfw3FFv8EtnAe1xE02xkN1wkCV1B2z126U44yk2BQVK7'];
app.keys = new KeyGrip(['OEK5zjaAMPc3L6iK7PyUjCOziUH3rsrMKB9u8H07La1SkfwtuBoDnHaaPCkG5Brg', 'MNKeIebviQnCPo38ufHcSfw3FFv8EtnAe1xE02xkN1wkCV1B2z126U44yk2BQVK7'], 'sha256');For security reasons, please ensure that the key is long enough and random.
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
app.context is the prototype from which ctx is created.
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.use(async ctx => {
console.log(ctx.db);
});Note:
- Many properties on
ctxare defined using getters, setters, andObject.defineProperty(). You can only edit these properties (not recommended) by usingObject.defineProperty()onapp.context. See https://github.com/koajs/koa/issues/652. - Mounted apps currently use their parent's
ctxand settings. Thus, mounted apps are really just groups of middleware.
app.currentContext
New in Koa v3.
If asyncLocalStorage is enabled, this will return the current context for the request. For example:
const app = new Koa({ asyncLocalStorage: true })
app.use(async (ctx, next) => {
callSomeFunction()
})
function callSomeFunction () {
const ctx = app.currentContext /* ctx of the middleware above */
}Starting in v3.1.0, you can also pass your own AsyncLocalStorage instance:
const asyncLocalStorage = new AsyncLocalStorage()
const app = new Koa({ asyncLocalStorage })
app.use(async (ctx, next) => {
callSomeFunction()
})
function callSomeFunction () {
const ctx = asyncLocalStorage.getStore()
}Use this to pass key request details like request ID or the user to your internal services.
Error Handling
By default outputs all errors to stderr unless app.silent is true.
The default error handler also won't output 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 => {
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) => {
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.
File: docs/api/request.md
Request
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.
API
request.header
Request header object. This is the same as the headers field
on Node's http.IncomingMessage.
request.header=
Set request header object.
request.headers
Request header object. Alias as request.header.
request.headers=
Set request header object. Alias as request.header=.
request.method
Request method.
request.method=
Set request method, useful for implementing middleware
such as methodOverride().
request.length
Return request Content-Length as a number when present, or undefined.
request.url
Get request URL.
request.url=
Set request URL, useful for url rewrites.
request.originalUrl
Get request original URL.
request.origin
Get origin of URL, include protocol and host.
ctx.request.origin
// => http://example.comrequest.href
Get full request URL, include protocol, host and url.
ctx.request.href;
// => http://example.com/foo/bar?q=1request.path
Get request pathname.
request.path=
Set request pathname and retain query-string when present.
request.querystring
Get raw query string void of ?.
request.querystring=
Set raw query string.
request.search
Get raw query string with the ?.
request.search=
Set raw query string.
request.host
Get host (hostname:port) when present. Supports X-Forwarded-Host
when app.proxy is true, otherwise Host is used.
request.hostname
Get hostname when present. Supports X-Forwarded-Host
when app.proxy is true, otherwise Host is used.
If host is IPv6, Koa delegates parsing to
WHATWG URL API,
Note This may impact performance.
request.URL
Get WHATWG parsed URL object.
request.type
Get request Content-Type void of parameters such as "charset".
const ct = ctx.request.type;
// => "image/png"request.charset
Get request charset when present, or undefined:
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
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
ctx.status = 200;
ctx.set('ETag', '123');
// cache is ok
if (ctx.fresh) {
ctx.status = 304;
return;
}
// cache is stale
// fetch new data
ctx.body = await db.find('something');request.stale
Inverse of request.fresh.
request.protocol
Return request protocol, "https" or "http". Supports X-Forwarded-Proto
when app.proxy is true.
request.secure
Shorthand for ctx.protocol == "https" to check if a request was
issued via TLS.
request.ip
Request remote address. Supports X-Forwarded-For when app.proxy
is true.
request.ips
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.
For example if the value were "client, proxy1, proxy2",
you would receive the array ["client", "proxy1", "proxy2"].
Most of the reverse proxy(nginx) set x-forwarded-for via
proxy_add_x_forwarded_for, which poses a certain security risk.
A malicious attacker can forge a client's ip address by forging
a X-Forwarded-Forrequest header. The request sent by the client
has an X-Forwarded-For request header for 'forged'. After being
forwarded by the reverse proxy, request.ips will be
['forged', 'client', 'proxy1', 'proxy2'].
Koa offers two options to avoid being bypassed.
If you can control the reverse proxy, you can avoid bypassing
by adjusting the configuration, or use the app.proxyIpHeader
provided by koa to avoid reading x-forwarded-for to get ips.
const app = new Koa({
proxy: true,
proxyIpHeader: 'X-Real-IP',
}); If you know exactly how many reverse proxies are in front of
the server, you can avoid reading the user's forged request
header by configuring app.maxIpsCount:
const app = new Koa({
proxy: true,
maxIpsCount: 1, // only one proxy in front of the server
});
// request.header['X-Forwarded-For'] === [ '127.0.0.1', '127.0.0.2' ];
// ctx.ips === [ '127.0.0.2' ];request.subdomains
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, ctx.subdomains is ["ferrets", "tobi"].
If app.subdomainOffset is 3, ctx.subdomains is ["tobi"].
request.is(types...)
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, 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
ctx.is('html'); // => 'html'
ctx.is('text/html'); // => 'text/html'
ctx.is('text/*', 'text/html'); // => 'text/html'
// When Content-Type is application/json
ctx.is('json', 'urlencoded'); // => 'json'
ctx.is('application/json'); // => 'application/json'
ctx.is('html', 'application/*'); // => 'application/json'
ctx.is('html'); // => false For example if you want to ensure that
only images are sent to a given route:
if (ctx.is('image/*')) {
// process
} else {
ctx.throw(415, 'images only!');
}Content Negotiation
Koa's request object includes helpful content negotiation utilities powered by accepts and negotiator. These utilities are:
request.accepts(types)request.acceptsEncodings(types)request.acceptsCharsets(charsets)request.acceptsLanguages(langs)
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.
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
ctx.accepts('html');
// => "html"
// Accept: text/*, application/json
ctx.accepts('html');
// => "html"
ctx.accepts('text/html');
// => "text/html"
ctx.accepts('json', 'text');
// => "json"
ctx.accepts('application/json');
// => "application/json"
// Accept: text/*, application/json
ctx.accepts('image/png');
ctx.accepts('png');
// => false
// Accept: text/*;q=.5, application/json
ctx.accepts(['html', 'json']);
ctx.accepts('html', 'json');
// => "json"
// No Accept header
ctx.accepts('html', 'json');
// => "html"
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')) {
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
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
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
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
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
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
ctx.acceptsLanguages();
// => ["es", "pt", "en"]request.idempotent
Check if the request is idempotent (e.g. a GET, HEAD, etc. request).
request.socket
Return the request socket.
request.get(field)
Return request header with case-insensitive field.
File: docs/api/response.md
Response
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.
API
response.header
Response header object.
response.headers
Response header object. Alias as response.header.
response.socket
Response socket. Points to net.Socket instance as request.socket.
response.status
Get response status. By default, response.status is set to 404 unlike Node's res.statusCode which defaults to 200.
response.status=
Set response status via numeric code:
- 100 "continue"
- 101 "switching protocols"
- 102 "processing"
- 200 "ok"
- 201 "created"
- 202 "accepted"
- 203 "non-authoritative information"
- 204 "no content"
- 205 "reset content"
- 206 "partial content"
- 207 "multi-status"
- 208 "already reported"
- 226 "im used"
- 300 "multiple choices"
- 301 "moved permanently"
- 302 "found"
- 303 "see other"
- 304 "not modified"
- 305 "use proxy"
- 307 "temporary redirect"
- 308 "permanent redirect"
- 400 "bad request"
- 401 "unauthorized"
- 402 "payment required"
- 403 "forbidden"
- 404 "not found"
- 405 "method not allowed"
- 406 "not acceptable"
- 407 "proxy authentication required"
- 408 "request timeout"
- 409 "conflict"
- 410 "gone"
- 411 "length required"
- 412 "precondition failed"
- 413 "payload too large"
- 414 "uri too long"
- 415 "unsupported media type"
- 416 "range not satisfiable"
- 417 "expectation failed"
- 418 "I'm a teapot"
- 422 "unprocessable entity"
- 423 "locked"
- 424 "failed dependency"
- 426 "upgrade required"
- 428 "precondition required"
- 429 "too many requests"
- 431 "request header fields too large"
- 500 "internal server error"
- 501 "not implemented"
- 502 "bad gateway"
- 503 "service unavailable"
- 504 "gateway timeout"
- 505 "http version not supported"
- 506 "variant also negotiates"
- 507 "insufficient storage"
- 508 "loop detected"
- 510 "not extended"
- 511 "network authentication required"
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.
Since response.status default is set to 404, to send a response
without a body and with a different status is to be done like this:
ctx.response.status = 200;
// Or whatever other status
ctx.response.status = 204;response.message
Get response status message. By default, response.message is
associated with response.status.
response.message=
Set response status message to the given value.
response.length=
Set response Content-Length to the given value.
response.length
Return response Content-Length as a number when present, or deduce
from ctx.body when possible, or undefined.
response.body
Get response body.
response.body=
Set response body to one of the following:
stringwrittenBufferwrittenStreampipedObject||Arrayjson-stringifiednull||undefinedno content response
If response.status has not been set, Koa will automatically set the status to 200 or 204 depending on response.body. Specifically, if response.body has not been set or has been set as null or undefined, Koa will automatically set response.status to 204. If you really want to send no content response with other status, you should override the 204 status as the following way:
// This must be always set first before status, since null | undefined
// body automatically sets the status to 204
ctx.body = null;
// Now we override the 204 status with the desired one
ctx.status = 200;Koa doesn't guard against everything that could be put as a response body -- a function doesn't serialise meaningfully, returning a boolean may make sense based on your application, and while an error works, it may not work as intended as some properties of an error are not enumerable. We recommend adding middleware in your app that asserts body types per app. A sample middleware might be:
app.use(async (ctx, next) => {
await next()
ctx.assert.equal('object', typeof ctx.body, 500, 'some dev did something wrong')
})String
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.
Buffer
The Content-Type is defaulted to application/octet-stream, and Content-Length
is also set.
Stream
The Content-Type is defaulted to application/octet-stream.
Whenever a stream is set as the response body, .onerror is automatically added as a listener to the error event to catch any errors.
In addition, whenever the request is closed (even prematurely), the stream is destroyed.
If you do not want these two features, do not set the stream as the body directly.
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;
app.use(async ctx => {
ctx.body = someHTTPStream.on('error', (err) => ctx.onerror(err)).pipe(PassThrough());
});Object
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.has(field)
Returns true if the header identified by name is currently set in the outgoing headers.
The header name matching is case-insensitive.
const rateLimited = ctx.response.has('X-RateLimit-Limit');response.set(field, value)
Set response header field to 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)
Set several response header fields with an object:
ctx.set({
'Etag': '1234',
'Last-Modified': date
});This delegates to setHeader which sets or updates headers by specified keys and doesn't reset the entire header.
response.remove(field)
Remove header field.
response.type
Get response Content-Type void of parameters such as "charset".
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 = 'image/png';
ctx.type = '.png';
ctx.type = 'png'; Note: when appropriate a charset is selected for you, for
example response.type = 'html' will default to "utf-8". If you need to overwrite charset,
use ctx.set('Content-Type', 'text/html') to set response header field to value directly.
response.is(types...)
Very similar to ctx.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.
const minify = require('html-minifier');
app.use(async (ctx, next) => {
await next();
if (!ctx.response.is('html')) return;
let body = ctx.body;
if (!body || body.pipe) return;
if (Buffer.isBuffer(body)) body = body.toString();
ctx.body = minify(body);
});response.redirect(url)
Perform a [302] redirect to url.
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.redirect('/cart');
ctx.body = 'Redirecting to shopping cart';response.back(url)
Similar to .redirect(url), but first checks the referer header to redirect.
This is new in v3 as .redirect(url, alt) removes the special case url = 'back' option.
response.attachment([filename], [options])
Set Content-Disposition to "attachment" to signal the client
to prompt for download. Optionally specify the filename of the
download and some options.
response.headerSent
Check if a response header has already been sent. Useful for seeing
if the client may be notified on error.
response.lastModified
Return the Last-Modified header as a Date, if it exists.
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=
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)
Vary on field.
response.flushHeaders()
Flush any set headers to the client. This is a proxy for res.flushHeaders()
response.writable
A boolean that indicates whether the response is still writable.
File: docs/error-handling.md
Error Handling
Try-Catch
Using async functions means that you can try-catch next.
This example adds a .status to all errors:
app.use(async (ctx, next) => {
try {
await next();
} catch (err) {
err.status = err.statusCode || err.status || 500;
throw err;
}
});Default Error Handler
The default error handler is essentially a try-catch at
the very beginning of the middleware chain. To use a
different error handler, simply put another try-catch at
the beginning of the middleware chain, and handle the error
there. However, the default error handler is good enough for
most use cases. It will use a status code of err.status,
or by default 500. If err.expose is true, then err.message
will be the reply. Otherwise, a message generated from the
error code will be used (e.g. for the code 500 the message
"Internal Server Error" will be used). All headers will be
cleared from the request, but any headers in err.headers
will then be set. You can use a try-catch, as specified
above, to add a header to this list.
Here is an example of creating your own error handler:
app.use(async (ctx, next) => {
try {
await next();
} catch (err) {
// will only respond with JSON
ctx.status = err.statusCode || err.status || 500;
ctx.body = {
message: err.message
};
}
})The Error Event
Error event listeners can be specified with app.on('error').
If no error listener is specified, a default error listener
is used. Error listeners receive all errors that make their
way back through the middleware chain, if an error is caught
and not thrown again, it will not be passed to the error
listener. If no error event listener is specified, then
app.onerror will be used, which simply log the error unless
error.exposeis true or app.silent is true or error.status
is 404.
File: docs/faq.md
Frequently Asked Questions
Does Koa replace Express?
It's more like Connect, but a lot of the Express goodies
were moved to the middleware level in Koa to help form
a stronger foundation. This makes middleware more enjoyable
and less error-prone to write, for the entire stack, not
just the end application code.
Typically many middleware would
re-implement similar features, or even worse incorrectly implement them,
when features like signed cookie secrets among others are typically application-specific,
not middleware specific.
Does Koa replace Connect?
No, just a different take on similar functionality
now that async functions allow us to write code with fewer
callbacks. Connect is equally capable, and some may still prefer it,
it's up to what you prefer.
Does Koa include routing?
No - out of the box Koa has no form of routing, however
many routing middleware are available: https://github.com/koajs/koa/wiki
Why isn't Koa just Express 4.0?
Koa is a pretty large departure from what people know about Express,
the design is fundamentally much different, so the migration from
Express 3.0 to this Express 4.0 would effectively mean rewriting
the entire application, so we thought it would be more appropriate
to create a new library.
What custom properties do the Koa objects have?
Koa uses its own custom objects: ctx, ctx.request, and ctx.response.
These objects abstract Node's req and res objects with convenience methods and getters/setters.
Generally, properties added to these objects must obey the following rules:
- They must be either very commonly used and/or must do something useful
- If a property exists as a setter, then it will also exist as a getter, but not vice versa
Many of ctx.request and ctx.response's properties are delegated to ctx.
If it's a getter/setter, then both the getter and the setter will strictly
correspond to either ctx.request or ctx.response.
Please think about these rules before suggesting additional properties.
File: docs/guide.md
Guide
This guide covers Koa topics that are not directly API related, such as best practices for writing middleware and application structure suggestions. In these examples we use async functions as middleware - you can also use commonFunction or generatorFunction which will be a little different.
Table of Contents
Writing Middleware
Koa middleware are simple functions with the signature (ctx, next) (i.e. a MiddlewareFunction). When
the middleware is run, it must manually invoke next() to run the "downstream" middleware.
For example if you wanted to track how long it takes for a request to propagate through Koa by adding an
X-Response-Time header field the middleware would look like the following:
async function responseTime(ctx, next) {
const start = Date.now();
await next();
const ms = Date.now() - start;
ctx.set('X-Response-Time', `${ms}ms`);
}
app.use(responseTime); If you're a front-end developer you can think any code before next(); as the "capture" phase,
while any code after is the "bubble" phase. This crude gif illustrates how async function allow us
to properly utilize stack flow to implement request and response flows:
- Create a date to track response time
- Await control to the next middleware
- Create another date to track duration
- Await control to the next middleware
- Set the response body to "Hello World"
- Calculate duration time
- Output log line
- Calculate response time
- Set
X-Response-Timeheader field - Hand off to Koa to handle the response
Next we'll look at the best practices for creating Koa middleware.
Middleware Best Practices
This section covers middleware authoring best practices, such as middleware
accepting options, named middleware for debugging, among others.
Middleware options
When creating a public middleware, it's useful to conform to the convention of
wrapping the middleware in a function that accepts options, allowing users to
extend functionality. Even if your middleware accepts no options, this is still
a good idea to keep things uniform.
Here our contrived logger middleware accepts a format string for customization,
and returns the middleware itself:
function logger(format) {
format = format || ':method ":url"';
return async function (ctx, next) {
const str = format
.replace(':method', ctx.method)
.replace(':url', ctx.url);
console.log(str);
await next();
};
}
app.use(logger());
app.use(logger(':method :url'));Named middleware
Naming middleware is optional, however it's useful for debugging purposes to assign a name.
function logger(format) {
return async function logger(ctx, next) {
};
}Combining multiple middleware with koa-compose
Sometimes you want to "compose" multiple middleware into a single middleware for easy re-use or exporting. You can use koa-compose
const compose = require('koa-compose');
async function random(ctx, next) {
if ('/random' == ctx.path) {
ctx.body = Math.floor(Math.random() * 10);
} else {
await next();
}
};
async function backwards(ctx, next) {
if ('/backwards' == ctx.path) {
ctx.body = 'sdrawkcab';
} else {
await next();
}
}
async function pi(ctx, next) {
if ('/pi' == ctx.path) {
ctx.body = String(Math.PI);
} else {
await next();
}
}
const all = compose([random, backwards, pi]);
app.use(all);Response Middleware
Middleware that decide to respond to a request and wish to bypass downstream middleware may
simply omit next(). Typically this will be in routing middleware, but this can be performed by
any. For example the following will respond with "two", however all three are executed, giving the
downstream "three" middleware a chance to manipulate the response.
app.use(async function (ctx, next) {
console.log('>> one');
await next();
console.log('<< one');
});
app.use(async function (ctx, next) {
console.log('>> two');
ctx.body = 'two';
await next();
console.log('<< two');
});
app.use(async function (ctx, next) {
console.log('>> three');
await next();
console.log('<< three');
}); The following configuration omits next() in the second middleware, and will still respond
with "two", however the third (and any other downstream middleware) will be ignored:
app.use(async function (ctx, next) {
console.log('>> one');
await next();
console.log('<< one');
});
app.use(async function (ctx, next) {
console.log('>> two');
ctx.body = 'two';
console.log('<< two');
});
app.use(async function (ctx, next) {
console.log('>> three');
await next();
console.log('<< three');
}); When the furthest downstream middleware executes next();, it's really yielding to a noop
function, allowing the middleware to compose correctly anywhere in the stack.
Async operations
Async function and promise forms Koa's foundation, allowing
you to write non-blocking sequential code. For example this middleware reads the filenames from ./docs,
and then reads the contents of each markdown file in parallel before assigning the body to the joint result.
const fs = require('fs').promises;
app.use(async function (ctx, next) {
const paths = await fs.readdir('docs');
const files = await Promise.all(paths.map(path => fs.readFile(`docs/${path}`, 'utf8')));
ctx.type = 'markdown';
ctx.body = files.join('');
});Debugging Koa
Koa, along with many of the libraries it's built, can be debugged using Node.js's built-in util.debuglog, which provides simple conditional logging via the NODE_DEBUG environment variable.
For example
to see all Koa-specific debugging information just pass NODE_DEBUG=koa* and upon boot you'll see the list of middleware used, among other things.
$ NODE_DEBUG=koa* node --harmony examples/simple
koa:application use responseTime +0ms
koa:application use logger +4ms
koa:application use contentLength +0ms
koa:application use notfound +0ms
koa:application use response +0ms
koa:application listen +0ms Since JavaScript does not allow defining function names at
runtime, you can also set a middleware's name as ._name.
This is useful when you don't have control of a middleware's name.
For example:
const path = require('node:path');
const serve = require('koa-static');
const publicFiles = serve(path.join(__dirname, 'public'));
publicFiles._name = 'static /public';
app.use(publicFiles);Now, instead of just seeing "serve" when debugging, you will see:
koa:application use static /public +0msThis lets you use Koaโs internal debug logs without any third-party dependencies by relying on node:util's built-in debuglog.
HTTP2
Example of setting up an HTTP2 server with Koa using the HTTP compatibility layer:
import Koa from 'koa'
import http2 from 'node:http2'
import fs from 'node:fs'
const app = new Koa();
const onRequestHandler = app.callback();
const serverOptions = {
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('cert.pem')
}
const server = http2.createSecureServer(serverOptions, onRequestHandler);
server.listen(3000);Server-Sent Events
An example of using server-sent events with Koa:
import { PassThrough } from 'node:stream'
import OpenAI from 'openai'
import Koa from 'koa'
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
})
const app = new Koa()
app.use(async (ctx, next) => { // TODO: use your favorite routing library
const { message } = await ctx.request.json() // this example uses koa-body-parsers
const stream = await openai.chat.completions.create({
model: 'gpt-4o-mini',
messages: [{ role: 'user', content: message }],
stream: true,
})
ctx.response.type = 'text/event-stream'
const body = ctx.body = new PassThrough()
// streaming needs to be handled in a separate event loop
;(async () => {
for await (const chunk of stream) {
const content = chunk.choices[0]?.delta?.content
if (!content) continue
body.write(`data: ${JSON.stringify({
delta: {
content: chunk.choices[0].delta.content || ''
}
})}\n\n`)
}
body.end()
})().catch((err) => app.emit('error', err))
})
app.listen(3000)File: docs/koa-vs-express.md
Koa vs Express
Philosophically, Koa aims to "fix and replace Node", whereas Express "augments Node".
Koa uses promises and async functions to rid apps of callback hell and simplify error handling.
It exposes its own ctx.request and ctx.response objects instead of Node's req and res objects.
Express, on the other hand, augments Node's req and res objects with additional properties and methods
and includes many other "framework" features, such as routing and templating, which Koa does not.
Thus, Koa can be viewed as an abstraction of Node.js's http modules, where as Express is an application framework for Node.js.
| Feature | Koa | Express | Connect |
|---|---|---|---|
| Middleware Kernel | โ | โ | โ |
| Routing | โ | ||
| Templating | โ | ||
| Sending Files | โ | ||
| JSONP | โ |
NOTE: this doesn't mean Koa is incapable of supporting these features, these features are simply supported by other modules (middleware, plugins, etc.) versus the framework itself.
Thus, if you'd like to be closer to Node.js and traditional Node.js-style coding, you probably want to stick to Connect/Express or similar frameworks.
If you want to get rid of callbacks, use Koa.
As result of this different philosophy is that traditional Node.js "middleware", i.e. functions of the form (req, res, next), are incompatible with Koa. Your application will essentially have to be rewritten from the ground, up.
Does Koa replace Express?
It's more like Connect, but a lot of the Express goodies
were moved to the middleware level in Koa to help form
a stronger foundation. This makes middleware more enjoyable
and less error-prone to write, for the entire stack, not
just the end application code.
Typically many middleware would
re-implement similar features, or even worse incorrectly implement them,
when features like signed cookie secrets among others are typically application-specific,
not middleware-specific.
Does Koa replace Connect?
No, just a different take on similar functionality
now that generators allow us to write code with fewer
callbacks. Connect is equally capable, and some may still prefer it,
it's up to what you prefer.
Why isn't Koa just Express 4.0?
Koa is a pretty large departure from what people know about Express,
the design is fundamentally much different, so the migration from
Express 3.0 to this Express 4.0 would effectively mean rewriting
the entire application, so we thought it would be more appropriate
to create a new library.
How is Koa different from Connect/Express?
Promises-based control flow
No callback hell.
Better error handling through try/catch.
No need for domains.
Koa is barebones
Unlike both Connect and Express, Koa does not include any middleware.
Unlike Express, routing is not provided.
Unlike Express, many convenience utilities are not provided. For example, sending files.
Koa is more modular.
Koa relies less on middleware
For example, instead of a "body parsing" middleware, you would instead use a body parsing function.
Koa abstracts Node's request/response
Less hackery.
Better user experience.
Proper stream handling.
Koa routing (third party libraries support)
Since Express comes with its own routing, but Koa does not have
any built-in routing, there are third party libraries available such as
koa-router and koa-route.
Similarly, just like we have helmet for security in Express, for Koa
we have koa-helmet available and the list goes on for Koa available third
party libraries.
File: docs/migration-v1-to-v2.md
Migrating from Koa v1.x to v2.x
New middleware signature
Koa v2 introduces a new signature for middleware.
Old signature middleware (v1.x) support will be removed in v3
The new middleware signature is:
// uses async arrow functions
app.use(async (ctx, next) => {
try {
await next() // next is now a function
} catch (err) {
ctx.body = { message: err.message }
ctx.status = err.status || 500
}
})
app.use(async ctx => {
const user = await User.getById(this.session.userid) // await instead of yield
ctx.body = user // ctx instead of this
})You don't have to use asynchronous functions - you just have to pass a function that returns a promise.
A regular function that returns a promise works too!
The signature has changed to pass Context via an explicit parameter, ctx above, instead of viathis. The context passing change makes Koa more compatible with es6 arrow functions, which capture this.
Using v1.x Middleware in v2.x
Koa v2.x will try to convert legacy signature, generator middleware on app.use, using koa-convert.
It is however recommended that you choose to migrate all v1.x middleware as soon as possible.
// Koa will convert
app.use(function *(next) {
const start = Date.now();
yield next;
const ms = Date.now() - start;
console.log(`${this.method} ${this.url} - ${ms}ms`);
});You could do it manually as well, in which case Koa will not convert.
const convert = require('koa-convert');
app.use(convert(function *(next) {
const start = Date.now();
yield next;
const ms = Date.now() - start;
console.log(`${this.method} ${this.url} - ${ms}ms`);
}));Upgrading middleware
You will have to convert your generators to async functions with the new middleware signature:
app.use(async (ctx, next) => {
const user = await Users.getById(this.session.user_id);
await next();
ctx.body = { message: 'some message' };
})Upgrading your middleware may require some work. One migration path is to update them one-by-one.
- Wrap all your current middleware in
koa-convert - Test
npm outdatedto see which Koa middleware is outdated- Update one outdated middleware, remove using
koa-convert - Test
- Repeat steps 3-5 until you're done
Updating your code
You should start refactoring your code now to ease migrating to Koa v2:
- Return promises everywhere!
- Do not use
yield* - Do not use
yield {}oryield [].- Convert
yield []intoyield Promise.all([]) - Convert
yield {}intoyield Bluebird.props({})
- Convert
You could also refactor your logic outside of Koa middleware functions. Create functions likefunction* someLogic(ctx) {} and call it in your middleware asconst result = yield someLogic(this).
Not using this will help migrations to the new middleware signature, which does not use this.
Application object constructor requires new
In v1.x, the Application constructor function could be called directly, without new to
instantiate an instance of an application. For example:
var koa = require('koa');
var app = module.exports = koa();v2.x uses es6 classes which require the new keyword to be used.
var koa = require('koa');
var app = module.exports = new koa();ENV specific logging behavior removed
An explicit check for the test environment was removed from error handling.
Dependency changes
- co is no longer bundled with Koa. Require or import it directly.
- composition is no longer used and deprecated.
v1.x support
The v1.x branch is still supported but should not receive feature updates. Except for this migration
guide, documentation will target the latest version.
Help out
If you encounter migration related issues not covered by this migration guide, please consider
submitting a documentation pull request.