dust

Routing

Basic routing

When someone visits a page in your application or submits a form, dust-framework looks at the request's method and URI, such as GET /greeting, and finds the route that matches it. The route tells dust-framework which code should handle the request. The simplest route pairs a URI with a closure that returns the response:

rust
use dust::prelude::*;pub fn routes(route: &mut Router) {    route.get("/greeting", async || "Hello World");}

A closure may also ask for what it needs through its arguments, and dust-framework provides them when the request comes in. For example, a closure that takes a User receives the user whose ID is in the URI, so a request to /users/1 returns the name of user 1. If no user has that ID, dust-framework responds with a 404 page instead:

rust
use crate::models::User;pub fn routes(route: &mut Router) {    route.get("/users/{user}", async |user: User| user.name);}

Closures are handy for a quick page, but as your application grows, a route file full of them gets hard to read, since every page's logic sits in one place. So most routes point at a handler instead: an async function in its own module under src/http/handlers. The route file stays a short list of URIs, and each handler holds the code for one page. A handler's arguments are extractors, such as the request, a service, or route parameters, and it returns a response:

rust
use crate::http::handlers::users;pub fn routes(route: &mut Router) {    route.get("/users", users::index);    route.get("/users/{user}", users::show);    route.post("/users", users::store);}

The default route files

A route file is a function that receives a Router. Your application keeps its route files in src/routes and registers them in src/app.rs:

rust
Application::configure()    .with_routing(|routing, _| {        routing            .web(routes::web::routes)            .api(routes::api::routes);    })

For most applications, you'll start by defining routes in src/routes/web.rs. Routes registered with web run within the web middleware group, which provides sessions, encrypted cookies, and CSRF protection.

If other applications, scripts, or services will call your application's API, define those routes in src/routes/api.rs. Routes registered with api are stateless and run within the api middleware group. dust-framework adds /api to the start of every URI in src/routes/api.rs, so a /users route defined in that file responds to /api/users. You may change the prefix with api_prefix:

rust
routing.api(routes::api::routes).api_prefix("/api/v1");

To register a route file that runs neither group, use routes. Its routes get no session, no CSRF check, and no prefix, so you choose their middleware yourself:

rust
// src/app.rs.with_routing(|routing, _| {    routing        .web(routes::web::routes)        .api(routes::api::routes)        .routes(routes::webhooks::routes);})
rust
// src/routes/webhooks.rsuse dust::prelude::*;use crate::http::handlers::webhooks;use crate::http::middleware::verify_stripe_signature;pub fn routes(route: &mut Router) {    route.middleware(verify_stripe_signature).group(|route| {        route.post("/webhooks/stripe", webhooks::stripe);    });}

You may call web, api, and routes more than once, to split your routes across several files.

The closure's second argument is your application's configuration, so you may register some routes only in some environments:

rust
.with_routing(|routing, config| {    routing.web(routes::web::routes);    if config.app.debug {        routing.web(routes::debug::routes);    }})

Available router methods

The router has a method for each HTTP verb:

rust
route.get(uri, handler);route.post(uri, handler);route.put(uri, handler);route.patch(uri, handler);route.delete(uri, handler);route.options(uri, handler);

A GET route also responds to HEAD. To respond to several methods, use on. To respond to every method, use any:

rust
use dust::http::Method;route.on(&[Method::GET, Method::POST], "/search", search::show);route.any("/webhooks/stripe", webhooks::stripe);

Redirect routes

A route that only redirects to another URI doesn't need a handler. Use redirect for a 302, or permanent_redirect for a 301:

rust
route.redirect("/here", "/there");route.permanent_redirect("/here", "/there");

Redirects are especially handy when you rename part of your site. Say your blog's posts moved from /posts to /articles. Visitors and search engines still have the old links, so redirect them to the new ones. The destination may use the same parameters as the old URI:

rust
route.permanent_redirect("/posts/{post}", "/articles/{post}");route.permanent_redirect("/blog/{*slug}", "https://blog.example.com/{*slug}");

The second redirect uses a wildcard parameter, {*slug}, which captures the rest of the path, slashes and all. So /blog/2026/hello-world redirects to https://blog.example.com/2026/hello-world, which is handy when you move a whole section of your site to another domain.

A redirect route has no handler, so you can't link to it with route!. Keep the old URI in a comment or a constant if other parts of your application still build that URL, and update those call sites when you remove the route.

View routes

Some pages have no logic behind them, such as an about page or a pricing page whose content lives entirely in its template. Writing a handler that only renders the page would add a function with nothing in it, so the route may render a view itself:

rust
route.view("/about", "about");route.view("/pricing", "pricing");

The view receives only the data shared with every view. For more data, such as a list of plans from your database, write a handler that returns the view instead. View routes and redirect routes have no handler to link to, so link to them by their URI.

Listing your routes

The route:list console command gives you an overview of every route your application defines:

shell
dust route:list

You may also add a few options to the command. -v shows each route's middleware, and --json prints the list as JSON for scripts and other tools. To see only some of your routes, filter the list by URI with --path=admin, or by handler with --handler=users.

Route parameters

To capture a segment of the URI, such as a user's ID, define a route parameter in braces:

rust
route.get("/users/{user}", users::show);route.get("/posts/{post}/comments/{comment}", comments::show);

Handlers receive parameters with the Params extractor, which parses each one into the type you give it, such as u64 or String. Several parameters arrive as a tuple, in the order the URI names them:

rust
use dust::prelude::*;pub async fn show(Params(id): Params<u64>) -> String {    format!("User {id}")}pub async fn show_comment(Params((post, comment)): Params<(u64, u64)>) -> String {    format!("Comment {comment} on post {post}")}

If a parameter doesn't parse into its type, such as /users/taylor for a u64, the request gets a 404 and your handler never runs.

A wildcard parameter, written as {*path}, captures the rest of the URI, including its slashes:

rust
route.get("/files/{*path}", files::show);

When several routes match a URI, dust-framework compares them one segment at a time. A fixed segment such as create beats a parameter such as {user}, and a parameter beats a wildcard such as {*path}. So /users/create reaches a /users/create route even if you registered /users/{user} first.

Optional parameters

Add ? to a parameter's name to make its segment optional. Optional parameters must come at the end of the URI:

rust
route.get("/archive/{year?}/{month?}", archive::show);

This route matches /archive, /archive/2026, and /archive/2026/10. Give each optional parameter an Option type, and choose defaults in your handler. This handler receives the parameters in a struct, which keeps them named and organized, so params.year can't be mixed up with params.month:

rust
use dust::prelude::*;#[derive(Deserialize)]pub struct ArchiveParams {    year: Option<u16>,    month: Option<u8>,}pub async fn show(Params(params): Params<ArchiveParams>) -> String {    match params.year {        Some(year) => format!("Archive for {year}, month {:?}", params.month),        None => "All archives".to_owned(),    }}

A tuple works too, and is shorter when you have one or two parameters. For example, Params<(u16, Option<u8>)> fits /archive/{year}/{month?}.

Restricting parameter values

A parameter that doesn't parse into its type is a 404, so the type you choose is also the parameter's constraint. To accept only a fixed set of values, such as the categories of a store, receive the parameter as an enum:

rust
use dust::prelude::*;#[derive(Deserialize)]#[serde(rename_all = "lowercase")]pub enum Category {    Movies,    Songs,    Paintings,}pub async fn show(Params(category): Params<Category>) -> &'static str {    match category {        Category::Movies => "Movies",        Category::Songs => "Songs",        Category::Paintings => "Paintings",    }}

With this handler on /categories/{category}, /categories/songs reaches the handler and /categories/podcasts is a 404.

Models in route parameters

When a parameter holds a model's key, such as the post's ID in /posts/{post}, take the model as a handler argument. Before your handler runs, dust-framework automatically retrieves the post with that ID from your database and passes it in. If no post has that ID, dust-framework responds with a 404, and your handler never runs:

rust
use crate::models::Post;pub async fn show(post: Post) -> String {    post.title}

To find the post by another field, such as its slug, name the field after a colon, as in /blog/{post:slug}. To learn more about finding models by something other than their ID, check out the models guide's section on customizing the key.

To find a model outside a handler's arguments, such as in middleware, call request.model with the parameter's name:

rust
let post: Post = request.model("post").await?;

A handler may take a model and other route parameters together. Take the model as its own argument, and the other parameters with Params. A struct works best here, because it only names the parameters you want and leaves out the model's. For example, for a route on /posts/{post}/comments/{sort}:

rust
use dust::prelude::*;use crate::models::Post;#[derive(Deserialize)]pub struct CommentParams {    sort: String,}pub async fn index(post: Post, Params(params): Params<CommentParams>) -> String {    format!("Comments on {}, sorted by {}", post.title, params.sort)}

Linking to routes

You link to a route by its handler, the function you registered it with. In a handler or middleware, pass the handler and any parameters to route! or redirect! (both are in the prelude):

rust
let url = route!(users::show, 1)?; // http://localhost/users/1let response = redirect!(users::show, 1);

You may pass a model in place of its ID. dust-framework fills the parameter with the model's route key, which is its ID unless you've customized the key:

rust
let url = route!(posts::show, &post)?; // http://localhost/posts/42let response = redirect!(posts::show, &post);

For a route with several parameters, pass them in the order the URI names them, or pass them by name with key = value:

rust
// http://localhost/posts/42/comments/7let url = route!(comments::show, &post, &comment)?;

Because your links point at handlers rather than URIs, you may change a route's URI without touching any code that links to it. If you rename or remove a handler, the compiler shows you every route! and redirect! call that still uses it.

If you need to generate a URL in a template, pass route the handler's path, written the way route:list prints it, followed by the route's parameters:

html
<a href="{{ route("posts::show", post) }}">{{ post.title }}</a>

To learn more about generating URLs, including adding query strings and creating signed URLs, check out the URL generation documentation.

Route groups

Route groups let many routes share attributes, such as a prefix or middleware, without repeating them on each route. You may also place a group inside another group. The inner group's prefix is added after the outer group's, and the inner group's routes run the middleware from both groups.

Prefixes

The prefix method adds a URI prefix to each route in the group. For example, you may want every admin route to start with /admin:

rust
route.prefix("/admin").group(|route| {    route.get("/users", admin::users::index); // Matches "/admin/users"...});

Middleware

To assign middleware to every route in a group, call middleware before group. You may combine it with other attributes:

rust
use dust::auth::Authenticate;route.prefix("/admin").middleware(Authenticate).group(|route| {    route.get("/", admin::dashboard);    route.get("/reports", admin::reports);});

You may also assign middleware to a single route. Inside a group, the route runs its own middleware after the group's middleware. Here, every admin page requires a logged-in user, and the billing page also requires a verified email address:

rust
use dust::auth::{Authenticate, RequireVerifiedEmail};route.prefix("/admin").middleware(Authenticate).group(|route| {    route.get("/", admin::dashboard);    route.get("/billing", admin::billing).middleware(RequireVerifiedEmail);});

Sometimes one route in a group shouldn't run one of the group's middleware. Call without_middleware on that route. This status page lives under /admin, but anyone may see it:

rust
route.prefix("/admin").middleware(Authenticate).group(|route| {    route.get("/", admin::dashboard);    route.get("/status", admin::status).without_middleware::<Authenticate>();});

without_middleware also works on middleware from the web and api groups, such as CSRF protection, and on a whole group when you call it before group. To learn more, check out the middleware guide's section on excluding middleware.

Domain routing

Use domain to restrict a group to a host. A domain may capture a part of the host as a parameter, such as each customer's account in a multi-tenant application:

rust
route.domain("admin.example.com").group(|route| {    route.get("/dashboard", admin::dashboard);});route.domain("{account}.example.com").group(|route| {    route.get("/users/{user}", users::show);});

The second group matches acme.example.com/users/42. Its handler receives the account from the domain along with the user from the path. Domain parameters come first:

rust
use dust::prelude::*;pub async fn show(Params((account, user)): Params<(String, u64)>) -> String {    format!("User {user} on the {account} account")}

Routes with a domain take precedence over routes without one. Among routes with a domain, the first one registered wins, so register specific hosts before patterns such as {account}.example.com.

[!WARNING] In production, dust-framework only answers requests for the host in your APP_URL and its subdomains. If a domain route uses another domain, such as example.org when your APP_URL is https://example.com, add that domain to your trusted hosts. Otherwise, dust-framework rejects its requests with a 400.

When you link to a route on one of these domains, pass the domain's parameters first, then the path's:

rust
let url = route!(users::show, "acme", 42)?; // http://acme.example.com/users/42

To learn more, check out the URL generation guide's section on domain parameters.

Head metadata

with_head gives a route or a group its head metadata, such as its title:

rust
use dust::head::{Head, Robots};route.get("/", welcome::show).with_head(Head::new().title("Welcome"));route.with_head(Head::new().robots(Robots::None)).prefix("/admin").group(|route| {    route.get("/dashboard", admin::dashboard).with_head(Head::new().title("Dashboard"));});

When a route and its group both set the same tag, such as the title, dust-framework uses the route's value. A handler can still change any tag for its own page by calling head::merge.

Resource routes

Most applications have models that need the same set of create, read, update, and delete (CRUD) routes. A photo gallery, for example, needs a page that lists your photos, a form to upload a new one, a page that shows a single photo, and routes to edit and delete it. Registering those seven routes for every model gets repetitive, so dust-framework can register them all at once. Write a module of handlers named after the actions, and register the module with resource!:

rust
use dust::routing::resource;use crate::http::handlers::photos;pub fn routes(route: &mut Router) {    resource!(photos);}

Each public function in photos that has an action's name gets that action's route:

Method URI Handler
GET /photos photos::index
GET /photos/create photos::create
POST /photos photos::store
GET /photos/{photo} photos::show
GET /photos/{photo}/edit photos::edit
PUT, PATCH /photos/{photo} photos::update
DELETE /photos/{photo} photos::destroy

A module without create or edit, such as an API module, gets only the other routes.

The routes are ordinary routes, so their handlers may take the photo as a model. dust-framework finds the photo by the {photo} parameter, or responds with a 404, and you may link to the route with the model itself:

rust
// src/http/handlers/photos.rsuse crate::models::Photo;pub async fn show(photo: Photo) -> String {    photo.title}
rust
let url = route!(photos::show, &photo)?; // http://localhost/photos/42

The resource's name comes from the module's name, with underscores written as dashes, so blog_posts routes /blog-posts/{blog_post}. The parameter is the singular of the name, so photos has {photo} and categories has {category}.

Register only some actions

Sometimes you only want some of the resource's routes. Invoices, for example, may be listed and viewed but never edited, so you may list the actions you want, the same way you'd write a use declaration. When you want most of the actions, it's shorter to name the ones to leave out with except. Here, photos get every route except the create and edit forms:

rust
use dust::routing::{Action, resource};resource!(invoices::{index, show});resource!(photos).except([Action::Create, Action::Edit]);

Nest a resource in its parent's module

Some resources only make sense inside another one. For example, every comment in a photo gallery is posted on a photo. You'd list the comments on photo 42 at /photos/42/comments, and show a single comment at /photos/42/comments/7. To nest a resource like this, put its handlers in a module inside the parent's module. The comment handlers live in src/http/handlers/photos/comments.rs, declared from the photos module:

rust
// src/http/handlers/photos.rspub mod comments;

Then register the nested module. dust-framework builds each URI from both modules:

rust
resource!(photos::comments);
Method URI Handler
GET /photos/{photo}/comments photos::comments::index
GET /photos/{photo}/comments/create photos::comments::create
POST /photos/{photo}/comments photos::comments::store
GET /photos/{photo}/comments/{comment} photos::comments::show
GET /photos/{photo}/comments/{comment}/edit photos::comments::edit
PUT, PATCH /photos/{photo}/comments/{comment} photos::comments::update
DELETE /photos/{photo}/comments/{comment} photos::comments::destroy

Your handlers may take both the photo and the comment as models. dust-framework looks up the photo from {photo} and the comment from {comment}:

rust
// src/http/handlers/photos/comments.rsuse crate::models::{Comment, Photo};pub async fn show(photo: Photo, comment: Comment) -> String {    format!("{} on {}", comment.body, photo.title)}

Once a comment exists, its own ID is often enough to find it, without the photo's ID in front. If you'd like shorter URIs in that case, call shallow. The routes for a single comment then leave the photo out, while the routes for listing and creating comments keep it, since they need to know which photo the comments belong to:

rust
resource!(photos::comments).shallow();
Method URI Handler
GET /photos/{photo}/comments photos::comments::index
GET /photos/{photo}/comments/create photos::comments::create
POST /photos/{photo}/comments photos::comments::store
GET /comments/{comment} photos::comments::show
GET /comments/{comment}/edit photos::comments::edit
PUT, PATCH /comments/{comment} photos::comments::update
DELETE /comments/{comment} photos::comments::destroy

Not every folder of handlers is a parent resource. For example, if you keep your admin pages in src/http/handlers/admin/, resource!(admin::users) would treat admin as a parent and route /admin/{admin}/users. In this situation, since admin isn't an actual resource, import the module and add the /admin prefix with a group:

rust
use crate::http::handlers::admin::users;route.prefix("/admin").group(|route| {    resource!(users); // /admin/users, /admin/users/{user}, ...});

Mark a resource as single

Some resources aren't a list of things. Each user has exactly one profile, so there's no need for an ID in its URIs: /profile shows the logged-in user's profile, and /profile/edit shows the form to change it. To register a resource like this without an ID in its URIs, call single:

rust
resource!(profile).single();

With show, edit, and update handlers in the profile module, these routes will be registered:

Method URI Handler
GET /profile profile::show
GET /profile/edit profile::edit
PUT, PATCH /profile profile::update

A single resource may have any action except index, since there's only one of it to list.

Add middleware to some actions

resource! returns the resource's routes, so you may add middleware to all of them with middleware, or to only some of their actions with middleware_for. To keep some actions from running one of the group's middleware, call without_middleware_for. In this example, anyone may browse the photos, but only a logged-in user with a verified email address may upload, change, or delete one:

rust
use dust::auth::{Authenticate, RequireVerifiedEmail};use dust::routing::{Action, resource};route.middleware(Authenticate).group(|route| {    resource!(photos)        .middleware_for(            [Action::Store, Action::Update, Action::Destroy],            RequireVerifiedEmail,        )        .without_middleware_for::<Authenticate>([Action::Index, Action::Show]);});

Fallback routes

Without a fallback, a request that matches no route gets a 404 page. The fallback method defines a route that handles those requests instead:

rust
route.fallback(pages::not_found);

Static files

Before a request reaches your fallback, dust-framework serves a matching file from your public directory, if there is one. A request for /logo.svg returns public/logo.svg without running a route, so static assets are cheap and never touch your handlers.

Static files are public by definition. Keep secrets, private exports, and uploads outside public/, and serve those through a handler with File or a filesystem disk after checking who may see them. To learn more about private downloads, check out the responses guide's section on files.

Form method spoofing

HTML forms can only send GET and POST requests. To call a PUT, PATCH, or DELETE route from a form, add a hidden _method field. dust-framework uses its value as the request method:

html
<form action="/posts/1" method="POST">    <input type="hidden" name="_method" value="DELETE">    {{ csrf_field() }}</form>

Put the hidden _method field before any file inputs, so dust-framework reads it while it parses the form. JavaScript clients send real PUT, PATCH, and DELETE requests, so they don't need _method.

The spoofed method is what routing and middleware see, so a DELETE route's middleware runs as it would for a real DELETE request. CSRF protection still checks the request, and the web group still starts the session.

Accessing the current route

Sometimes code other than the handler needs to know which route matched, such as middleware that only applies to some pages. To read a domain or path parameter from the request, call request.route. It gives you the parameter as a string, or None when the route has no such parameter:

rust
if let Some(account) = request.route("account") {    tracing::info!(account, "Serving an account page");}

If you need the parameter as another type, such as a number, use route_as with that type instead. Like a handler's Params, it responds with a 404 when the value doesn't fit the type:

rust
let user_id: u64 = request.route_as("user")?;

The current_route method returns the route that matched the request, and route_is tells you whether a given handler handles it:

rust
if let Some(route) = request.current_route() {    route.uri();     // "/users/{user}"    route.handler(); // "app::http::handlers::users::show"}if request.route_is(users::show) {    // ...}

Global middleware run before routing, so current_route() returns None there. Route middleware and handlers see the matched route.

CORS

When JavaScript on another domain calls your application, such as a single-page app calling your API, browsers first ask whether you allow it. dust-framework answers these cross-origin resource sharing (CORS) requests for you, using the cors section of your configuration. By default, any origin may call routes under api/*.

To change who may call your application, edit your application's src/config/cors.rs configuration file. This example adds a webhooks/* path, allows only https://app.example.com, and lets requests carry cookies:

rust
// src/config/cors.rsuse dust::config;use dust::config::cors::{Allowed, Cors};use dust::time::ToSpan;#[config::section]fn cors() -> Cors {    Cors {        paths: vec!["api/*".to_owned(), "webhooks/*".to_owned()],        methods: Allowed::Any,        origins: Allowed::only(["https://app.example.com"]),        origin_patterns: Vec::new(),        headers: Allowed::Any,        exposed_headers: Vec::new(),        max_age: Some(0.seconds().into()),        credentials: true,    }}
Field What it allows Default
paths The paths that answer cross-origin requests, where * is a wildcard api/*
origins The origins that may call your application, where * is a wildcard: https://*.example.com any
origin_patterns Regular expressions for other origins: OriginPattern::new(r"https://pr-\d+\.preview\.dev") none
methods The methods they may use any
headers The request headers they may send any
exposed_headers The response headers their JavaScript may read none
max_age How long browsers may cache a preflight's answer none
credentials Whether requests may carry cookies false

The health route

Your application answers health checks from load balancers and uptime monitors at /up, set in src/app.rs:

rust
.with_routing(|routing, _| {    routing        .web(routes::web::routes)        .api(routes::api::routes)        .health("/up");})

It responds with a 200 once your application has booted, and a 503 if it couldn't, such as when a package's boot check failed. It runs before any middleware, so probes by IP address work.

The health route doesn't check your database. If your application shouldn't serve requests while its database is down, query the database in a booted callback in src/app.rs. If the query fails, the application doesn't start:

rust
use dust::db;Application::configure()    .booted(async |_| {        db::query!("SELECT 1").statement().await?;        Ok(())    })