Expand description
Request Context: typed fields that travel with a request to every service it reaches (for example, the authenticated user).
Declare each field once in the application as a module-level static with a
string literal name and value type so Encore can parse it statically:
use encore::reqctx::Field;
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Clone)]
pub struct User {
pub id: String,
pub email: String,
}
/// The authenticated user for a request, set by the gateway.
pub static CURRENT_USER: Field<User> = Field::new("user");Gateway middleware attaches fields to forwarded requests using set_field
in on_request (encore::gateway), and downstream services read them while
handling requests:
async fn orders() -> Result<(), encore::Error> {
let Some(user) = CURRENT_USER.get() else {
return Err(encore::Error::unauthenticated("not signed in"));
};
// …load orders for user.id…
Ok(())
}A service can also set or clear fields for nested operations and outbound service calls:
let system = User { id: "system".into() };
CURRENT_USER.scope(&system, billing_invoices())?.await;Another service (even in a different language) can bind an existing field by
name with Field::named("user").
§Context propagation
Fields live inside opentelemetry::Context
alongside the trace, so they propagate across .await points with
FutureExt::with_context.
Tasks spawned with tokio::spawn do not inherit the current context
automatically; wrap them with fut.with_current_context() to preserve both
tracing and Request Context fields.
§Trust model
External clients cannot set Request Context fields. Encore strips the underlying headers at every public entry point and cryptographically signs them between containers, so services can trust field values from other services in the application.
§Extracting and injecting headers
extract reads Request Context fields from incoming request headers into
a context. inject writes context fields onto outgoing request headers;
only call it for requests to other Encore services in the same application,
never for external third-party URLs. Pub/Sub messages automatically carry
any set fields declared with Field::pubsub into their subscribers’
contexts.
§Size limits
Each field is encoded as base64url JSON in its own header, so values must be
compact: at most 4 KiB per field (1 KiB for fields marked with
Field::pubsub), and at most 8 KiB across all fields on a request.
Exceeding a limit fails immediately at the call site that sets the field.
§Errors
Setting a field returns this module’s Error if serialization fails or a
size limit is exceeded. It does not automatically convert into
encore::Error; map it to an appropriate error code at the
call site.
Structs§
- Field
- A typed Request Context field serialized as JSON.
Enums§
- Error
- Error returned when setting a Request Context field fails. See the module documentation.
- Size
Error - A value too big to set.