Skip to main content

Scopes

Grouping routes logically

Actix 4.9+ 4 min read

# Scopes

As your application grows, managing routes at the top-level App becomes unwieldy. Scopes allow you to group related routes under a common path prefix and share state or middleware among them.

#Defining a Scope

You create a scope using web::scope("/prefix"). All routes added to this scope will be prefixed with /prefix.

code_blocksrust
use actix_web::{web, App};

// Routes will be /api/users and /api/posts
let scope = web::scope("/api")
    .route("/users", web::get().to(get_users))
    .route("/posts", web::get().to(get_posts));

#Shared Resources

Scopes can have their own application state and middleware, which is only applied to routes within that scope. This is extremely useful for applying authentication middleware exclusively to an /admin scope.

Was this page helpful?

Reference Implementation

The following code snippet demonstrates the authoritative pattern for this documentation.

src/main.rs
1use actix_web::{web, App, HttpServer, Responder};
2
3async fn v1_status() -> impl Responder { "V1 OK" }
4async fn v2_status() -> impl Responder { "V2 OK" }
5
6#[actix_web::main]
7async fn main() -> std::io::Result<()> {
8 HttpServer::new(|| {
9 App::new()
10 .service(
11 web::scope("/v1")
12 .route("/status", web::get().to(v1_status))
13 )
14 .service(
15 web::scope("/v2")
16 .route("/status", web::get().to(v2_status))
17 )
18 })
19 .bind(("127.0.0.1", 8080))?
20 .run()
21 .await
22}
Was this page helpful?