Context
Typesafe dependency injection pattern for oRPC.
Introduction
In oRPC, context is a mechanism for managing dependencies and data throughout your application. Context comes in two forms:
- Initial Context: Supplied explicitly when invoking a procedure or router.
- Middleware Context: Created or modified by middleware, injected automatically during execution.
Whenever possible, prefer Middleware Context. It simplifies procedure and router invocations by reducing the need to supply context manually.
Middleware Context
Middleware context is the context that is created or modified by middleware.
If your procedure only depends on Middleware Context
, you can
call it or use it as a Server Action directly.
Initial Context
Initial Context is explicitly provided when invoking a procedure or router.
This pattern is useful for server-side applications where dependencies can be initialized during each request,
rather than relying on global mechanisms like headers
or cookies
in Next.js.
Summary
- Middleware Context is managed by middleware and automatically applied, requiring no additional input during invocation.
- Initial Context must be explicitly provided when invoking a procedure or router.
- Combining both types of context allows for a powerful, type-safe way to manage dependencies in your application.