dust

URL Generation

Introduction

The dust::url module provides helpers for generating absolute URLs to your application's routes, paths, and package assets. For example, when you build an API response that links to a post's comments, or send a customer an email with an unsubscribe link, dust::url builds the full URL using the right scheme and host.

You may also generate signed URLs that protect route and query parameters from tampering, or expire automatically after a period of time.

You need Use
The URL of a route route! or url::route
An absolute URL for a path url::to
The URL of a package asset url::vendor_asset
The current request's URL request.url() and request.full_url()
A tamper-proof or expiring link url::signed_route

Configuration

During an HTTP request, generated URLs use the scheme and host that the request arrived with. Outside of a request, such as in a queued job or a console command, dust-framework uses the APP_URL environment variable instead. Make sure to set APP_URL to your application's public URL in production so links sent from background jobs don't point to http://localhost:

ini
APP_URL=https://example.com

URLs for routes

You may generate a URL to any of your application's routes by passing its handler function to route! (available in the prelude). Because links reference the handler directly, every generated URL updates automatically if you change the route's URI, and renaming or removing a handler produces a compile-time error instead of a broken link.

For example, given a route registered as route.get("/users/{user}", users::show), you may generate the URL for user 1 like this:

rust
use dust::prelude::*;let url = route!(users::show, 1)?; // "http://example.com/users/1"

route! returns a dust::Result because the handler might not be registered on a route, or a required parameter might be missing. In a handler, ? turns that failure into an error response. When you need a function rather than a macro, such as inside generic code, call url::route(handler, params) directly.

In a template, pass the handler's path as a string instead, such as {{ route("users::show", user) }}. To learn more about generating links in views, check out the templates guide's section on URLs. If you'd like to redirect the user to a route from a handler, return redirect!, which accepts the same parameters.

Route parameters

When a route has no parameters, pass its handler alone. For routes with {placeholders}, pass positional arguments in order:

rust
route!(home::show)?;           // "http://example.com"route!(users::show, 1)?;       // "http://example.com/users/1"route!(comments::show, 1, 2)?; // "http://example.com/posts/1/comments/2"

You may also pass parameters by name with key = value. Named parameters may mix models, numbers, and strings in the same call, and any named parameter that doesn't match a route placeholder is appended to the URL's query string:

rust
// "http://example.com/users?page=2"route!(users::index, page = 2)?;// "http://example.com/users/1?tab=posts"route!(users::show, user = 1, tab = "posts")?;

For query parameter names that aren't Rust identifiers, quote the key, such as route!(users::index, "utm-source" = "newsletter")?.

To omit trailing optional parameters, leave them out or pass None. Passing None lets you forward Option values that your handler received directly to route!. For a route at /archive/{year?}/{month?}:

rust
route!(archive::show)?;                 // "http://example.com/archive"route!(archive::show, 2026, 10)?;       // "http://example.com/archive/2026/10"route!(archive::show, 2026, None::<u8>)?; // "http://example.com/archive/2026"

Domain parameters

When a route is defined inside a domain group, route! builds the URL's host from that domain. You must always pass the domain's parameters explicitly, because dust-framework never infers them from the current request. Positional parameters fill the domain placeholders first, followed by the path placeholders.

For example, given a route at /users/{user} inside a {account}.example.com group:

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

Models and your own types

Since you'll often generate links for a model, you may pass a reference to the model itself as a route parameter. dust-framework automatically extracts the model's primary key, its custom route_key, or the specific column named in the route's placeholder (such as slug for {post:slug}).

For example, this API handler returns a post along with the URL to its comments:

rust
use dust::prelude::*;use serde_json::{Value, json};use crate::models::Post;pub async fn show(post: Post) -> dust::Result<Json<Value>> {    Ok(Json(json!({        "title": post.title,        // "http://example.com/posts/42/comments"        "comments_url": route!(comments::index, &post)?,    })))}

Strings, integers, UUIDs, and ULIDs all work as route parameters out of the box. If you'd like to pass a custom type of your own, such as an enum, implement the RouteParam trait:

rust
use dust::prelude::*;use dust::url::RouteParam;pub enum Category {    Engineering,    Design,    Product,}impl RouteParam for Category {    fn to_route_param(&self) -> String {        match self {            Self::Engineering => "engineering",            Self::Design => "design",            Self::Product => "product",        }        .to_owned()    }}// "http://example.com/articles/engineering"let url = route!(articles::by_category, Category::Engineering)?;

How route URLs are built

When you call route!(users::show, &user), dust-framework builds the URL in a fixed order:

  1. It finds the route registered with the handler you named. If no route uses that handler, it returns an error.
  2. It fills the domain's placeholders, then the path's placeholders, from the positional arguments.
  3. It appends any named parameter that doesn't match a placeholder as a query string value.
  4. It prepends the scheme and host from the current request, or from APP_URL outside a request.
  5. It percent-encodes the values, so a value can't change the shape of the URL.
Problem What happens
The handler isn't registered on a route A 500 error.
A required parameter is missing or empty A 500 error.
There are more positional values than placeholders A 500 error.
A named parameter doesn't match a placeholder It becomes a query string parameter.
A domain parameter is missing A 500 error, even inside a request.
An optional parameter has a value, but one before it doesn't A 500 error.

Because the handler is the key, a typo in a handler name is a compile error, and renaming a route's URI updates every link automatically.

URLs for paths

Sometimes you need an absolute URL for a path that isn't backed by a route handler, such as a static file in your public directory. Pass the path to url::to, and dust-framework prepends your application's scheme and host. If you pass a full URL such as https://dust.example, url::to returns it unchanged:

rust
use dust::url;let url = url::to("/about"); // "http://example.com/about"

Package assets

A package may serve its own CSS, JavaScript, and images. To generate the URL for one of those files, call url::vendor_asset with the package's asset namespace and the file's path. dust-framework appends a hash of the file to the query string so browsers automatically fetch a fresh copy whenever the file changes:

rust
// "http://example.com/vendor/inspire/inspire.css?id=34b6aba934cd2bfe"let url = url::vendor_asset("inspire", "inspire.css");

The current URL

To read the URL of the incoming request in a handler, call url or full_url on the Request. To read the last page the user visited, call previous_url on the session:

rust
use dust::prelude::*;pub async fn show(request: Request) -> dust::Result<String> {    let current = request.url();                       // "http://example.com/users"    let with_query = request.full_url();               // "http://example.com/users?page=2"    let previous = request.session()?.previous_url();  // Some("http://example.com/dashboard")    // ...}

To learn more about building a link to the current page with query parameters added or removed, check out the requests guide's section on request path, host, and method.

Signed URLs

Some links act on the user's behalf without asking them to log in, such as an unsubscribe link in a newsletter. Because the route is publicly accessible, you need to verify that nobody tampered with the user ID or other parameters in the URL. A signed URL appends a cryptographic signature hash to the query string so dust-framework can detect if any part of the URL has been modified.

To create a signed URL to a route, call url::signed_route, which accepts the same parameters as url::route:

rust
use dust::url;// "http://example.com/unsubscribe/1?signature=…"let url = url::signed_route(newsletter::unsubscribe, 1)?;

If the link should expire after a period of time, such as a temporary invoice download, use url::temporary_signed_route. Pass a duration from now (such as 30.minutes()) or a specific moment when the link should stop working:

rust
use dust::prelude::*;use dust::url;let url = url::temporary_signed_route(invoices::download, 30.minutes(), 42)?;

dust-framework signs URLs using your application's APP_KEY, so signing fails if APP_KEY isn't set. Signed URLs also reserve the signature and expires query parameters, so avoid using those names for your own route or query parameters.

Validating signed route requests

To reject requests without a valid signature, assign the ValidateSignature middleware to the route in your route file. It responds with a 403 when the signature is missing, invalid, or expired:

rust
use dust::http::middleware::ValidateSignature;route    .get("/unsubscribe/{user}", newsletter::unsubscribe)    .middleware(ValidateSignature);

If you'd rather verify the signature manually inside a handler, call has_valid_signature on the Request:

rust
use dust::prelude::*;pub async fn unsubscribe(request: Request) -> dust::Result<Redirect> {    dust::abort_unless(request.has_valid_signature(), 403)?;    // Unsubscribe the user...    Ok(Redirect::to("/"))}

[!WARNING] The signature covers the URL, not the request body. Read signed values from route parameters, or from the query string with Query<T> or request.query(), never from Valid<T> or request.parse().

Some email providers automatically append tracking parameters, such as utm_source, to links in outgoing emails, which invalidates the signature. To allow specific query parameters on a single route, pass them to ValidateSignature::ignore(...):

rust
route    .get("/unsubscribe/{user}", newsletter::unsubscribe)    .middleware(ValidateSignature::ignore(["utm_source", "utm_campaign"]));

To ignore tracking parameters on every signed URL across your application, list them in the APP_SIGNED_URL_IGNORE environment variable instead. request.has_valid_signature() ignores these parameters as well:

ini
APP_SIGNED_URL_IGNORE=utm_source,utm_campaign,fbclid

Because ignored parameters aren't covered by the signature, anyone can modify them, so never trust their values.

If your application runs behind a load balancer that terminates TLS, trust the load balancer. Otherwise every request appears to arrive over http, and a URL signed for https fails its signature check.

Responding to invalid signed routes

When someone opens a signed link that has expired or been modified, dust-framework responds with a generic 403 error page. The underlying error is an InvalidSignature, which distinguishes between InvalidSignature::Expired for a temporary link that has run out and InvalidSignature::Incorrect for a missing or invalid signature.

To render a custom response, such as offering to send a fresh link when one expires, register an error renderer in src/app.rs:

rust
use dust::url::InvalidSignature;.with_errors(|errors, _| {    errors.render(|invalid: &InvalidSignature, _request, status| {        if *invalid == InvalidSignature::Expired {            return Some((status, "This link has expired. Please request a new one."));        }        None    });})