dust

Responses

Introduction

Every route and handler in your application returns an HTTP response to send back to the user's browser or API client. You rarely need to build an HTTP response by hand, because dust-framework converts any value that implements IntoResponse into a full response.

Whether a handler returns plain text, JSON, a rendered view, a redirect, a file download, or a live stream, dust-framework takes care of the status code, headers, and body for you.

Creating responses

Strings and JSON

The most basic response is a string, which dust-framework sends as plain text:

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

When building an API or returning structured data, wrap any Serialize value in Json. dust-framework serializes the value and sets the Content-Type header to application/json:

rust
use dust::prelude::*;#[derive(Serialize)]pub struct Health {    pub status: &'static str,    pub version: &'static str,}pub async fn health() -> Json<Health> {    Json(Health {        status: "ok",        version: "1.0.0",    })}

For quick, ad-hoc JSON payloads where defining a struct feels like overkill, you may use serde_json::json! instead:

rust
use dust::prelude::*;use serde_json::{Value, json};pub async fn status() -> Json<Value> {    Json(json!({        "status": "ok",        "version": "1.0.0",    }))}

Since models implement Serialize, you may also return a model or a list of models wrapped in Json:

rust
use dust::prelude::*;use crate::models::User;pub async fn index() -> dust::Result<Json<Vec<User>>> {    let users = User::all().await?;    Ok(Json(users))}

Any field marked #[serde(skip)] is left out of the JSON output. Your application's User model skips its password and remember_token fields this way, so they aren't exposed in JSON responses.

HTML

When you want to render an HTML page on the server, return a view:

rust
use dust::prelude::*;use dust::view::View;pub async fn about() -> View {    view("about", data! { company => "dust-framework" })}

Sometimes you already have HTML that you trust, such as a terms of service page that your build step generates from Markdown. Wrap it in Html::raw to send it as HTML without escaping it:

rust
use dust::view::Html;pub async fn terms() -> Html {    Html::raw(include_str!("../../../resources/terms.html"))}

[!WARNING] Html::raw does not escape its contents. Only pass HTML that you generated or reviewed yourself, never a value a user typed.

A new application uses io/ui for its pages, and its layout lives in resources/views/layout.html. Your handlers still return a View, so the two work together: io/ui supplies the markup and behaviour, and the handler supplies the data. To learn more, check out the frontend guide.

Created and no content

When building a JSON API, you'll usually respond with 201 Created after creating a resource and 204 No Content after deleting one. dust-framework provides Created to serialize a value as JSON with a 201 status, and NoContent to send an empty 204 response.

In this posts handler module, NewPost is the post's fill struct, store creates the post for the logged-in user, and destroy deletes the post that the route names:

rust
use dust::http::{Created, NoContent};use dust::model::create;use dust::prelude::*;use crate::models::{Post, User};#[dust::input(fills = Post)]#[validate(authenticated)]pub struct NewPost {    #[validate(required, max_length(255))]    pub title: String,    #[validate(required)]    pub body: String,}pub async fn store(    Authenticated(user): Authenticated<User>,    Valid(input): Valid<NewPost>,) -> dust::Result<Created<Post>> {    let post = create!(Post { user: &user, ..input }).await?;    Ok(Created(post))}pub async fn destroy(post: Post) -> dust::Result<NoContent> {    post.delete().await?;    Ok(NoContent)}

If you'd also like to tell the client where the new resource lives, attach a Location header with its URL. Calling with_header on Created turns it into a Response, so the handler returns dust::Result<Response>:

rust
pub async fn store(    Authenticated(user): Authenticated<User>,    Valid(input): Valid<NewPost>,) -> dust::Result<Response> {    let post = create!(Post { user: &user, ..input }).await?;    let location = route!(posts::show, &post)?;    Ok(Created(post).with_header("location", location))}

NoContent sends an empty body, so don't return data alongside it. A 204 response has no representation for a client to parse; if the client needs the deleted record's ID, include it in a response header or use 200 OK with a small JSON body instead.

Status codes and headers

Sometimes a handler needs to respond with a status code other than 200 OK, such as 202 Accepted after queuing a background export. To set a status code, return it in a tuple with your response body:

rust
use dust::prelude::*;pub async fn export() -> (StatusCode, &'static str) {    // Queue the export...    (StatusCode::ACCEPTED, "Your export is being prepared.")}

The statuses you'll choose most often:

Status When to use it
200 OK A successful response with a body.
201 Created A new resource, usually through Created.
202 Accepted Work that continues in the background.
204 No Content Success with nothing to return, usually after a delete.
302 Found / 303 See Other A redirect after a form submission.
304 Not Modified A cached response the client already has.
400 Bad Request Malformed input that isn't a validation failure.
401 Unauthorized The client isn't signed in.
403 Forbidden The client is signed in but may not do this.
404 Not Found The record or page doesn't exist.
409 Conflict The request conflicts with the current state, such as a double booking.
413 Content Too Large The body or upload exceeds a limit.
422 Unprocessable Content The input failed validation.
429 Too Many Requests The client exceeded a rate limit.
500 Internal Server Error A server failure.
503 Service Unavailable A temporary outage or a request that timed out.

For a status code that isn't a constant, build it with StatusCode::from_u16(..) and handle the error if the number is invalid.

You may also change the status code of any response with with_status, passing either a StatusCode or a numeric status code. On View, with_status keeps the concrete type, so the handler may still return View:

rust
pub async fn readiness() -> Response {    "Database unavailable".with_status(StatusCode::SERVICE_UNAVAILABLE)}

To attach a header to any response, call with_header, or call with_headers to attach several headers at once. A header you attach replaces any existing header of the same name, including defaults such as a view's Content-Type:

rust
use dust::prelude::*;use dust::view::View;pub async fn feed() -> View {    view("feed", data! {}).with_header("content-type", "application/rss+xml")}pub async fn show() -> View {    view("reports.show", data! {}).with_headers([        ("cache-control", "no-store"),        ("x-frame-options", "DENY"),    ])}

Header names are case-insensitive, so with_header("Content-Type", ..) replaces the same header as with_header("content-type", ..). Some headers are managed by dust-framework already, such as the security headers added by middleware; a value you set on the response wins.

When different branches of a handler return different kinds of responses, Rust requires the handler to return a single type. Return Response and call .into_response() on each branch. If the handler also uses ?, return dust::Result<Response> and wrap each branch in Ok(..):

rust
use dust::prelude::*;pub async fn show(request: Request) -> Response {    let report = json!({ "title": "Q3 Sales", "total": 1_200 });    if request.wants_json() {        return Json(report).into_response();    }    view("reports.show", data! { report }).into_response()}

Cookies

Sometimes a handler needs to store a small value in the user's browser, such as their preferred color theme. You may attach a cookie to any outgoing response with with_cookie, and expire a cookie early with without_cookie:

rust
use dust::prelude::*;pub async fn update_theme() -> Redirect {    Redirect::back().with_cookie(("theme", "dark"))}pub async fn forget_theme() -> Redirect {    Redirect::back().without_cookie("theme")}

To learn more about cookie lifetimes, attributes, and how dust-framework encrypts cookies, check out the cookies guide.

Redirects

After saving a form or completing an action, you'll usually send the user to another page rather than render one directly. To redirect to a path or a full URL, such as a payment provider's checkout page, return Redirect::to. To send the user back to the page they came from, return Redirect::back():

rust
use dust::prelude::*;pub async fn dashboard() -> Redirect {    Redirect::to("/home/dashboard")}pub async fn update() -> Redirect {    // Save the user's settings...    Redirect::back()}

You don't need to redirect back yourself when a submitted form is invalid. Validation handles that for you by redirecting the user back to the form with the validation errors and their previous input.

Redirecting to routes

To redirect to one of your application's routes, pass its handler to redirect! (available in the prelude). Route parameters work as they do in route!: pass the handler alone when the route has no parameters, pass positional parameters such as a model, or pass named key = value pairs. This handler creates a post from the NewPost form and redirects to the new post's page:

rust
use dust::model::create;use dust::prelude::*;use crate::models::{Post, User};pub async fn store(    Authenticated(user): Authenticated<User>,    Valid(input): Valid<NewPost>,) -> dust::Result<Redirect> {    let post = create!(Post { user: &user, ..input }).await?;    Ok(redirect!(posts::show, &post))}

To attach query parameters to a redirect, such as the active tab or a filter, pass named parameters directly or chain with_query with any Serialize value (such as key-value pairs or a struct). To scroll the user to a specific section of the destination page, such as the comments section of a post, chain with_fragment. For example, this redirects to /posts/42?tab=comments#reply:

rust
redirect!(posts::show, &post)    .with_query([("tab", "comments")])    .with_fragment("reply")

When you need a function rather than a macro, call Redirect::route(handler, params) directly.

Redirecting with flashed session data

Redirecting to a new page and flashing data to the session often go together, such as showing a banner that confirms a form was saved. To flash a value for the next request, chain with onto the redirect:

rust
use dust::prelude::*;pub async fn update() -> Redirect {    // Update the user's profile...    Redirect::back().with("status", "Profile updated!")}

The flashed value is available only for the next request. A view may read it with session("status"). Because with stores the value in the session, it only works on routes in the web middleware group.

Redirecting to the intended page

When a guest visits a page that requires authentication, Authenticate stores that URL in the session and sends them to your login page. After they log in, Redirect::intended sends them on to the page they originally requested. If no intended URL was stored in the session, it falls back to the route you pass it:

rust
use dust::prelude::*;pub async fn store() -> Redirect {    // Log the user in...    Redirect::intended(dashboard::show, ())}

Redirect status codes

By default, redirects respond with a 302 Found status code. If you need a different status code, pass a number or a StatusCode to status, or call permanent for a 301 Moved Permanently redirect:

rust
Redirect::to("/login").status(303);Redirect::to("/new-home").permanent();

Files

Some files shouldn't be publicly accessible, such as invoices and reports that only their owner should see. After checking that the user has access, you may return a file on disk from your handler as a File.

File downloads

To prompt the user's browser to download a file, return File::download with the file's path. The browser saves the file under its name on disk unless you specify another name with name:

rust
use dust::http::File;pub async fn report() -> File {    File::download("storage/reports/q3.pdf").name("Q3 Report.pdf")}

File responses

To display a file directly in the browser instead of downloading it, such as an image or a PDF, return File::new:

rust
use dust::http::File;use dust::prelude::*;pub async fn invoice(Params(id): Params<u64>) -> File {    File::new(format!("storage/invoices/{id}.pdf"))}

For both File::download and File::new, dust-framework sets the Content-Type header from the file's extension and supports conditional and range requests, so browsers can cache the file and resume interrupted downloads. If the file doesn't exist on disk, dust-framework responds with a 404. Relative paths resolve against your application's base path rather than the process's working directory.

[!WARNING] Never build a File path directly from untrusted user input, such as a raw filename from the request. A path containing .. or a leading / could allow a user to read arbitrary files on disk. Use a typed ID, look up the path from your database, or serve files through a filesystem disk instead.

If a file is stored without an extension, specify its content type explicitly with content_type:

rust
pub async fn avatar(Params(id): Params<u64>) -> File {    File::new(format!("storage/avatars/{id}")).content_type("image/png")}

If you generated a temporary file on disk solely for this response, such as a one-off export, call delete_after_send so dust-framework removes the file once it's sent:

rust
pub async fn export() -> File {    File::download("storage/exports/tmp-users.csv")        .name("users.csv")        .delete_after_send()}

[!NOTE] dust-framework serves static files in your public directory without a route. Use File for private files that your routes decide whether to serve.

Downloads of generated content

Sometimes you want to offer generated content as a download, such as a CSV export, without writing a temporary file to disk first. Return a Download with the filename and contents, and dust-framework sets the content type from the filename:

rust
use dust::http::Download;use crate::models::User;pub async fn export() -> dust::Result<Download> {    let users = User::all().await?;    let mut csv = String::from("name,email\n");    for user in users {        csv.push_str(&format!("{},{}\n", user.name, user.email));    }    Ok(Download::new("users.csv", csv))}

For a large export, holding the entire file in memory isn't practical. Instead, pass a stream of chunks to Download::try_stream when producing chunks can fail, such as reading rows with a model's cursor. dust-framework sends each chunk as it's produced:

rust
use dust::http::Download;use dust::stream::StreamExt;use crate::models::User;pub async fn export() -> Download {    let rows = User::query()        .cursor()        .map(|row| row.map(|user| format!("{},{}\n", user.name, user.email)));    Download::try_stream("users.csv", rows)}

If your stream of chunks can't fail, use Download::stream instead.

Streamed responses

Some responses take a while to produce, such as an AI model's reply that arrives token by token or the live output of a deployment. Instead of waiting until the entire response is ready, a streamed response sends each chunk to the client as soon as it's available.

To stream chunks from an async closure, return Streamed::channel. The closure starts running once your handler returns, and sends chunks with sender.send:

rust
use dust::http::Streamed;pub async fn deploy() -> Streamed {    Streamed::channel(async |sender| {        for step in ["Building", "Migrating", "Done"] {            // Run the step...            sender.send(format!("{step}\n")).await?;        }        Ok(())    })}

sender.send fails once the client disconnects, so ? stops the closure cleanly. If the closure returns any other error, dust-framework reports it and closes the response abruptly, so the client can tell the stream was cut short.

Streamed responses use text/plain by default. To send another content type, chain content_type onto the response:

rust
pub async fn answer() -> Streamed {    Streamed::channel(async |sender| {        sender.send("# Summary\n\n").await?;        sender.send("Here is the streamed Markdown reply.").await?;        Ok(())    })    .content_type("text/markdown")}

[!NOTE] dust-framework saves the session after your handler returns and before it sends the response body. Make any session changes in the handler before returning the streamed response, not inside the producer closure.

If you already have an infallible Stream of bytes or strings (or build one with stream!), pass it directly to Streamed::new. The dust::stream module re-exports the stream utilities you'll need, including StreamExt for methods like map and filter and the stream! and try_stream! macros for building async streams with yield.

On the frontend, you may consume a streamed response with the useStream hook from @dust/stream-react or @dust/stream-vue. Install the package for your frontend:

shell
npm install @dust/stream-react

useStream sends a POST request, so register the route with route.post in src/routes/web.rs, such as route.post("/deploy", deploys::deploy). The hook reads the CSRF token from the XSRF-TOKEN cookie that the web group sets. Once you invoke send, the hook automatically appends each incoming chunk to data:

tsx
import { useStream } from "@dust/stream-react";
 
export default function Deploy() {
    const { data, isFetching, isStreaming, send } = useStream("/deploy");
 
    return (
        <div>
            <pre>{data}</pre>
            {isFetching && <p>Connecting...</p>}
            <button onClick={() => send({})} disabled={isStreaming}>
                Deploy
            </button>
        </div>
    );
}

Streamed JSON responses

When you need to return a large list as JSON, such as every user in your database, loading the entire list into memory at once can be slow and expensive. Instead, return a JsonStream, which serializes and sends each item as it arrives.

Use JsonStream::try_new with a stream that can fail, such as a model query's cursor, which reads one row at a time from the database. By default, JsonStream sends the items as a JSON array:

rust
use dust::http::JsonStream;use crate::models::User;pub async fn users() -> JsonStream {    JsonStream::try_new(User::query().cursor()) // [{"id":1,...},...]}

If you'd rather wrap the array in a JSON object under a top-level key, chain key onto the stream:

rust
pub async fn users() -> JsonStream {    JsonStream::try_new(User::query().cursor()).key("users") // {"users":[{"id":1,...},...]}}

If the query fails part way, dust-framework reports the error and ends the response abruptly, so the client sees incomplete JSON rather than a list that looks finished. If your stream can't fail, use JsonStream::new instead. To build a fallible stream yourself instead of using a query cursor, use try_stream! from dust::stream, which lets you use ? inside the stream body and yield each item as it becomes ready.

On the frontend, the useJsonStream hook from @dust/stream-react or @dust/stream-vue reads the streamed response and parses the JSON once the stream finishes:

tsx
import { useJsonStream } from "@dust/stream-react";
 
type User = {
    id: number;
    name: string;
    email: string;
};
 
export default function Users() {
    const { data, send } = useJsonStream<{ users: User[] }>("/users");
 
    return (
        <div>
            <ul>
                {data?.users.map((user) => (
                    <li key={user.id}>{user.name}</li>
                ))}
            </ul>
            <button onClick={() => send({})}>Load Users</button>
        </div>
    );
}

Event streams

When you want to push updates to a page as things happen on the server, such as live job progress or new tasks added to a list, return an EventStream to send server-sent events (text/event-stream). Pass an async closure to EventStream::channel, call sender.send(...) for each event, and use ? for errors. Each value you send may be text, Json, Html, or a view, and dust-framework sends it as an update event by default:

rust
use dust::http::sse::EventStream;use dust::prelude::*;use dust::task;use serde_json::json;use crate::models::Export;pub async fn progress(mut export: Export) -> EventStream {    EventStream::channel(async move |sender| {        loop {            sender.send(Json(json!({ "percent": export.percent }))).await?;            if export.percent >= 100 {                break;            }            task::sleep(1.seconds()).await;            let Some(updated) = Export::find(export.id).await? else {                break;            };            export = updated;        }        Ok(())    })}

sender.send fails once the client disconnects, so ? stops the closure cleanly. If the closure returns any other error, dust-framework reports it and ends the stream without sending the final </stream> event.

If you'd like to give an event a custom name that the browser can listen for separately, wrap its data in an Event:

rust
use dust::http::sse::Event;sender.send(Event::new("export-progress", Json(json!({ "percent": export.percent })))).await?;

If you already have an infallible Stream, such as a Redis subscription transformed with StreamExt::map, pass it directly to EventStream::new.

On the frontend, the useEventStream hook from @dust/stream-react or @dust/stream-vue listens for update events and updates message as each one arrives:

tsx
import { useEventStream } from "@dust/stream-react";
 
export default function Progress() {
    const { message } = useEventStream("/progress");
 
    return <div>{message}</div>;
}

When the stream runs out of events, dust-framework sends a final update event containing </stream> so the @dust/stream hooks know the stream has finished. If you consume the stream manually with the browser's EventSource API, close the connection when </stream> arrives so the browser doesn't reconnect automatically:

js
const source = new EventSource("/progress");source.addEventListener("update", (event) => {    if (event.data === "</stream>") {        source.close();        return;    }    console.log(event.data);});

You may customize the final event with end_with, or omit it with without_end_event:

rust
EventStream::new(events).end_with(Event::new("done", "complete"));EventStream::new(events).without_end_event();

While no events arrive, dust-framework sends a comment every 15 seconds so proxies don't close the connection.

Responses of your own

If several handlers in your application return the same kind of response, you may wrap it in a type of your own that implements IntoResponse. For example, an API that queues background work might define an Accepted type that serializes a payload as JSON with a 202 Accepted status:

rust
use dust::prelude::*;pub struct Accepted<T>(pub T);impl<T: Serialize> IntoResponse for Accepted<T> {    fn into_response(self) -> Response {        (StatusCode::ACCEPTED, Json(self.0)).into_response()    }}

Handlers may now return Accepted(job) directly, and because Accepted implements IntoResponse, it also gains with_header, with_headers, with_cookie, and without_cookie.

Testing

To test the responses your routes return, send requests through the test Application and chain assertions onto the response. For example, these tests verify that /feed returns an RSS content type and that /dashboard redirects to /home/dashboard:

rust
use dust::testing::prelude::*;#[dust::test]async fn the_feed_is_rss(app: Application) {    app.get("/feed")        .await        .assert_ok()        .assert_header("content-type", "application/rss+xml");}#[dust::test]async fn the_old_dashboard_redirects(app: Application) {    app.get("/dashboard").await.assert_redirect_to("/home/dashboard");}

To learn more about asserting status codes, headers, cookies, redirects, and JSON responses, check out the testing guide's section on available assertions. If you'd like to inspect the page a redirect leads to, check out following redirects.