hermet hermet SSR. Islands. Rust.

Writing pages

As in your first site, you write how the page looks in HTML and the data you pass to it in Rust. To add a page, follow these steps.

  1. Create an HTML template and a Rust type with the fields that you pass to it.
  2. Write a function that prepares the values to show. This guide calls this function Load.
  3. Include the new page's Rust file from src/pages/mod.rs, and register the URL and the page in src/manifest.rs. This pairing of a URL and what handles it is called a route.

Where files go

The folder that you put a file in gives the file its role. File names are plain, such as product.rs and product.html (names in lowercase letters and _ are recommended).

Folder What goes there <script>
src/pages/ Pages and their parts. Pair product.rs (the type and Load) with product.html. Not allowed
src/components/ Everything else. Put the shared layout (layout.html), components that you embed in pages, Server Islands and Client Islands here. At most one per file
  • If you put HTML outside these two folders, the build stops and tells you where HTML goes.
  • The file name does not decide whether a component shows per-user data (a Server Island). A component is a Server Island when a page's or a layout's template wires it in islands { … } (Server Islands). Only the function wired there receives the session (who is viewing). Every other component goes into the HTML of whatever calls it. When a page's Load calls it, it becomes part of the shared HTML. When a Server Island's function calls it, it becomes part of that Island's fragment. You can use the same component from both.

Everything that you put in src/components/ is a component. Components come in three kinds, by role.

Component (src/components/)
├─ plain component : rendered as it is into whatever calls it: the shared HTML, or an Island's fragment (layout, badge, ...)
├─ Server Island   : data-island plus islands { … }; filled in later, per user
└─ Client Island   : has a <script type="module"> and runs in the browser
   (one component can be both a Server Island and a Client Island, for example cart.html)

Where small parts go

Small pieces of HTML, such as one row of a list or a message shown only on an error, are also each a template of their own (Template rules). So that you do not get lost when there are many, put them in a folder named after the one that uses them.

Part Where Example
Used by one page only src/pages/<page>/ pages/article/paragraph.html
Used only inside one component src/components/<component>/ (the component itself stays components/<component>.rs and .html) components/post_form/error.html
Used by several pages or components Directly in src/components/ components/article_row.html
src/
  pages/
    article.rs, article.html
    article/                 ← parts only article.rs uses
      paragraph.html
      tag.html
  components/
    layout.html              ← the shared layout
    article_row.html         ← a part that several pages use
    post_form.rs, post_form.html
    post_form/               ← parts only post_form uses
      error.html
      notice.html

This way, you only need to look directly inside pages/ and components/ to see which pages and main components the site has.

  • Small parts get no .rs of their own. Write their type and their hermet::template! line in the .rs of the one that uses them (article.rs in the example above). When a part gets more work of its own, create a .rs next to its HTML.
  • Give a component with a <script> a name of its own, such as components/search.html. Do not use a name like components/search/index.html (JS is served under the file name, so if two of them have the same name, the build stops).
  • Use the function name render only for functions that you wire in islands { … }. Give another name to a function that a page's Load also calls. This is a convention of the samples. The build does not check it.

Three layers

Where What you write
The site's list of URLs (src/manifest.rs) You state what each URL returns, who may view it, and how long it is cached.
Pages and handlers (functions that handle requests) They prepare the data that a page shows, and handle form submissions.
Middleware (only for sites that need it) It blocks a request, or redirects it to another URL, before the request reaches a page. You can also use it to add headers to the response.

The shape of a page

Take a product page as an example. For the URL /products/42, Load takes out 42, finds the product, and passes its name and price to the template. In this excerpt, catalog finds the product and cart shows the cart. Both are components that your site provides.

src/pages/product.rs
pub struct ProductView { name: &'static str, price: String }
// product.html is a whole HTML document. Wire cart::render to its data-island="cart"
hermet::template!(ProductView, "pages/product.html", islands { "cart": cart::render });

pub async fn load(_shared: Shared, params: RouteParams) -> Result<Option<ProductView>> {
    let Some(p) = catalog::find(params.require("id")?) else { return Ok(None) }; // 404
    Ok(Some(ProductView { name: p.name, price: catalog::yen(p.price) }))
}
src/manifest.rs
.page(Page::at("/products/{id}", product::load).cache(Cache::Ttl(300)))   // may be up to 300 seconds old
  • product.html is a whole HTML document with <head> (with {hermet:head} inside) and <body>. A load that returns a whole document can go to Page::at as it is. Server Islands are written in the template's islands { … }, so they come with the view. In the manifest, write only the route, who may view the page, and how long it is cached.
  • If the template is a fragment with only the main content (meant to go into the site's shared layout), make it a document on the page side with .layout(layout) (the samples' framed(…) does this). layout must be a function that returns a whole document. .layout wires both the Islands of the page's template and the Islands of the layout's template (the law article example). Compilation stops if you pass a fragment's PageBody to Page::at as it is, return a fragment from .map(), or return rendered Markup from Load.
  • A part of the path in curly braces, such as {id}, can be read in Load with params.require("id")?. If the name differs from the one in the manifest, the result is an error, not a 404, and the log shows the name that was asked for and the names that the route has. For a value that may or may not be there, use params.get("id").
  • If Load returns Ok(None), the response is a 404.
  • A page's Load does not receive the query string (?q=…). The shared HTML is the same whatever the query is. To change the content by a value, put the value in the path, such as /search/{q}, call an API from a Client Island, or pass the query names that you declared to a Server Island (Receiving the query).
  • When several routes match one path, the path is compared from the left, and the route whose fixed text comes first wins (/docs/search wins over /docs/{slug}). The order in the manifest does not matter.
Three ways to write a page
  • A whole document: you can pass the load function to Page::at as it is (the same shape as your first site; for example, .page(Page::at("/about", about::load).until_deploy())). If the page has a Server Island, write it in the template's islands { … }, and it comes along (the shape of the product page above). load can take only Shared, RouteParams and Member, in this order, and each one is optional. It returns Result<View> or Result<Option<View>>, where None is a 404.
  • A fragment with only the main content: put it in the shared layout on the page side with .layout(layout) (the samples' framed(…)). The Islands of both the page and the layout are wired. If you pass the fragment to Page::at as it is, compilation stops.
  • Load returns a plain struct (data that is not a template): in PageBody::new(load).map(f), f turns it into a whole-document template. The Islands that are wired are those of the document template that f returns.

Choosing the cache

For a page whose HTML is made when it is requested, state on the route how long an old response may be reused. For a page that uses static generation, write .prerender(…) instead.

Setting When to use it
.until_deploy() A page that can keep the same content until the next deploy. You can choose it for a page whose Load does not take shared data (Shared), such as PageBody::bundled or a load without Shared in its arguments.
.cache(Cache::Ttl(seconds)) A page that may show older content for a set time. For example, Ttl(300) is 5 minutes. TTL is how long a cached copy may be reused.
.cache(Cache::None) A page whose shared HTML is made again on every request.

Even with .until_deploy(), the HTML is made in each data center when the first request arrives there. So that every data center has the same content, made from the data at deploy time, a page that uses Shared to read data that can change after the deploy cannot use this setting.

Reading data that everyone shares (Shared), and typed names

Cloudflare has D1, which handles data with SQL, KV, which stores pairs of names and values, and R2, which stores files. To use them from a Worker, give each one that you connect to a name in cloudflare.rs. Such a named connection is called a binding.

Shared is the way in for a page's Load to read shared data. The build makes a Rust constant for each binding, which holds the binding's name and kind (hermet::D1, hermet::Kv, hermet::R2). In src/lib.rs, put pub mod bindings { hermet::bindings!(); }. Then you can pass the constants as they are to the manifest, to queries and to R2 files.

cloudflare.rs
pub const DB: D1 = D1::binding("DB");

fn default(_: &Ctx) -> Result<Config, ConfigError> {
    Ok(Config::new().compatibility_date("2026-11-13").worker(
        Worker::new("my-site").d1(DB, D1Db::id("…").name("my-site-db")),
    ))
}
src/manifest.rs and Load
App::new(hermet::generated!()).shared_d1(crate::bindings::DB)   // declare the D1 that pages' Load reads

pub async fn load(shared: Shared, params: RouteParams) -> Result<Option<ProductView>> {
    let id = params.require("id")?;
    let row: Option<Row> = shared
        .first(crate::bindings::DB, "SELECT * FROM products WHERE id = ?", &[id.into()])
        .await?;
    // …
}
  • If you pass a constant of the wrong kind (a KV constant where a D1 goes, for example), compilation stops with an error. You can also write the name as a string ("DB"), but then the kind cannot be checked.
  • Give one name the same kind in every mode. To check that no name has different kinds, run hermet check without a mode. It compares the modes that it could evaluate. What a binding connects to (a database ID, for example) can change per mode.
  • Shared is read-only. It accepts a single statement that starts with SELECT.
  • Use shared.first for one row and shared.all for several. Row is a serde::Deserialize type that you define.
  • A site normally has one D1. Give each kind of data, such as articles or posts, its own table, and declare that D1 with App::shared_d1. A page's Load reads it through Shared. Forms, APIs and Server Islands read and write the same D1 through deps.bindings().d1(…). When a form changes an article, clear that page's cache with deps.purge(…).
  • What Hermet guards is this: a page's Load does not receive who is viewing, and it only reads. So one person's data never gets into the HTML that is served to everyone. Which tables to read, and from where to write, is for your site's code to decide.

Putting data that everyone shares in KV

Data for which pairs of names and values are enough, such as notices or settings, can also go in KV. Declare the KV with App::shared_kv in the manifest, and a Load can read it through Shared. Shared only reads it.

src/manifest.rs and Load
App::new(hermet::generated!()).shared_kv(crate::bindings::NOTICES)   // declare a KV for shared data

pub async fn load(shared: Shared, _params: RouteParams) -> Result<Option<NoticeView>> {
    let banner: Option<String> = shared.kv_text(crate::bindings::NOTICES, "banner").await?;
    let notice: Option<Notice> = shared.kv_json(crate::bindings::NOTICES, "maintenance").await?;
    …
}
  • There are four ways to read: kv_text for text, kv_json to turn JSON into your own type, kv_bytes for bytes, and kv_html for HTML that is already converted (only HTML that passes the check for safe HTML).
  • A key that is not there gives Ok(None) (a normal case: there is just no value). A KV that is not declared, JSON that does not fit the type, and HTML that fails the check give Err, and the page answers 500 (it is not cached either).
  • You cannot write through Shared. Forms, APIs, scheduled jobs and the like do the writing (they use the same KV through deps.bindings().kv(…)).
  • The KV that stores login sessions (App::sessions) cannot be declared as shared data. If you declare it, the Worker stops at startup.
  • D1 or KV: in production, a value written to KV can take a little time before it can be read everywhere (eventual consistency). So even if you clear the cache right after a write, a page may be made with the old value and be cached again. Keep data that must change at once (stock, status) in D1, and data that may lag a little (guidance text, settings) in KV.

Template rules

Values are escaped automatically to fit the place they go into (escaping replaces characters such as < with a safe form). For safety, there are rules like these:

  • You can put values only into element content and quoted attribute values.
  • href and src accept only the validated Url type. The whole attribute value must be a single {field}.
  • Event attributes such as onclick, and the style attribute, are not allowed.
  • Templates have no if or for. The HTML only fills in values, and you write branches and loops in Rust. This is because the server makes the HTML either way, and Rust already has match and if / else (the compiler finds a case that you forgot). Use Markup::each for loops and Markup::of for embedding. "Show only when there is one" can be written as a list of zero or one item (Markup::each(reason.map(|message| FieldError { message }))). A template with a Server Island placeholder (data-island) cannot be passed to either of them (write placeholders in a page's or a layout's template).
  • Hermet decides which types you can put in. Convert your own types to String or a number first.
  • You cannot use markup that browsers and Hermet read differently (<iframe>, <noscript> and others). If you make a mistake, the build stops, so you do not need to memorize these.

Why templates are HTML files bound with hermet::template!

  • They are ordinary .html files, so editor highlighting, completion and display on GitHub work as they are.
  • The only syntax is {field} and {hermet:head}, so it never breaks how HTML is written.
  • hermet::template! turns the HTML into Rust code at compile time. A misspelled field name or a wrong type is a compile error, and the Worker needs no template engine.
  • A template with <head> and <body> is treated as a whole page document. If you forget to put a fragment in the layout, compilation stops where the page is registered.

A shared layout (header, footer)

When several pages use the same header and footer, your site provides a layout. Load passes each page's data, and .layout(layout) combines the page's content with the shared layout. Write the layout's Islands (such as the header) in the islands { … } of the layout's template. For a page that is rendered on request, the HTML of the frame and the main content together is cached per URL.

src/components/mod.rs
pub trait PageView: Template { fn title(&self) -> String; }

pub struct Layout { title: String, main: PageMarkup }   // the page's HTML, from main.into_markup()
// wire the layout's Island (the header) in the layout's template
hermet::template!(Layout, "components/layout.html", islands { "header": header::render });

// .layout gives the view as a PageMain. Read it with view(), and make it the main content with into_markup()
fn layout<V: PageView>(main: PageMain<V>) -> Layout {
    Layout { title: main.view().title(), main: main.into_markup() }
}

// .layout(layout) closes the page (the Layout that layout returns is a whole document with <head> and <body>).
// It wires both the Islands of the page's view and the Islands of the layout
pub fn framed<V: PageView + 'static, K, D>(body: PageBody<V, K, D>) -> PageBody<Closed, K, D> {
    body.layout(layout)
}

// each page
pub fn page() -> PageBody { framed(PageBody::new(load)) }

Example: a law article (the page's Island and the layout's Island)

In the law sample, the article page has "Favorites" (favorite), and the shared layout has a header (header). List each Island in the declaration of the template that has its placeholder.

src/pages/article.rs (excerpt)
// wire the render function of Favorites to data-island="favorite" in article.html
hermet::template!(ArticleView, "pages/article.html", islands { "favorite": crate::components::favorite::render });

pub fn page() -> PageBody {
    framed(PageBody::new(load))   // do not write the Islands here (they come with the template)
}
src/components/mod.rs (excerpt)
// wire the header's render function to data-island="header" in layout.html
hermet::template!(Layout, "components/layout.html", islands { "header": crate::components::header::render });

pub fn framed<V: PageView + 'static, K, D>(body: PageBody<V, K, D>) -> PageBody<Closed, K, D> {
    body.layout(layout)   // wires the Islands of both the page (favorite) and the layout (header)
}
src/manifest.rs (excerpt)
// the manifest has only the route, who may view it, and the cache. It says nothing about Islands
.page(Page::at("/law/{slug}/{num}", pages::article::page()).cache(Cache::Ttl(LAW_TTL)))

When you open an article, the header and favorite Islands arrive once each. The law sample's tests/islands.cjs counts them to check this.

Put a page that has Islands in the layout with .layout

.map(f) wires only the Islands of the document that f returns (here, the layout). Suppose that you write framed above with .map and try to embed the article with Markup::of(&view). The article's template has a placeholder (favorite), so hermet check --full points to that line and stops compilation (`ArticleView` has Server Island placeholders). With .layout, the layout function receives a PageMain, and its into_markup() makes the article the main content. The article's Islands are wired too. Then add a test that checks that the page's Islands arrived by counting the Island fragments that arrived, not by an HTTP 200.

Styles (CSS)

  • Write the CSS of a page or component in a <style> in its HTML. Write site-wide CSS in src/global.css. The build merges all of it into one and puts it in {hermet:head}.
  • Classes defined in a file are renamed per file (counter → counter_1a2b3c). They never collide with classes in other files.
  • To change a component's state from JavaScript, add or remove an attribute such as data-open, instead of a class (the build renames classes). CSS can select that state with [data-open].
  • In a component's CSS, choose what a rule applies to with classes defined in that file. Rules for elements, such as button { … }, go in global.css. ID selectors, :is() and CSS nesting are not allowed either. If you make a mistake, the build stops.