How is the context object created per request?
How is the context object created per request?
About koajs/koa · 2 messages · last activity 7/12/2026
The context object is created per request in the createContext method of the application. Here's how it works:
When a request comes in, Koa's callback() method [lib/application.js:L164-L180] sets up a handleRequest function that creates a new context for each request:
const handleRequest = (req, res) => {
const ctx = this.createContext(req, res)
// ... context is then passed to handleRequest
}
The actual context creation happens in the createContext method [lib/application.js:L213-L232]. This method:
- Creates the context object from the application's context prototype using
Object.create(this.context) - Creates request and response objects by extending Koa's request and response prototypes with
Object.create() - Links everything together by setting cross-references:
- The context stores references to
request,response,app, and the original Nodereq/res - The request and response objects store references back to the context, each other, and the app
- The context stores references to
- Initializes request metadata like
originalUrlfrom the Node request - Initializes context state as an empty object for middleware to use
This design allows Koa to wrap Node's native IncomingMessage and ServerResponse objects with a cleaner interface, as noted in the README [Readme.md:L107-L113]. Each middleware then receives this context object as its first parameter, allowing it to work with the request and response through Koa's abstractions rather than Node's objects directly.
FOLLOW_UPS:
- What is the context.state object used for?
- How does middleware composition flow through the context?
- What async local storage features does Koa provide?
Want to ask your own question?
Open chat for koajs/koaPublic Q&A. Generated by RepoPilot from the actual source of koajs/koa. AI answers can be incomplete or stale — verify before relying on them.