2013-11-13 17:01:15 +00:00
# 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
2014-02-14 02:23:45 +00:00
that they are added at this level instead of a higher level framework,
2013-12-22 12:26:30 +00:00
which would force middleware to re-implement this common functionality.
2013-11-13 17:01:15 +00:00
2013-11-20 06:40:52 +00:00
A `Context` is created _per_ request, and is referenced in middleware
2016-03-22 18:03:10 +00:00
as the receiver, or the `ctx` identifier, as shown in the following
2013-12-19 04:35:38 +00:00
snippet:
```js
2017-07-21 01:01:03 +00:00
app.use(async ctx => {
2016-03-22 18:03:10 +00:00
ctx; // is the Context
2018-01-31 05:05:00 +00:00
ctx.request; // is a Koa Request
ctx.response; // is a Koa Response
2013-12-19 04:35:38 +00:00
});
```
2013-11-13 17:01:15 +00:00
2014-02-14 02:23:45 +00:00
Many of the context's accessors and methods simply delegate to their `ctx.request` or `ctx.response`
2014-02-14 17:20:29 +00:00
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` .
2014-02-14 02:23:45 +00:00
2013-11-13 17:01:15 +00:00
## API
`Context` specific methods and accessors.
### ctx.req
Node's `request` object.
### ctx.res
2013-11-20 06:40:52 +00:00
2013-11-13 17:01:15 +00:00
Node's `response` object.
2013-12-31 06:07:22 +00:00
Bypassing Koa's response handling is __not supported__ . Avoid using the following node properties:
- `res.statusCode`
- `res.writeHead()`
- `res.write()`
- `res.end()`
2013-12-26 08:11:14 +00:00
2013-11-13 17:01:15 +00:00
### ctx.request
2018-01-31 05:05:00 +00:00
A Koa `Request` object.
2013-11-13 17:01:15 +00:00
### ctx.response
2013-11-20 06:40:52 +00:00
2018-01-31 05:05:00 +00:00
A Koa `Response` object.
2013-11-13 17:01:15 +00:00
2014-11-18 08:54:14 +00:00
### ctx.state
The recommended namespace for passing information through middleware and to your frontend views.
```js
2016-08-22 04:21:09 +00:00
ctx.state.user = await User.find(id);
2014-11-18 08:54:14 +00:00
```
2013-11-13 17:01:15 +00:00
### ctx.app
Application instance reference.
2018-12-07 07:28:23 +00:00
### ctx.app.emit
Koa applications extend an internal [EventEmitter ](https://nodejs.org/dist/latest-v11.x/docs/api/events.html ). `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 ](https://koajs.com/#error-handling ) for more information.
2017-04-21 13:49:06 +00:00
### ctx.throw([status], [msg], [properties])
2013-11-13 17:01:15 +00:00
Helper method to throw an error with a `.status` property
2013-12-19 04:35:38 +00:00
defaulting to `500` that will allow Koa to respond appropriately.
2013-12-18 09:30:27 +00:00
The following combinations are allowed:
2013-11-13 17:01:15 +00:00
```js
2017-04-21 13:49:06 +00:00
ctx.throw(400);
2016-03-22 18:03:10 +00:00
ctx.throw(400, 'name required');
2017-04-21 13:49:06 +00:00
ctx.throw(400, 'name required', { user: user });
2013-11-13 17:01:15 +00:00
```
2017-04-21 13:49:06 +00:00
For example `ctx.throw(400, 'name required')` is equivalent to:
2013-11-13 17:01:15 +00:00
```js
2015-10-24 09:21:47 +00:00
const err = new Error('name required');
2013-11-13 17:01:15 +00:00
err.status = 400;
2016-11-25 03:51:02 +00:00
err.expose = true;
2013-11-13 17:01:15 +00:00
throw err;
```
Note that these are user-level errors and are flagged with
2013-11-20 06:40:52 +00:00
`err.expose` meaning the messages are appropriate for
2013-11-13 17:01:15 +00:00
client responses, which is typically not the case for
error messages since you do not want to leak failure
2013-12-19 04:35:38 +00:00
details.
2013-12-25 06:59:55 +00:00
2014-08-12 20:22:33 +00:00
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.
2014-08-08 20:31:28 +00:00
```js
2016-03-22 18:03:10 +00:00
ctx.throw(401, 'access_denied', { user: user });
2014-08-08 20:31:28 +00:00
```
2018-11-01 11:17:16 +00:00
Koa uses [http-errors ](https://github.com/jshttp/http-errors ) to create errors. `status` should only be passed as the first parameter.
2014-09-20 20:19:07 +00:00
2016-03-27 03:26:09 +00:00
### ctx.assert(value, [status], [msg], [properties])
2014-09-20 20:19:07 +00:00
Helper method to throw an error similar to `.throw()`
when `!value` . Similar to node's [assert() ](http://nodejs.org/api/assert.html )
method.
```js
2016-03-22 18:03:10 +00:00
ctx.assert(ctx.state.user, 401, 'User not found. Please login!');
2014-09-20 20:19:07 +00:00
```
2018-01-31 05:05:00 +00:00
Koa uses [http-assert ](https://github.com/jshttp/http-assert ) for assertions.
2014-09-20 20:19:07 +00:00
2014-01-24 22:38:40 +00:00
### ctx.respond
2016-03-22 18:03:10 +00:00
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.
2014-01-24 22:38:40 +00:00
2014-05-03 21:21:07 +00:00
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.
2014-01-24 22:38:40 +00:00
2013-12-25 06:59:55 +00:00
## Request aliases
The following accessors and alias [Request ](request.md ) equivalents:
- `ctx.header`
2014-08-09 05:39:36 +00:00
- `ctx.headers`
2013-12-25 06:59:55 +00:00
- `ctx.method`
- `ctx.method=`
- `ctx.url`
- `ctx.url=`
2014-05-06 02:01:34 +00:00
- `ctx.originalUrl`
2015-10-03 03:38:48 +00:00
- `ctx.origin`
2014-11-23 08:00:17 +00:00
- `ctx.href`
2013-12-25 06:59:55 +00:00
- `ctx.path`
- `ctx.path=`
- `ctx.query`
- `ctx.query=`
- `ctx.querystring`
- `ctx.querystring=`
- `ctx.host`
2014-05-04 14:43:58 +00:00
- `ctx.hostname`
2013-12-25 06:59:55 +00:00
- `ctx.fresh`
- `ctx.stale`
- `ctx.socket`
- `ctx.protocol`
- `ctx.secure`
- `ctx.ip`
- `ctx.ips`
- `ctx.subdomains`
- `ctx.is()`
- `ctx.get()`
## Response aliases
The following accessors and alias [Response ](response.md ) equivalents:
- `ctx.body`
- `ctx.body=`
- `ctx.status`
- `ctx.status=`
2014-10-01 12:12:20 +00:00
- `ctx.message`
- `ctx.message=`
2014-02-14 17:33:10 +00:00
- `ctx.length=`
2014-03-07 02:05:01 +00:00
- `ctx.length`
2014-02-14 17:33:10 +00:00
- `ctx.type=`
2014-03-07 02:05:01 +00:00
- `ctx.type`
2013-12-25 06:59:55 +00:00
- `ctx.headerSent`
- `ctx.redirect()`
- `ctx.attachment()`
- `ctx.set()`
2015-01-25 17:53:55 +00:00
- `ctx.append()`
2013-12-25 06:59:55 +00:00
- `ctx.remove()`
- `ctx.lastModified=`
2014-02-14 05:42:04 +00:00
- `ctx.etag=`