Getting Started
Core Concepts
Built-In Middleware
Advanced Features
Troubleshooting
The Context object is the heart of every request in this framework. It acts as a bridge between the incoming HTTP request and the outgoing response, providing you with tools to read environment variables, manage request data, and construct sophisticated HTTP responses.
Whenever a handler function is triggered (such as inside app.get or app.use), the first argument provided is this Context object.
The Context object provides the following primary functionalities:
c.json(), c.text(), c.html(), and c.newResponse() make it simple to return data with the correct headers and status codes.c.set() and c.get() to pass data between middleware and your final route handlers.c.env.c.req to read headers, queries, and body content.You can respond with various data types using built-in methods.
app.get('/hello', (c) => {
// Returns application/json
return c.json({ message: 'Hello World' });
});
app.get('/plain', (c) => {
// Returns text/plain
return c.text('Hello World');
});Before returning your response, you can chain method calls to modify the HTTP response.
app.get('/custom', (c) => {
c.header('X-Custom-Header', 'Value');
c.status(201);
return c.text('Created');
});Context methods allow you to pass information from middleware into your application logic using keys.
// Middleware to set a value
app.use('*', async (c, next) => {
c.set('user-id', '12345');
await next();
});
// Accessing that value later
app.get('/profile', (c) => {
const userId = c.get('user-id');
return c.text(`User ID is ${userId}`);
});Tip
You can extend the ContextVariableMap interface in your project to get type safety for your custom keys when using c.get() and c.set().
Warning
Once a response has been finalized (e.g., returned from the handler), subsequent attempts to change headers via c.header() may lead to unexpected behavior. Set your headers before returning the final response.
Note
Use c.res to inspect the response state, but prefer using the dedicated return methods like c.json() or c.text() to build your final response object.
The standard lifecycle of a request through the Context object follows this pattern: