Context
NileContext provides access to request context, session data, and shared resources throughout your application.
Accessing Context
The context is passed as the second parameter to your action handler:
You can also use getContext() to access context from anywhere:
What's in Context
Accessing Resources
Resources are provided at server startup and available via context:
Session Management
Store and retrieve session data per interface:
Type-Safe Context
Pass a generic to get type safety for your database:
Example: Full Context Usage
Why a Single Context?
NileContext is a server-level singleton. One instance is shared across all interfaces. But per-request data is isolated via AsyncLocalStorage, so concurrent requests never interfere with each other.
The design splits into two layers:
- Server-level (shared):
resources(logger, database, cache) and the general-purpose_storemap are shared across all requests. Set once at boot, available everywhere. - Request-level (isolated): Interface contexts (
rest,ws,rpc) andsessionsare scoped per-request viaAsyncLocalStorage. Each request gets its ownRequestStore. Concurrent requests never see each other's Hono context or session data.
This is intentional:
- No race conditions. Two simultaneous REST requests won't overwrite each other's session or Hono context
- Simplicity. One context object, no request-scoped DI containers. Per-request isolation is handled transparently
- Composition. Hooks that reference other actions share the same request scope through AsyncLocalStorage continuations
- Resource sharing. Database connections, loggers, and caches are attached once at boot and available everywhere
Server Configuration with Resources
Pass resources when creating the server: