Model answers for 4 Koa.js questions
Typical round: middleware model, ctx, error handling, a small coding task
Q: How does Koa middleware execute? A: Each middleware is an async function (ctx, next). Code before await next() runs on the way down the stack; code after it runs on the way back up, like layers of an onion. That is why a timing middleware can record the start time, await next(), then set an X-Response-Time header after every later middleware has finished.
Q: What is ctx? A: The context object Koa creates per request. It wraps Node's req and res as ctx.request and ctx.response, delegates common properties such as ctx.body, ctx.status, ctx.query and ctx.headers, and offers ctx.state for passing data, such as the logged-in user, between middleware.
Q: How do you handle errors in Koa? A: Put a middleware near the top that wraps await next() in try/catch, sets ctx.status and ctx.body from the error, and calls ctx.app.emit('error', err, ctx) for logging. Inside routes, ctx.throw(404, 'Not found') or ctx.assert(user, 401) raise HTTP errors that this handler formats.
Q: Koa vs Express? A: Both are minimal Node.js frameworks from the same original team. Koa is built around async functions and a context object, has no bundled router or body parser, and its cascading middleware makes before-and-after logic and error handling simpler. Express has a larger ecosystem and callback-style middleware with req, res and next.