Cookies
Introduction
Cookies let your application store small pieces of data in a visitor's browser and read them back on later requests, such as their preferred color theme or whether they dismissed a product tour. You read incoming cookies from the Request and attach outgoing cookies to the response your handler returns.
Routes in the web middleware group automatically encrypt and sign cookies so visitors can't read or tamper with them. Routes outside the web group, such as those in src/routes/api.rs, send cookies unencrypted. For data that should stay on your server, use the session instead.
Reading cookies
To retrieve a cookie from an incoming request, call cookie on the Request. It returns Option<String>, or None if the browser didn't send that cookie:
use dust::prelude::*;pub async fn show(request: Request) -> String { let theme = request.cookie("theme").unwrap_or_else(|| "light".to_owned()); format!("Your theme is {theme}")}On routes in the web middleware group, request.cookie(...) automatically returns the decrypted value. If a cookie's value was modified by the client and fails decryption, cookie returns None.
Sending cookies
To attach a cookie to an outgoing response, call with_cookie. Passing a (name, value) tuple creates a session-scoped cookie that lasts until the user closes their browser:
use dust::prelude::*;pub async fn update() -> Response { Response::new("Saved").with_cookie(("theme", "dark"))}Every response type supports with_cookie, including redirects, views, and Json. For example, a handler that redirects after updating settings may attach the cookie directly to the Redirect:
pub async fn update() -> Redirect { Redirect::to("/settings").with_cookie(("theme", "dark"))}Attaching a cookie replaces any cookie already on the response with the same name, path, and domain. Middleware may also attach cookies to the response returned by next.run(request).
Cookie attributes
To give a cookie a lifetime or customize its attributes, build a Cookie instead of passing a tuple. Lifetimes are passed as a span, such as 30.days():
use dust::cookie::{Cookie, SameSite};use dust::prelude::*;pub async fn update() -> Response { Response::new("Saved") .with_cookie(Cookie::new("theme", "dark").max_age(30.days())) .with_cookie(Cookie::new("cookie_consent", "accepted").forever()) .with_cookie(Cookie::new("embed", "1").same_site(SameSite::None).secure(true))}| Method | Attribute | Effect |
|---|---|---|
max_age(span) |
Max-Age |
Keeps the cookie for this long. |
expires(time) |
Expires |
Keeps the cookie until a time, such as dust::now().end_of_day()?. |
forever() |
Max-Age |
Keeps the cookie for 400 days, the longest that browsers allow. |
path(path), domain(domain) |
Path, Domain |
Where the browser sends the cookie. |
secure(bool) |
Secure |
Sends the cookie only over HTTPS. |
http_only(bool) |
HttpOnly |
Hides the cookie from JavaScript. Pass false to let scripts read it. |
same_site(SameSite) |
SameSite |
Whether the browser sends the cookie with requests from other sites: Lax, Strict, or None. |
Unless you override them, new cookies inherit the Path, Domain, Secure, and SameSite defaults from your session configuration, and have HttpOnly enabled. Those defaults are safe for most cookies, so you'll usually only need to set a lifetime.
[!NOTE] Browsers reject
SameSite::Nonecookies that aren't alsoSecure, so set both together:Cookie::new("embed", "1").same_site(SameSite::None).secure(true). They also cap a cookie at about 4 KB, so a value that large belongs in the session or your database instead.
The SameSite values differ in when the browser sends the cookie:
| Value | The browser sends the cookie |
|---|---|
Lax |
On same-site requests and on top-level navigations to your site. The default. |
Strict |
Only on same-site requests, so following a link from another site arrives without it. |
None |
On cross-site requests too, such as an embedded widget. Requires Secure. |
Deleting cookies
To remove a cookie from the browser, call without_cookie on the response. dust-framework sends an expired cookie in its place so the browser deletes it:
use dust::prelude::*;pub async fn dismiss() -> Response { Response::new("Dismissed").without_cookie("tour")}If the cookie was originally set with a custom path or domain, the browser only deletes it when the removal cookie specifies the same path and domain. In that case, pass a Cookie with those attributes:
use dust::cookie::Cookie;Response::new("Dismissed").without_cookie(Cookie::new("tour", "").path("/admin"))Cookies and encryption
The EncryptCookies middleware runs first in the web middleware group and encrypts every outgoing cookie using your application's encryption key. When the browser sends those cookies back on subsequent requests, EncryptCookies decrypts them before your handler runs. If a cookie fails decryption because a visitor tampered with it, EncryptCookies discards it and request.cookie(...) returns None.
[!WARNING]
EncryptCookiesencrypts only the cookies on responses that pass back through it. A middleware that runs outside thewebgroup, such as a global middleware, sends its cookies unencrypted.
Excluding cookies from encryption
Sometimes JavaScript or another application needs to read a cookie, such as a script that applies the visitor's color theme before the page renders. To exclude specific cookies from encryption, replace EncryptCookies inside with_middleware in src/app.rs:
use dust::cookie::EncryptCookies;use dust::prelude::*;Application::configure() .with_middleware(|middleware, _| { middleware.replace(EncryptCookies::except(["theme"])); })For JavaScript to read the cookie in the browser, also disable HttpOnly when you attach it:
Response::new("Saved").with_cookie(Cookie::new("theme", "dark").http_only(false))[!WARNING] Only exclude cookies that don't contain sensitive data. Visitors can read and modify an unencrypted cookie, so always treat its value as untrusted input.
Troubleshooting
When a cookie doesn't arrive, the browser usually discarded it before the request. These are the common causes:
| Symptom | Likely cause |
|---|---|
request.cookie(..) returns None |
The cookie expired, its Path or Domain doesn't match the request, or Secure is set while you test over plain HTTP. |
request.cookie(..) returns None only in production |
The cookie was encrypted with an old APP_KEY, or a proxy stripped it. |
| JavaScript can't read the cookie | HttpOnly is on by default; set .http_only(false) when you attach it. |
| A cross-site request doesn't send the cookie | SameSite=Lax or Strict blocked it; use SameSite::None with Secure for an embedded widget. |
without_cookie doesn't remove it |
The original cookie used a custom Path or Domain; delete it with the same attributes. |
Testing
In tests, send an incoming cookie with cookie, and assert outgoing cookies with assert_cookie and assert_cookie_expired. Both work with plain values, so you don't need to encrypt or decrypt cookies yourself:
use dust::testing::prelude::*;#[dust::test]async fn the_theme_can_be_changed(app: Application) { app.get("/").cookie("theme", "dark").await.assert_see("Your theme is dark"); app.post("/theme").await.assert_cookie("theme", "dark"); app.post("/tour/dismiss").await.assert_cookie_expired("tour");}To learn more about carrying cookies from one response to the next request with with_cookies_from, check out the testing guide's section on cookies and sessions.