Overview
The Context object (c) is passed to every handler and middleware function. It provides access to the request, response, environment variables, and utility methods for building responses.
From src/context.ts:293-299:
Request Access
Access the request object through c.req:
From src/context.ts:364-369:
Response Methods
The Context provides several methods for returning responses:
Text Response
Return plain text:
From src/context.ts:670-694:
JSON Response
Return JSON data:
From src/context.ts:696-721:
HTML Response
Return HTML content:
From src/context.ts:723-733:
Redirect
Redirect to another URL:
From src/context.ts:735-762:
Body Response
Return raw body data:
From src/context.ts:643-668:
From src/context.ts:500-527:
Status Code
Set HTTP status code:
From src/context.ts:529-531:
Context Variables
Store and retrieve values during request processing:
Setting Variables
From src/context.ts:533-556:
Getting Variables
From src/context.ts:558-580:
Accessing Variables with .var
Read-only access to all variables:
From src/context.ts:582-602:
Type-Safe Variables
Define variable types for type safety:
Environment Variables
Access environment bindings (Cloudflare Workers, etc.):
From src/context.ts:302-315:
Execution Context
Access the execution context (for Cloudflare Workers):
From src/context.ts:385-397:
From src/context.ts:29-52:
Rendering
Custom Renderer
Set a custom renderer for templating:
From src/context.ts:437-497:
Error Property
Access errors thrown in middleware:
From src/context.ts:317-333:
Response Access
Access or set the response:
From src/context.ts:399-434:
Not Found Handler
Trigger the not found handler:
From src/context.ts:764-779:
Best Practices
- Use TypeScript to define environment and variable types
- Set context variables in middleware for cross-handler data sharing
- Use appropriate response methods (
json, text, html) for content types
- Access
c.req for all request data instead of the raw request object
- Leverage
c.executionCtx for background tasks in Cloudflare Workers
Don’t modify the raw request object. Use Context methods and properties for all request/response operations.