Context

Understand Koa's ctx context object, learn its common properties and aliases, and use it to read requests and configure responses.

🎯 Introduction

By the end of this article, you will understand what ctx contains and use common aliases such as ctx.query, ctx.body, and ctx.status to read request data and configure responses. These are the basics you will use every day when writing Koa applications.


🧱 What Is ctx?

In the native http module and Express, request and response information lives in separate req and res objects. Koa wraps both in a single object called ctx, short for Context.

Think of ctx as a courier's delivery form. It contains both the recipient details (data sent by the requester) and a receipt section (the response we send back). You can handle the entire request with one form, without switching between two objects.

Koa creates a separate ctx for every incoming request, keeping requests independent. Recall the middleware syntax:

app.js
app.use(async (ctx) => {
    // ctx is the delivery form for this request
});

🧱 ctx.request and ctx.response

Inside ctx, information is divided into two parts:

  • ctx.request: Request information, such as the URL, HTTP method, and query parameters.
  • ctx.response: Response information, such as the body, status code, and headers.

For example:

app.js
app.use(async (ctx) => {
    console.log(ctx.request.path); // Request path, such as /users
    console.log(ctx.request.method); // HTTP method, such as GET

    ctx.response.body = 'Hello'; // Set the response body
    ctx.response.status = 200; // Set the status code
});

This is a little verbose. Koa provides aliases that expose frequently used properties directly on ctx, so you can write less code.


💡 Common Aliases at a Glance

Aliases are the usual choice in application code. These are the most common:

AliasEquivalent toPurpose
ctx.queryctx.request.queryQuery parameter object
ctx.pathctx.request.pathRequest path
ctx.methodctx.request.methodHTTP method
ctx.bodyctx.response.bodyRead or set the response body
ctx.statusctx.response.statusRead or set the status code
ctx.set()ctx.response.set()Set a response header

Here is an example using them together:

app.js
app.use(async (ctx) => {
    // When visiting /search?keyword=koa
    const keyword = ctx.query.keyword; // Read the query parameter value: koa

    ctx.set('X-Powered-By', 'Koa'); // Set a custom response header
    ctx.status = 200;
    ctx.body = {
        message: `You searched for: ${keyword}`,
        path: ctx.path,
        method: ctx.method,
    };
});

Visit http://localhost:3000/search?keyword=koa to receive a JSON response containing the search term. You do not need to parse the ?keyword=koa string yourself: ctx.query already provides a parsed object.

Remember: read ctx.xxx to access request data, and assign ctx.body and ctx.status to configure the response. These aliases cover most everyday tasks.

⚠️ Can I Still Use the Native req and res?

Yes. Koa still uses Node.js's http module underneath. The native objects are available as ctx.req and ctx.res:

app.js
app.use(async (ctx) => {
    console.log(ctx.req.url); // URL from the native request object
});

However, mixing the two APIs is discouraged. Koa's ctx handles almost all common scenarios. Manipulating the response through native objects, such as calling ctx.res.end(), bypasses Koa's response handling and can leave the response in an inconsistent state.

As a rule, set responses through ctx.body and avoid ctx.res.end(). Access native objects only for uncommon low-level requirements, such as specialized stream handling.

❓ Questions and Answers

Q1: What types of values does ctx.query return?

Query parameter values are strings. For ?page=2, ctx.query.page is the string '2', not the number 2. Use Number() when you need a number.

Q2: What if the same query parameter appears more than once?

For ?tag=a&tag=b, ctx.query.tag is the array ['a', 'b']. With one occurrence, it is a string, so check the type before processing it.

Q3: Can I read ctx.body?

Yes. Later middleware can read a value set by earlier middleware. In practice, reading the response body is less common; you usually assign it once near the end of processing.

Q4: What happens if I do not set ctx.status?

It defaults to 404. Once you assign a value to ctx.body, Koa automatically changes the status to 200, so you generally do not need to set 200 manually.


🧪 Practice

  1. Write a /user endpoint that accepts name and age query parameters and returns JSON: { "greeting": "Hello, xxx. You are xx years old." }.
app.js
import Koa from 'koa';

const app = new Koa();

app.use(async (ctx) => {
    if (ctx.path === '/user') {
        // Write your code here
    }
});

app.listen(3000);
  1. Visit http://localhost:3000/user?name=Alex&age=18 in your browser to verify the result.

🎉 You now know the common operations on ctx! Next, we will explore middleware and the onion model, the key to understanding Koa.