Frontend development

Explore frontend options for araara apps, from server-rendered HTML with typed views and htmx to OCaml browser clients.

Choosing what a route returns

An araara application is an HTTP server. Each route returns what the application defines for it. Some routes render HTML for a browser, some return JSON for a programmatic client, some do both, and many applications need only one of these. araara does not generate an API for a route, and it does not require one.

This documentation site serves HTML. It has no JSON API because no client uses one. A headless service might serve JSON without HTML, and another application might serve both. An application defines the routes its project needs.

When a single resource has both an HTML page and a JSON endpoint, the convention is to back them with the same context. This is called web/API parity, and the shared context holds the logic used by both. It applies when an application has both kinds of route.

For the UI, araara uses hypermedia as the default in its examples. HTML is rendered on the server and swapped into the page with htmx. Applications can also compile OCaml to JavaScript or use a JS/TS framework, as the last section describes.

Why hypermedia is the default: the server renders the domain data as HTML. The browser receives that HTML and swaps it into the page, so there is one rendering path for the data and no second client-side store to keep updated.

htmx, TyXML and ocsigen-i18n

When the UI is rendered on the server, araara uses three community libraries: htmx, TyXML and ocsigen-i18n. These libraries are community projects that araara adopts as conventions. Each one handles a different part of the work.

TyXML renders the HTML. Views are ordinary OCaml functions from data to a typed node tree: escaped by default, with htmx attributes and translation lookups written inline as plain function calls.

htmx makes that HTML interactive. An attribute on an element says which URL to call and where to put the HTML that comes back, so the page updates in place. This does not require JavaScript written for the page, and the state remains on the server.

ocsigen-i18n provides translations. Translations are stored in TSV files and compiled to typed lookups, so a missing or misspelled key is a compile error in a multilingual UI.

TyXML builds the markup with htmx attributes and i18n calls included. The server sends the markup, and htmx swaps it into the page. ocsigen-i18n provides the text in the selected language. This gives a typed, translatable, server-rendered UI without a bundler. A site such as this one can use it without hand-written JavaScript. The sections below describe each library.

The default: HTML over the wire

htmx can turn an element into a hypermedia control. An attribute names the URL to request and where to put the HTML that comes back. Server-Sent Events push fragments when state changes on the server. alpinejs handles state that does not need the server, such as an open menu or a focused tab. Other state is kept on the server.

A view function used for a page and for fragments

examples/htmx_fragments/main.ml
(* A view function renders a todo row. The full page and the htmx
   fragment response both call it. *)
let todo_row text_ =
  li ~a:[ a_class [ "todo" ] ] [ txt text_ ]

let todo_list todos =
  ul ~a:[ a_id "todos"; a_class [ "stack" ] ] (List.map todo_row todos)

todo_row renders one item. The full page calls it through todo_list, the POST handler returns it on its own, and an SSE push can stream it. All three paths use the same function.

The form declares the swap

examples/htmx_fragments/main.ml
(* The form posts via htmx and appends the returned <li>
   fragment to #todos. The page is not reloaded, and the
   example includes no application JavaScript. *)
form
  ~a:[
    hx "hx-post" "/todos";
    hx "hx-target" "#todos";
    hx "hx-swap" "beforeend";
    hx "hx-on::after-request" "this.reset()";
  ]
  [
    label ~a:[ a_label_for "text" ] [ txt "New todo" ];
    input ~a:[ a_id "text"; a_name "text"; a_required () ] ();
    button ~a:[ a_button_type `Submit ] [ txt "Add" ];
  ];

Read the attributes: Hx.post submits over XHR; Hx.target names the element to update; Hx.swap "beforeend" appends the response inside it. hx-on::after-request resets the form when the round trip finishes.

The handler returns a fragment

examples/htmx_fragments/main.ml
let create _params req =
  match form_value (Hcs.Request.body req) "text" with
  | None | Some "" -> Hcs.Server.respond ~status:`Bad_request "text required"
  | Some text_ ->
      let rec add () =
        let old = Atomic.get todos in
        if not (Atomic.compare_and_set todos old (text_ :: old)) then add ()
      in
      add ();
      (* htmx asked for a fragment: return only the new row. *)
      Hcs.Server.respond_html (Format.asprintf "%a" (Tyxml.Html.pp_elt ()) (todo_row text_))
in

The handler validates the input, updates the state, and responds with the new

  • . htmx inserts it into the list. The handler returns HTML that the browser can insert directly, so this interaction does not use a JSON response or a client-side store.

    $ dune exec examples/htmx_fragments/main.exe
    $ xdg-open http://localhost:8080

    Rendering HTML in OCaml

    The examples render HTML with TyXML, which expresses HTML as a typed OCaml DSL. Elements are constructors, text is escaped by default, and htmx attributes are ordinary HTML attributes. A view is a function from data to a node tree.

    examples/tyxml_components/main.ml
    type product = { name : string; price_cents : int; in_stock : bool }
    
    (* A component takes data and returns a node. It can be tested by
       calling it. *)
    let product_card (prod : product) =
      article
        ~a:[ a_class [ "card" ] ]
        [
          header [ h3 [ txt prod.name ] ];
          p [ txt (Printf.sprintf "$%d.%02d" (prod.price_cents / 100) (prod.price_cents mod 100)) ];
          (if prod.in_stock then
             button ~a:[ a_class [ "btn"; "btn--primary" ] ] [ txt "Add to cart" ]
           else span ~a:[ a_class [ "pill" ] ] [ txt "Out of stock" ]);
        ]

    Because a component is a function, it can be refactored as a function, and a unit test can call it and check the rendered string. TyXML is a convention araara adopts. Another server-side HTML approach can also be used, as htmx only requires that the response is HTML.

    Translations: ocsigen-i18n

    For multilingual server-rendered UIs, ocsigen-i18n turns TSV files into typed lookup functions, so a missing key is a compile error. Translations are stored next to the views that use them.

    examples/i18n_hello/main.ml
    let print_in lang =
      (* Every [%i18n ...] lookup below now resolves in [lang]. *)
      Translations.set_language lang;
      Printf.printf "%s:\n" (Translations.string_of_language lang);
      Printf.printf "  %s\n" [%i18n greeting];
      Printf.printf "  %s\n" [%i18n farewell]
    
    let () =
      (* [Translations.languages] lists the TSV columns in order: En; Es. *)
      List.iter print_in Translations.languages;

    Returning a fragment or a full page

    htmx requests carry the header HX-Request: true. Under the araara convention, one controller action renders both forms. If the request is from htmx, it returns the fragment. On direct navigation or refresh, it returns the same fragment wrapped in the full layout. The helper Render.html_partial req ~partial ~full selects between the two, so URLs can be bookmarked and refreshed.

    hx-boost needs separate handling. Boosted links are full navigations sent as XHR, and they expect the layout. They can be detected by checking HX-Boosted.

    Live updates and local state

    For server-pushed updates, the page declares a connection and a swap target with the htmx sse extension. It uses Hx.ext "sse", Hx.sse_connect on a container, and Hx.sse_swap on the element that receives events. The server responds with Hcs.Sse.respond and emits each update as an HTML fragment. This fragment often comes from the same row function the POST handler uses, with updates supplied by hive's pubsub after a context commits a write. The hcs documentation has a runnable SSE server that can be tested with curl.

    The examples/helpdesk app, open as two users at once. When the customer (right) opens a ticket, it appears in the operator's queue (left). The update is pushed over Server-Sent Events, without polling or a refresh.

    alpinejs covers state that does not need a request to the server, such as open/closed, hover, or a character counter. Attach x-data to the semantic element rather than a wrapper div. State that must survive a page reload belongs on the server and is reached through htmx. alpinejs is used for temporary UI state, such as whether a menu is open.

    A few conventions we follow: vendor htmx and alpine into priv/static/vendor/ and pin versions (the example uses a CDN only to stay single-file); keep one hand-authored stylesheet with semantic class names; prefer semantic elements over divs; and serve a strict Content-Security-Policy that lists the site's scripts by hash, with syntax highlighting done on the server.

    Other frontends

    An application that needs a rich client, such as a canvas editor, an offline-first app, or a single-page application, can use one with araara. The application can expose a JSON API for that client. The API is backed by the same contexts as any HTML routes, and any client that uses HTTP can call it.

    Other server-side HTML renderers

    TyXML is the araara convention. It is typed and is used in the OCaml web ecosystem. It is not a required dependency of hcs or of the layering rules, because htmx only requires that a controller returns HTML. A project can use a different server-side HTML DSL instead, such as pure-html. Templates or other renderers can also be used if they handle escaping and composition in a disciplined way.

    OCaml in the browser

    OCaml can also be compiled to JavaScript for use in the browser. Brr provides direct, typed bindings to the DOM and browser APIs. js_of_ocaml compiles existing OCaml to JS, and Melange compiles OCaml to readable JS and integrates with the npm and React ecosystems. Each of these can call araara's JSON API. Responses can be decoded with the same kinds of codecs that simdjsont uses on the server.

    For a rich client with live state, brote provides a reactive option. It uses incremental signals with cutoff and keyed-stable collections on a stdlib-only core that compiles to native code and to JavaScript. Its adapters serve live collections over an hcs WebSocket and replicate them across a hive cluster. The reactive graph runs in the browser, and messages carry state deltas rather than markup. brote can be used alongside server-rendered pages, on the screens that need a client with live state. See the brote reference and the trading-floor tutorial, which builds a brote application.

    ReasonML, ReScript, and JS/TS frameworks

    ReasonML and ReScript are ML-family languages that compile to JavaScript and are used with React. The frontend does not need to use an ML-family language. React, Vue, Svelte, SolidJS or a plain fetch() call can use the JSON API as they would use another HTTP backend. araara provides the server, and the application chooses its rendering technology.