The context object exposes various methods and properties to help with HTTP application development and middleware creation. In this way, Koa varies from its predecessor, Express, in that the many functions needed for development can be accessed simply via the context object instead of needing to access the request (req) and response (res) objects separately.
Some of the methods and properties exposed on the Context object include the following:
- ctx.req: This serves as a reference to the request object in Node. Note that this differs from the Koa request object.
For example, you can access an object containing the request headers by using the req.headers property, as seen here:
console.log(ctx.req.headers);
// => { host: 'localhost:1234',
// 'user-agent': 'curl/7.54.0',
// accept: '*/*' }
- ctx.res: Similar to ctx.req, this serves as a reference to the response object in Node. Note that bypassing Koa's response handling is not supported by Koa currently. Hence, Node response methods that directly attempt to write or manipulate the response body should be avoided, such as the following:
- res.statusCode
- res.writeHead()
- res.write()
- res.end()
The ctx.res object can be used in the following manner:
ctx.res.setHeader('Content-Type', 'text/html');
console.log(ctx.res.getHeader('Content-Type'));
// => text/html
- ctx.request:This is an instance of the Koa request object. It provides access to all the request related methods and properties needed for HTTP application development. This object will be discussed in further details in later sections.
The request object can be used, for example, to retrieve the origin of a request, as seen in the example here:
console.log(ctx.request.origin);
// => http://localhost:1234
- ctx.response: This is an instance of the Koa response object. Similar to the Koa request object, it provides everyday functionality for building out HTTP applications. It will also be discussed in more detail in later sections of this chapter.
Here is an example of how you can use the response object to set the HTTP status for a response in Koa:
ctx.response.status = 200;
console.log(ctx.response.message);
// => Ok
- ctx.state: This is the namespace recommend by Koa for passing data throughout your application. A good use case of this is passing some data across middleware and to your views, as seen in this example:
// middleware for retrieving user details
app.use(async ctx => {
ctx.state.user = await User.find(id);
});
// middleware to send response back to user
app.use(async ctx => {
const { user } = ctx.state;
ctx.body = `Hello, ${user.name}`;
});
- ctx.app: This is a reference to the Koa application instance discussed earlier in this chapter. This reference allows us to make use of the application object in our middleware. For example, this is a middleware we can use to log information depending on the environment our application is running in:
app.use(async (ctx, next) => {
const { env } = ctx.app;
if (env === 'development') {
console.log(`request made to ${ctx.request.url}`);
}
await next();
});
- ctx.cookies: This object consists of two methods for interacting with cookies. Koa uses the cookies module and simply passes the options. The two methods available for use are:
- ctx.cookies.get(name, [options]): This returns the value of a cookie named name with options.
- ctx.cookies.set(name, [options]): This sets cookie name with options.
These methods can be used in the following manner:
ctx.cookies.set('SESSION_ID', '1234');
// after response has been sent and the
// cookie has been set on the client
console.log(ctx.cookies.get('SESSION_ID'));
// => 1234
- ctx.throw([status], [msg], [properties]): This is a helper method that throws an HTTP error with a status as a response. This makes use of the http-errors module. Here are some simple example usages of the method:
ctx.throw(401);
ctx.throw(401, 'Unauthorized');
ctx.throw(401, 'Unathourized', { user });
- ctx.assert(value, [status], [msg], [properties]): This is a helper method that throws an error similar to the ctx.throw method when value is a false value. Koa makes use of http-assert for assertions.
- ctx.respond: Koa's default response handling can be turned off by explicitly setting ctx.respond to false. This can be used if a decision is made to manually write to the res object, instead of utilizing Koa's response handling. This behavior is currently not supported by Koa and could cause unexpected results.