Forms, APIs, and cache purge
Use an HTML form for a submission that moves to another page. To send and receive values from JavaScript in the browser, use an API that returns data as JSON (an entry point that programs call). This section also covers Purge, which deletes cached content after you update data.
| Route | manifest | What it can return | Cached |
|---|---|---|---|
| Form | .form(Form::at("/cart/add", cart::add)) |
A redirect (HTTP 303). For an input it does not accept, the page itself (HTTP 422) | No |
| POST JSON API | .api(Api::post("/api/cart", cart::add_json)) |
JSON | No |
| GET JSON API | .api(Api::get("/api/favorites", favorites::list)) |
JSON (read-only) | No |
| Public text | .download(Download::public(…).cache(…)) |
robots.txt, sitemap.xml, RSS | Yes |
| Public files | .download(Download::public_file(…).cache(…)) |
Files in R2 | Yes |
| Per-user files | .download(Download::private(…)) |
Files (login required) | No |
Forms
pub async fn add(deps: Deps, session: Option<Session>, form: FormData) -> Result<Redirect, Reject> {
let id = form.get("product_id").ok_or(Reject::BadRequest)?; // 400 if missing
// … change data …
let _ = deps.purge(&[Purge::Tag(format!("product-{id}"))]).await?; // purge the cached product page
Ok(Redirect::to(LocalUrl::new(&format!("/products/{id}")).unwrap())) // 303 to the product page
}- After you change data, return a redirect (303). It tells the browser to open another URL after the submission (POST), and the browser loads that URL. This flow is called PRG (Post/Redirect/Get). A reload does not send the same submission again.
- The destination is a path on the same site, and only the
LocalUrltype is accepted. To redirect to another site (a payment service, for example), useRedirect::external, and declare the destination inCargo.tomlunderform_redirects. - The paths of forms and POST APIs are fixed (you cannot use
{id}). Send the ID in the body. - The Gate checks every POST before the handler runs: does it come from the same origin (the combination of URL scheme, host name, and port)? If not, the Gate rejects it with 403. It also rejects a POST from another subdomain of the same site. This protects against CSRF (Cross-Site Request Forgery), an attack in which another site makes the user's browser send an action the user did not intend.
When an input is not accepted (Reject::Invalid)
The server checks the input and may not accept it, for example a name that is only spaces or a message that is too long. For such an input, you can return the same page with the sent values and the reasons. The status is 422. Nothing was saved, so a reload cannot send it twice, and there is no reason to redirect. A redirect would lose what the user typed.
pub async fn receive(_deps: Deps, _session: Option<Session>, form: FormData) -> Result<Redirect, Reject> {
let name = form.get("name").unwrap_or_default();
let message = form.get("message").unwrap_or_default();
if let Err(problem) = check(Some(name), Some(message)) {
// nothing is saved: render the same page with the sent values and the reasons, and return it (422)
let page = HomeView::with(ContactFormView::refused(name, message, problem));
return Err(Reject::Invalid(InvalidPage::of(&page)));
}
// … process the accepted input …
Ok(Redirect::to(LocalUrl::new("/thanks").ok_or(Reject::BadRequest)?)) // 303 when accepted
}
- It uses the same template as the page. The page's Load renders it with empty values, and the handler renders it with the sent values and the reasons. The sent values are escaped like any other value.
- Use
InvalidPage::of(&document)for a whole document written from<head>. UseInvalidPage::in_layout(view, layout)for a view that goes into the site's layout (pass the same function as in the page's.layout(layout)). - This response is only for that person (
Cache-Control: private, no-store). It does not go into the shared cache. This 422 response is the only place where the Gate renders a page. - It is shown even without JS. The form and its content are in the response HTML itself. Server Islands such as the header are inserted with JS, as on any other page.
- Return it only when nothing was saved. If you save something and then return this page, a reload saves it twice. After saving, return 303.
- To show errors in place (without reloading the page), you can still call a POST API from a Client Island. You can also use both.
- Examples:
examples/min-form(no login), and the posting form ofexamples/knowledge-base(inside the layout).
JSON API
pub async fn add_json(deps: Deps, session: Option<Session>, body: ApiBody) -> Result<Json<AddResponse>, Reject> {
let s = session.ok_or(Reject::Login)?; // 401 if not signed in
let req: AddRequest = body.json()?; // 400 if the shape is wrong
let count = add_item(&deps, &s.user.id, &req.product_id, req.qty.unwrap_or(1)).await?;
Ok(Json::new(AddResponse { count })) // 200
}A GET API (Api::get) is a read-only route. It can receive a query (?slug=…). It gets the same GetDeps as a Server Island, so it cannot sign anyone out or purge the cache. To call it from the browser, call it from a page of the same origin. An origin is the combination of URL scheme (such as HTTPS), host name, and port.
Purging the cache (Purge)
- Tag the page:
.cache(Cache::Ttl(300)).tags(|p| vec![format!("product-{}", p.get("id").unwrap_or_default())]) - In the form or API that changed the data, purge by that tag:
deps.purge(&[Purge::Tag(…)])
- There are four kinds:
Purge::Page(that page),Purge::Tag,Purge::Prefix(paths that start with it), andPurge::Everything(everything). - Purge is limited to 5 calls per minute, with a burst allowance of 25. When you reach the limit, the result of
deps.purgetells you that the purge was rate-limited. - A purge can take from a few seconds to over ten seconds to reach every data center. Locally, in
hermet dev, a stand-in removes the entries at once (with no rate limit). Purge does nothing inwrangler dev. - Forms and POST APIs (
Deps) and webhooks (WebhookDeps) can purge the cache. A scheduled job records what to purge withdeps.purge_later, and the purge happens later in the same run. Server Islands and GET APIs (GetDeps) cannot purge, so following a link never purges the cache.