Medium15 minKoa.js Fundamentals
UpdatedAug 5, 2026
Edit

Koa Response Handling

Question Variations

  • "What happens when a Koa handler sets `ctx.body` to an object?"
  • "Why should you avoid `ctx.res.end()`?"
  • "How do you return 204 correctly from a Koa route?"

Why This Is Asked

Koa’s response abstraction sets defaults based on the body and status. Interviewers use this topic to assess whether you can produce correct API responses without bypassing the framework’s lifecycle.

Key Concepts

  • Set ctx.status, ctx.body, headers, and type through the Koa context.
  • Objects and arrays are JSON serialized by Koa.
  • Koa defaults to 404 until a response body or status changes it.
  • Writing to raw ctx.res bypasses Koa and is generally unsupported.

Question Variations

  • “What happens when a Koa handler sets ctx.body to an object?”
  • “Why should you avoid ctx.res.end()?”
  • “How do you return 204 correctly from a Koa route?”

Answers by Technology

+ Add Variant
Koa.jsImprove this answer ✏️

Expected Answer (Koa 3.2.1 / Node.js 18+)

Use Koa’s context to build responses: set ctx.status, ctx.body, and headers rather than manually writing to Node’s raw response. Assigning an object or array to ctx.body serializes it as JSON. Koa defaults an untouched response to 404, which is why a route must set a body or explicit status. For a bodyless success, set the intended 204 status directly.

Why It Matters

Koa’s response abstraction keeps status, headers, and body behavior consistent across middleware.

Code Example

import Koa, { Context } from 'koa';

const app = new Koa();
app.use((ctx: Context) => {
  if (ctx.path === '/deleted') { ctx.status = 204; return; }
  ctx.status = 200; ctx.body = { message: 'ok' };
});
app.listen(3000);

Common Mistakes

  • Calling ctx.res.end() directly: It bypasses Koa’s response handling.
  • Leaving a successful route without body or status: Koa retains the default 404.

Follow-up Questions

  • What body type produces JSON? (Answer: An object or array.)
  • Why explicitly set 204? (Answer: It communicates successful no-content semantics.)