Skip to main content

Nested Routes

Complex routing structures

Actix 4.9+ 5 min read

# Nested Routes

While scopes are the standard way to nest configurations, Actix Web also allows you to configure routes dynamically using the configure() method. This pattern is excellent for modularizing your application.

#The Configure Pattern

You can create a configuration function that takes a &mut web::ServiceConfig. This function can then register routes, scopes, and state.

code_blocksrust
use actix_web::{web, App, HttpResponse};

fn user_config(cfg: &mut web::ServiceConfig) {
    cfg.service(
        web::scope("/users")
            .route("/{id}", web::get().to(|| async { HttpResponse::Ok() }))
    );
}

// In App setup:
// App::new().configure(user_config)

This allows you to split your routing configuration across multiple files and modules, keeping your main.rs clean.

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, HttpResponse};
2
3fn admin_routes(cfg: &mut web::ServiceConfig) {
4 cfg.route("/dashboard", web::get().to(|| async { HttpResponse::Ok().body("Admin Dashboard") }));
5}
6
7#[actix_web::main]
8async fn main() -> std::io::Result<()> {
9 HttpServer::new(|| {
10 App::new()
11 .service(
12 web::scope("/admin")
13 .configure(admin_routes)
14 )
15 })
16 .bind(("127.0.0.1", 8080))?
17 .run()
18 .await
19}
Was this page helpful?