# How do I share state between actix-web handlers and test them?
Source: https://ruststudio.org/community/t/188/how-do-i-share-state-between-actix-web-handlers-and-test-them
Author: Ruststudio Team (staff) | Published: 2026-12-05 | Updated: 2026-12-05 | Checked with: rustc 1.93.0, actix-web 4.21.0, tokio 1.54.1, Windows 11
Category: Help and questions | Kind: FAQ | Tags: actix-web, state, testing, web | Views: 0

## Short answer
Create the state once with web::Data::new before HttpServer::new, clone the Data into each worker with app_data, and read it in handlers as web::Data<T>. For tests, build the App with actix_web::test::init_service and call it with TestRequest, no network port needed.

## Answer
## Answer
`HttpServer::new` calls its closure once per worker thread. State created **inside** the closure would therefore exist once per worker, and each worker would count separately. Create it outside and clone the `web::Data` (a shared pointer) into each one:

```rust title=src/main.rs
use actix_web::{get, test, web, App};
use std::sync::Mutex;

struct Counter { hits: Mutex<u32> }

#[get("/hit")]
async fn hit(data: web::Data<Counter>) -> String {
    let mut n = data.hits.lock().unwrap();
    *n += 1;
    format!("hit {n}")
}

#[actix_web::main]
async fn main() {
    // Create the state once, outside the factory closure. HttpServer::new calls the closure once per worker,
    // so state created inside it would be one copy per worker.
    let data = web::Data::new(Counter { hits: Mutex::new(0) });
    let app = test::init_service(App::new().app_data(data.clone()).service(hit)).await;
    for _ in 0..2 {
        let body = test::call_and_read_body(&app, test::TestRequest::get().uri("/hit").to_request()).await;
        println!("{}", String::from_utf8_lossy(&body));
    }
    println!("seen from outside: {}", data.hits.lock().unwrap());
}
```

```text
hit 1
hit 2
seen from outside: 2
```

- Both requests went through the same counter (`hit 1`, `hit 2`), and the program saw the final value `2` from outside.
- The `Mutex` is inside the state because `web::Data` gives shared, read-only access.
- `test::init_service` builds the `App` without a network port; `call_and_read_body` sends a `TestRequest` and returns the body. The same functions work for status codes and headers (see `test::call_service` in the thread on routes and JSON).

```toml title=Cargo.toml
actix-web = "4.21.0"
```

For a real server the sequence is `let data = web::Data::new(...); HttpServer::new(move || App::new().app_data(data.clone()) ...)`.

## Common mistakes
- Creating the state in the closure and wondering why counters differ between requests.
- Holding a `std::sync::Mutex` guard across an `.await` in a handler. Finish with the lock before awaiting.
- Using the wrong type in the handler: `web::Data<Counter>` must match the type given to `app_data` exactly.

## Related questions
### Why is the counter behind a Mutex?
`web::Data<T>` hands out shared references, so changing the value needs interior mutability such as `Mutex`, `RwLock` or an atomic.

## Sources
- actix-web, `web::Data`: https://docs.rs/actix-web/4.21.0/actix_web/web/struct.Data.html (read 2026-12-05)
- actix-web, `test`: https://docs.rs/actix-web/4.21.0/actix_web/test/index.html (read 2026-12-05)
