Web Application State
Application state makes your services and configuration available throughout
a web application. A web::App has an application state type and usually
inherits its value from the surrounding server or service pipeline. Handlers,
extractors, filters, middleware, and error responses can all use that value.
ntex distinguishes two kinds of state:
- Application state is the state supplied by the service pipeline. A
worker’s value is cloned for each connection, and handlers borrow that
connection’s clone. Data that must be shared between connections belongs
behind a shared handle such as
Rc. - Request-local state belongs to one request. It is owned by
WebRequest, can change type as the request moves through filters and middleware, and can be moved into a state-aware handler.
For worker initialization and process-wide versus worker-local data, see Worker and request state. For the underlying service-state model, see Service state.
The web::State Trait
Implement web::State to use your type as application state and choose its
error domain:
pub trait State: 'static {
type Error;
}
The trait has no methods. Its associated Error type defines the application’s
error domain. Handlers, filters, middleware, and fallback services use this
error type through WebError and WebResponseError.
Most applications can use DefaultError:
use ntex::web;
#[derive(Clone)]
struct ApplicationState {
greeting: String,
}
impl web::State for ApplicationState {
type Error = web::DefaultError;
}
web::State itself does not require Clone. State used with the built-in
HTTP server must implement it, though. ServerAppConfig::State requires
Clone, as does state passed to build_with().
HttpService clones the connection state when creating each connection’s
application service. You can use a non-Clone state type directly with an
application factory. You cannot pass it through these server paths.
Inheriting Worker State
Use web::server_with_config() to initialize state for each worker. It
creates one value per worker and passes it to that worker’s application
factory. The returned App uses the same state type:
use std::io;
use ntex::{SharedCfg, web};
/// State created independently for each worker.
#[derive(Clone)]
struct ApplicationState {
greeting: String,
}
impl web::State for ApplicationState {
type Error = web::DefaultError;
}
/// Process-wide factory used to create worker state.
struct ApplicationConfig;
impl ntex::server::ServerAppConfig for ApplicationConfig {
type State = ApplicationState;
async fn create(&self) -> io::Result<Self::State> {
Ok(ApplicationState {
greeting: "Hello".to_owned(),
})
}
}
async fn index(state: &ApplicationState, _request_state: ()) -> String {
state.greeting.clone()
}
#[ntex::main]
async fn main() -> io::Result<()> {
web::server_with_config(ApplicationConfig, async |_| {
web::App::new().route("/", web::get().to_with_state(index))
})
.bind("127.0.0.1:8080", SharedCfg::default())?
.run()
.await
}
Every request handled by a worker can access its state through the service
context. Each connection receives its own clone of the worker state. Put
values that all connections on a worker should share, such as caches or
counters, behind Rc. See
Worker-Local and Process-Wide
State
for details.
Design State for Cheap Cloning
Keep application state cheap to clone because each connection gets a clone. A small collection of handles avoids copying large data structures:
use std::{cell::RefCell, collections::HashMap, rc::Rc, sync::Arc};
use ntex::web;
#[derive(Clone)]
struct ApplicationState {
worker_cache: Rc<RefCell<HashMap<String, String>>>,
shared_settings: Arc<Settings>,
}
struct Settings {
service_name: String,
}
impl web::State for ApplicationState {
type Error = web::DefaultError;
}
Connections on the same worker share worker_cache. All workers can also
share the thread-safe shared_settings value. To share it, the configuration
factory must give each worker a clone of the same Arc.
Handlers receive &ApplicationState. To change data, you normally use a
client handle or an interior-mutable value. That value might use Cell,
RefCell, a lock, or an atomic.
Keep RefCell borrows short. Do not hold them across an .await: unrelated
work could try to borrow the same value and panic.
One Counter per Worker, One Counter for the Process
Suppose the notes API needs a request count for each worker and a total for
this server process. Use Rc<Cell<usize>> for the worker count and an
Arc<AtomicUsize> for the total. Create the Rc inside create(), but put
the Arc in the process-wide configuration so every worker clones the same
handle:
use std::{
cell::Cell,
io,
rc::Rc,
sync::{Arc, atomic::{AtomicUsize, Ordering}},
};
use ntex::{SharedCfg, web};
#[derive(Clone)]
struct Counters {
worker_hits: Rc<Cell<usize>>,
total_hits: Arc<AtomicUsize>,
}
impl web::State for Counters {
type Error = web::DefaultError;
}
struct CounterConfig {
total_hits: Arc<AtomicUsize>,
}
impl ntex::server::ServerAppConfig for CounterConfig {
type State = Counters;
async fn create(&self) -> io::Result<Counters> {
Ok(Counters {
worker_hits: Rc::new(Cell::new(0)),
total_hits: self.total_hits.clone(),
})
}
}
async fn count(state: &Counters, (): ()) -> web::HttpResponse {
let worker = state.worker_hits.get() + 1;
state.worker_hits.set(worker);
let total = state.total_hits.fetch_add(1, Ordering::Relaxed) + 1;
web::HttpResponse::Ok().json(&serde_json::json!({
"worker_hits": worker,
"total_hits": total,
}))
}
#[ntex::main]
async fn main() -> io::Result<()> {
let config = CounterConfig {
total_hits: Arc::new(AtomicUsize::new(0)),
};
web::server_with_config(config, async |_| {
web::App::new().route("/count", web::get().to_with_state(count))
})
.workers(2)
.bind("127.0.0.1:8080", SharedCfg::default())?
.run()
.await
}
Each connection clones Counters, but cloning the two handles does not
reset their contents. Connections assigned to one worker share its local
count. Connections assigned to another worker use a different local count,
while both update the same total. Here the counter measures calls to
/count, not all traffic; move the increment into an application filter
when every request should count.
Ordering::Relaxed is enough for an independent statistic: the atomic
increment needs no relationship to other shared data. It does not turn the
two JSON fields into an atomic snapshot. Other workers can update the total
while this handler builds its response. A process-wide count also is not a
fleet-wide count; another server process has its own memory.
An Rc cannot cross worker threads. Capturing one in the outer server
factory will fail the factory’s Send requirement, and putting it in the
configuration will fail ServerAppConfig’s Send + Sync bounds. Creating it
inside create() is the intended way to get worker-local sharing. Conversely,
creating a new Arc inside each create() call gives separate counters,
not one global counter. Sharing depends on where you allocate the value,
not merely on which pointer type you choose.
For shared structured data, an Arc<Mutex<Cache>> can protect a cache used
across workers. Keep the critical section short and release its guard before
an .await; a standard mutex blocks the worker thread while waiting. A
worker-local Rc<RefCell<Cache>> avoids cross-thread locking, but each worker
has an independent cache and still needs short borrow scopes.
Database Pools and Other Client Handles
Treat a database pool as a long-lived application dependency, not something
to create for each request. Place the driver’s pool handle in your state and
borrow it from a to_with_state() handler. The handler can then await a query
through the pool without rebuilding the connection configuration.
Choose its placement from the driver’s actual guarantees. A thread-safe,
cheaply cloned pool can be created once and supplied to each worker through
the configuration. A thread-local client belongs in the worker’s create()
method. If each worker creates its own pool, budget the database connection
limit across all those pools rather than treating a per-pool limit as a
process limit. The framework does not select a database driver or create a
pool for you.
Do asynchronous connection checks or other fallible startup work in
ServerAppConfig::create(), which returns io::Result. Connection-level
state cloning should copy a handle, not open a new pool. A plain Vec<Note>
or HashMap field is cloned by value, so putting one directly in a Clone
state type does not create shared storage. Wrap mutable in-memory storage in
the appropriate shared handle before passing it to the server.
Accessing Application State in Handlers
Use Route::to_with_state() when a handler needs direct access to state.
For a resource route without a method guard, use Resource::to_with_state().
The handler receives its arguments in this order:
- A shared reference to the application state.
- The request-local state.
- Any request extractors.
use ntex::web;
#[derive(Clone)]
struct ApplicationState {
service_name: &'static str,
}
impl web::State for ApplicationState {
type Error = web::DefaultError;
}
async fn user(
state: &ApplicationState,
_request_state: (),
user_id: web::types::Path<u32>,
) -> String {
format!("{} user {}", state.service_name, user_id.into_inner())
}
fn main() {
let app = web::App::<ApplicationState>::new().route(
"/users/{user_id}",
web::get().to_with_state(user),
);
}
Filters, middleware, and lower-level services access application state through
their service Ctx.
Handlers registered with Route::to() receive only request extractors. Use
to() when the handler does not need application or request-local state.
Extractors receive a shared reference to application state through
FromRequest. Your custom extractors can use it to access application
services or configuration.
Extractors do not receive request-local state. Only to_with_state() supplies
that value, as a separate handler argument.
Sharing State with Filters and Middleware
The handler does not need to own every cross-cutting operation. A resource
filter can update a request counter, while application middleware labels the
response. In a from_fn() closure, next.st() is the application’s state;
req.st() would be the request-local value instead.
This test shows all three access paths together:
use std::{cell::Cell, convert::Infallible, rc::Rc};
use ntex::http::header::{HeaderName, HeaderValue};
use ntex::web::{self, middleware::{Next, from_fn}, test, WebRequest};
#[derive(Clone)]
struct ApplicationState {
name: &'static str,
hits: Rc<Cell<usize>>,
}
impl web::State for ApplicationState {
type Error = web::DefaultError;
}
async fn count_request(
state: &ApplicationState,
req: WebRequest<()>,
) -> Result<WebRequest<()>, Infallible> {
state.hits.set(state.hits.get() + 1);
Ok(req)
}
async fn index(state: &ApplicationState, (): ()) -> String {
format!("{} requests: {}", state.name, state.hits.get())
}
#[ntex::test]
async fn layers_use_the_same_state() {
let state = ApplicationState {
name: "notes",
hits: Rc::new(Cell::new(0)),
};
let app = test::init_service_st(
state.clone(),
web::App::new()
.middleware(from_fn(async |req, next: Next<'_, _, ApplicationState>| {
let name = next.st().name;
let mut response = next.call(req).await?;
response.headers_mut().insert(
HeaderName::from_static("x-application"),
HeaderValue::from_static(name),
);
Ok(response)
}))
.service(
web::resource("/")
.filter(count_request)
.route(web::get().to_with_state(index)),
),
)
.await;
let response = test::call_service(
&app, test::TestRequest::get().uri("/").to_request(),
).await;
assert_eq!(response.headers().get("x-application").unwrap(), "notes");
assert_eq!(test::read_body(response).await, "notes requests: 1");
assert_eq!(state.hits.get(), 1);
}
The Next annotation gives Rust the state type it needs for field access.
For a full middleware service, use ctx.st() instead. You are borrowing the
same application state in each case, not retrieving values from
HttpRequest extensions. See
Filters and Middleware for deciding which layer should own
the operation.
Request-Local State
Use request-local state for data produced while processing a request, such as authentication details. It belongs to one request. Application state is long-lived and shared across requests.
WebRequest carries request-local state. The type parameter in
WebRequest<RequestState> is the state type. An ordinary web request starts
with ().
A filter or middleware can keep the value or mutate it through
WebRequest::st_mut(). To replace it with another type, use
WebRequest::map_state(). A handler registered with to_with_state()
receives the result as its second argument:
use std::convert::Infallible;
use ntex::web::{self, WebRequest};
#[derive(Clone)]
struct ApplicationState {
service_name: &'static str,
}
impl web::State for ApplicationState {
type Error = web::DefaultError;
}
async fn index(state: &ApplicationState, user_id: usize) -> String {
format!("{} user {user_id}", state.service_name)
}
fn main() {
let app = web::App::<ApplicationState>::new()
.filter(async |req: WebRequest<()>| {
// Authentication could produce this request-local value.
Ok::<_, Infallible>(req.map_state(|()| 42usize))
})
.route("/", web::get().to_with_state(index));
}
Request-local state moves through the filter and middleware chain. Changing
the state also changes the WebRequest type expected by the next service.
Rust checks this pipeline at compile time. For example, a handler expecting
AuthInfo can only follow a filter or middleware that produces
WebRequest<AuthInfo>.
Inside filters and middleware, WebRequest::st() returns request-local
state. Use WebRequest::st_mut() for mutable access. Application state comes
from the service context.
map_state() consumes the previous value. If later stages need some of the
old information, include it in the new state:
struct Authenticated {
user_id: usize,
}
struct Validated {
user: Authenticated,
request_id: String,
}
Application filters affect every route. A scope or resource filter can create state needed only by that part of the application. Unrelated handlers then have no dependency on that state.
Request-local state is not stored in HttpRequest extensions. Request
extractors cannot read it. Use to_with_state() when the final handler needs
the value. A handler registered with to() ignores and drops it.
Complete web application state example
Typed Web Configuration Is Separate
Use WebAppConfig for HTTP-facing configuration, especially extractor
limits and settings read from a request. Populate its typed value store with
set_value().
These values are separate from application service state. Service state such
as AppState<T> is not part of the store. Keep services and resources that
participate in the service lifecycle in application state. Store typed web
configuration in WebAppConfig.
- Read configuration values through
HttpRequest::app_value()orWebRequest::app_value(). to_with_state()does not pass them as its first argument.- Values must be
Send + Sync. Worker-local state may containRcandRefCellinstead. - The store holds one value for each concrete type.
Here, the handler reads a configured limit from the request:
use ntex::web::{self, App, HttpRequest, WebAppConfig};
struct Limits {
max_items: usize,
}
async fn limits(req: HttpRequest) -> String {
let max_items = req
.app_value::<Limits>()
.map_or(100, |limits| limits.max_items);
format!("maximum items: {max_items}")
}
let config = WebAppConfig::new().set_value(Limits { max_items: 50 });
let app = App::default()
.with_config(config)
.route("/limits", web::get().to(limits));
Supplying Fixed State with .build_with()
Use AppServices::build_with() when your web application needs its own
state and the surrounding HTTP or server pipeline uses different state or
none.
The application builder becomes AppServices after the first call to
route(), service(), configure(), or default_service(). See
Builder Order. Finish building it with either
build() or build_with().
build() uses state from the surrounding service pipeline.
build_with(state) gives the application its own fixed state. The outer
pipeline can then use a different state type:
use ntex::web::{self, HttpResponse};
#[derive(Clone)]
struct ApplicationState {
greeting: &'static str,
}
impl web::State for ApplicationState {
type Error = web::DefaultError;
}
async fn index(state: &ApplicationState, _request_state: ()) -> HttpResponse {
HttpResponse::Ok().body(state.greeting)
}
fn main() {
let app = web::App::<ApplicationState>::new()
.route("/", web::get().to_with_state(index))
.build_with::<()>(ApplicationState {
greeting: "Hello",
});
}
In this standalone example, () is the outer pipeline’s state type. It is
normally inferred when you pass the application factory to HttpService.
Application state must implement Clone. build_with() clones it when
creating application service instances.
build_with() replaces the application’s state without adding another state
layer. Code outside the application keeps using the outer state. Web handlers
and application middleware receive the fixed state.
Use server_with_config() for asynchronous per-worker initialization or state
that should be recreated with a worker. Use build_with() to embed a ready
value in an application factory, especially when the surrounding HTTP pipeline
uses another state type.
The AppState<T> Wrapper
Use AppState<T> to wrap application state when you use DefaultError.
You do not need to write a web::State implementation.
The wrapper accepts any 'static T and dereferences to the wrapped value.
It implements Clone and Default whenever T does:
use ntex::web;
#[derive(Clone)]
struct Settings {
service_name: &'static str,
}
fn main() {
let state = web::AppState::new(Settings {
service_name: "users",
});
assert_eq!(state.service_name, "users");
assert_eq!(state.st().service_name, "users");
}
Use a dedicated state type and implement web::State directly when you need a
custom error type or other state-specific behavior.
AppState<T> does not change how values are cloned or shared. If T::clone()
copies a plain field, connections receive separate copies. If it clones an
Rc or Arc, they share the value behind that handle.
Testing Stateful Routes
Use test::init_service_st() to test an application with an explicit state
value. Keep a clone of a shared handle if your test needs to inspect what the
handler changed:
use std::{cell::Cell, rc::Rc};
use ntex::web::{self, test};
#[derive(Clone)]
struct ApplicationState {
hits: Rc<Cell<usize>>,
}
impl web::State for ApplicationState {
type Error = web::DefaultError;
}
async fn index(state: &ApplicationState, (): ()) -> &'static str {
state.hits.set(state.hits.get() + 1);
"ok"
}
#[ntex::test]
async fn state_is_used() {
let state = ApplicationState {
hits: Rc::new(Cell::new(0)),
};
let service = test::init_service_st(
state.clone(),
web::App::<ApplicationState>::new()
.route("/", web::get().to_with_state(index)),
)
.await;
let request = test::TestRequest::get().uri("/").to_request();
let _response = test::call_service(&service, request).await;
assert_eq!(state.hits.get(), 1);
}