Storefront Fragments¶
A storefront script that changes something on the page (a quantity in the mini basket, for example) asks the server for the parts of the page that change and swaps them in. The server stays the only thing that knows how to draw them: the script never builds markup, and never parses a whole page to find one part.
This page describes the contract between the server and the script, how to add a fragment, and the client helper. The reasons for this approach are in Front-End Direction, section 2.
The contract¶
Request¶
The script sends the usual request (the same URL and form a browser without JavaScript uses) with one extra header:
The value is a comma-separated list of fragment ids. An endpoint that can answer with fragments keeps the ids it serves and ignores the rest. When none are left, the endpoint behaves exactly as it does without the header.
Responses¶
| Status | Headers | Meaning |
|---|---|---|
| 200 | X-Badger-Notice: <code> (optional) |
The requested fragments, one after another. A notice means the change was refused in a way the page can show in place (for the basket, notEnoughStock). |
| 204 | X-Badger-Location: <path> |
The outcome needs a whole page (a refusal only the basket page explains, a payment in progress). The script goes to that path, which is where the redirect would have gone. |
Each fragment's root element carries data-fragment="<id>", so a response with
one fragment and a response with several have the same shape.
Fragment responses are Cache-Control: private, no-store. Every response of an
endpoint that can answer with fragments, fragment or not, carries
Vary: X-Badger-Fragment, so a browser's back/forward cache or a CDN never
serves a fragment as a page or a page as a fragment.
Fallback¶
Without JavaScript, nothing changes: the forms post and redirect as they always have. With JavaScript, anything the script doesn't expect sends the shopper to a full page load:
- a network failure, or any status other than 200 and 204;
- a redirect (the endpoint answered as a page);
- a 204 without a location on this site;
- a requested fragment missing from the response (a theme that doesn't have it renders nothing for it).
The page then shows where things stand, as it would without the script.
The server side¶
The classes are in web-mvc, package render.fragment:
StorefrontFragment: the allowlist. Each entry maps an id to a view name of the formtemplate :: fragment.FragmentRequest: the header names,requested(request, allowed)(the ids an endpoint serves, in the order asked), andisFragment(request)for code that must not count a fragment request as a page view or a search.FragmentResponses:fragments(list, model, notice)for the 200 (orfragments(list, model, own, notice), whereowngives each fragment attributes only it sees, on top ofmodel; andfragments(list, extensions, model, notice)with extensions too),elsewhere(path)for the 204, andvaryOnFragmentHeader(response).ExtensionFragments: extensions on a page as fragments (see below).
Both responses are ModelAndViews (the 200 wraps Spring's FragmentsRendering),
so a controller method keeps one return type for its page and fragment
branches. Each fragment's view goes through the storefront's view resolver, so
the shop's theme (and its fallback to Nova) applies.
Every page interceptor's postHandle still runs for a fragment response, the
204 included: Spring sees a view (the FragmentsRendering) with no view name,
so the interceptors that build page chrome (structured data, language sites,
ordering status, layout flags) do their usual lookups and add attributes the
fragments don't read. The currency (ShopCurrencyInterceptor, which
#shopMoney needs) and commerceChromeEnabled arrive this way. It is wasted
work, not wrong output; skipping it for fragment requests is a later
optimisation.
TenantAwareThymeleafView renders a template :: fragment view name by parsing
it as a fragment expression, as Thymeleaf's own view does, but only a plain
selection (path/to/template :: fragment-name: no parameters, no expression
syntax). Any other name, including one an admin stored as a page's or a
collection's template name, is looked up as a template file of that whole name,
as before, so nothing in it is evaluated.
Extensions as fragments¶
An extension on a page can answer as a fragment too, so a script can ask the
page for that one block again. Its id is ext-<extensionId>: the extension's
id (its configuration's id, or the BDGR_h... id derived for one stored without
an id; see Block ids and form posts) in lower case, with anything but letters and digits turned into hyphens
(ExtensionFragmentId.of, in commerce-core).
These ids depend on the page, so they can't be entries in StorefrontFragment.
The allowlist isn't weakened for them:
- the request's
ext-ids are only candidates (ExtensionFragments.requested: kebab-case, at most four, each at most 64 characters); - an id is only compared with the page's own placements, and only an extension
rendered on that page whose model carries the id answers
(
ExtensionFragments.find). An unknown or forged id matches nothing and is ignored, like an unknown fixed id; - every extension fragment renders through one fixed view,
fragments/extension-fragment :: extension-fragment(ExtensionFragments.VIEW_NAME). It draws the extension from its own model, exactly as a page's slot loop does, so the theme's copy of the extension's template is used. The id only ever selects among models the server built; nothing from the request reaches a view name or a template lookup.
An extension opts in by putting ExtensionFragmentId.of(extensionId) into its
model under fragmentId and writing it on its root element:
It also declares it on its class, with what it needs to render
(@RenderIsolation(value = RenderInput.ALONE, skippable = true, fragmentId =
true), see below). An extension that doesn't put the id in its model is never
answered for, whatever is asked.
Cost. The page controller asks ExtensionService.renderOnly for the
placements whose ext- ids were asked for. It runs only those (and any
extensions they must run after, see after below), in page order, with the
ids, form prefixes and cache keys the whole page gives them (both work from the
same plan of the page's placements). The globals, the other placements and the
page template don't run. The partial render falls back to
the whole page's extensions (as a page load runs them, minus drawing the page)
when:
- the request is in inline-edit mode, or carries form fields;
- an extension it would run needs its page (
RenderInput.PAGE, or not classified); - a placement it would leave out can't be left out (
skippable = false, or not classified).
When nothing asked for is on the page (or the extension asked for draws nothing, such as an ordering status that is hidden while open), the page is rendered: its extensions then run as for any page load, which costs about what it did before. Fixed fragments a page answers for (below) don't run the extensions at all.
Classifying an extension¶
Every BadgerExtension carries @RenderIsolation (RenderIsolationCoverageTest
fails on one without it):
value: what it needs to build the same model as on the whole page.ALONE(only its own arguments and services),NEEDS_PREPROCESSORS(also the page's preprocessors, which then run first) orPAGE(what other extensions did, or what only the page's controller provides).skippable: whether a render that leaves it out is still correct. Leaving it out must change nothing the other extensions see and nothing about the response, such as a save the next request depends on or a redirect.after: extensions that must run before it when they are on the same page, because it reads what they do. The basket actions name the full basket, which reconciles and prices the order the summary reads, so a partial render runs the full basket first (and doesn't return its model unless it was asked for).fragmentId: whether it answers to anext-id. Such an extension can't bePAGE.
An extension whose GET path nobody has checked is PAGE and not skippable, so
any page it is on is rendered whole. Relax it only after reading what the
extension reads and writes when its page is shown.
Every extension has been checked (November 2026). Most are ALONE and
skippable. The exceptions:
- the order confirmation blocks (order, ticket, appointment and gift card
summaries, and the sign-up offer) are
NEEDS_PREPROCESSORS: they read the confirmed order the page's preprocessor loads; - HTML, product HTML and Markdown blocks run
afterthe full basket, because in dynamic mode their templates are given the order it reconciles and prices; - the checkout steps change the shared order while the page is shown: personal
details and the two address steps put empty objects on it, and the delivery
chooser saves and reprices it. None of them can be left out, the delivery
chooser is
PAGE, and the payment step runsafterall four, so a checkout page is always rendered whole.RenderIsolationCoverageTestpins this; - the collection product grid is
PAGE.
A write on first view that any later request would redo the same way (a site's signing key created when it is first needed, a customer's till card code) doesn't stop an extension being skippable.
Pages¶
A page (/p/..., PageController) answers for:
restaurant-basketandordering-status, from the display order and what the interceptors add, without running the page's extensions;- its extensions, by their
ext-ids.
Fixed fragments come first in the response, then extensions in the order asked. When nothing asked for is on the page, the page is rendered as it is without the header. A request with the header is never counted as a page view. Every response varies on the header.
Other pages that draw extensions (products, collections) don't answer for them
yet. Asked for a fragment, they send the whole page, in which the helper still
finds an element with that data-fragment: it works, but costs a whole page and
may count as a view there.
The basket endpoints¶
/basket, /basket/update, /basket/remove and /basket/clear serve
mini-basket-content, header-basket and restaurant-basket:
- a change that went through (or changed nothing): 200 with the fragments;
- not enough stock: 200 with the fragments and
X-Badger-Notice: notEnoughStock; - invalid input, a refusal with a reason (missing options, a kitchen that isn't taking orders, an unknown variant) or a payment in progress: 204 with the basket page, and its error query, as the location.
They render the fragments from the display order read back as saved, as the
basket page would after the redirect, and skip everything else a basket page
loads (the page, its extensions, stock). Like the basket page, they show the
lines' stock notices ("only 2 available") once: having drawn them, they clear
them from the saved order, so the next page's drawer doesn't repeat them. The
clear writes the notices alone (OrderService.dropShownStockNotices), never the
page's copy of the order: the change that left a notice also started a reprice,
which may finish while the page renders, and saving the copy would put the
basket back to "repricing" with the old prices, waiting for prices forever.
GET /basket with the header answers with the same fragments as the basket
stands, changing nothing in it, for a script whose basket was changed by
something else on the page (Bistro's drawer, after the restaurant menu adds in
the background). The mapping only matches a request that carries the header, so
a GET /basket without it is handled exactly as before. Asking it for no
fragment it serves redirects to the basket page.
The listing endpoints¶
/search, /c/** and /collection/** serve facet-total: how many products
the listing holds with the request's filters. The template is
nova/fragment/facet-total.html, shared by every theme:
The text is the search.filters.total message (a choice on the count); the
number is in data-facet-total for scripts.
Each controller keeps its page method, which returns a view name as before, and
maps a thin handler over it that adds Vary and turns the answer into a
response (FacetTotalFragment in render/search). Asked for facet-total, the
page method stops straight after resolving the listing and running its search
for one product: no cards, stock, extensions, category counts, search rule,
experiment arm or content search, and nothing recorded (no search term, page
view, shop activity or product impressions). A filter that would move a category
page to its brand landing page isn't moved: the count is the same either way.
A listing that answers with a redirect (a hidden category asking a guest to sign in, a collection moved to a category, a search scoped to a category) still redirects, and the script falls back as for any redirect.
The listing traffic guard (see Listing Traffic Guard) treats a count like any other filtered listing request. The header never exempts a request from it.
The phone filter sheet (nova/js/modules/facet-sheet.js) asks for the count of the
filters a shopper has staged, 200 ms after the last tap, with an abort key, so a
newer count replaces one still on its way. It only reads the count from the
response; nothing on the page is swapped. If the helper isn't on the page or the
request fails, the apply button keeps its plain label and applying still
navigates to the filtered page. Every theme's head loads fragments.js (see
The client helper), so it is there on every listing.
Before the fragment, the sheet fetched the whole listing page with an
X-Badger-Count-Preview header and read the first data-facet-total from it.
A page opened before the change still runs that script until it is reloaded, so
/search and the trackers still treat that header as "not seen", and the pages
keep their data-facet-total attributes.
The product page¶
GET /product/** serves quick-add: the listings' quick add dialog
(ui/quick-add.html :: quick-add, Nova's in every theme). A card's "Choose
options" link (data-quick-add) is the product page's own URL, with ?v= when
the shopper was looking at a colour, so without JavaScript it simply opens the
page. nova/js/modules/product-cards.js asks that URL for the fragment and
swaps it into the listing's <dialog>.
ProductController.handleProduct varies every response on the header. Asked for
quick-add, it looks the product up, checks the shopper may see it, and asks
QuickAddViews for the view (QuickAddView, built from the variant picker's
own payload, VariantDisplayer.buildSelectorResponse: enabled variants, their
stock, each colour's swatch). It runs none of the page's extensions, builds no
breadcrumbs or delivery lines, and records no page view or search click.
- A product the dialog can sell: 200 with the fragment.
- Anything else (no enabled variants; bespoke, donation, price-as-quantity or event ticket products; a dish ordered from the restaurant menu; an appointment; quick add switched off; a product this shopper can't see): 204 with the product page as the location, so the script goes there.
The fragment holds no script. The script finds the SKU from the checked radios
by key (the positions of the values, 1.0) in the list the fragment carries,
and copies that SKU's price and stock line, which the server drew, into place.
The form posts to /basket like any add-to-basket form, so the shared add to
basket sends it (see Add to basket): where the theme listens
for adds, its listener does, otherwise the script calls
NovaUi.addToBasket.send. The dialog closes when the basket fragments are
swapped in.
The basket page¶
A post to a page (POST /p/{page}, PageController) serves
basket-items-card and basket-summary-card: the basket page's lines (the
full basket extension's card, extensions/fullBasket/basket) and its order
summary (the basket actions extension's card, extensions/fullBasket/basketActions).
The collect-or-deliver script (basket-handover.js) posts its forms with both.
These cards are inside extension templates, which read their extension's model
as model. Each card is also a fragment without parameters (th:fragment on
the card itself, which repeats the checks and th:with around it on the page),
and the controller renders each one with its own extension's model as model
(the own attributes of FragmentResponses.fragments). It finds that model
among the page's rendered extensions by the template the fragment is in. The
post itself runs the page's extensions, as a post always does. Each card names
the extension it is drawn from (StorefrontFragment.extension()), and the GET
the post redirects back to runs only those (ExtensionService.renderOnly): the
full basket, then the basket actions, which run after it because they read the
order it reconciles and prices. They keep the ids and form prefixes they have on
the page. When another extension on the page can't be left out, or one of the
two needs its page, every extension on the page runs as before. Either way the
page template, with its header, navigation and other blocks, isn't rendered.
- The post redirects back to the same page (post/redirect/get, as every collect-or-deliver choice does): the cards' extensions (or, as above, all of the page's) run as that GET would run them, with the redirect's query (which carries the notice of what changed) and the order read back as saved. 200 with the fragments.
- The extensions answer the post in place (no redirect): the fragments are drawn from that answer. 200.
- The redirect goes elsewhere on the site (the store picker): 204 with that address. A redirect off the site stays a redirect, which the script treats as a reason to load a page.
- A fragment can't be drawn (its extension isn't on the page, or uses another layout, such as the read-only summary) or the basket is being paid for (its notice sits above the lines, where no fragment reaches): 204 with the page.
The lines card carries data-order-repricing, so basket-v2.js (listening for
novaui:swapped) knows whether to poll for prices still being worked out. The
phone checkout bar sits outside the summary card and watches the new card after
a swap. The heading's item count, the page's stock and payment notices and the
empty basket are outside the cards: a change that can alter them (a quantity, a
removal) still loads the page.
The header's store link isn't a fragment either: in each theme it is written into the navigation. So when the page shows it, choosing a store in the chooser posts the ordinary way and the page loads again.
The full basket extension also adds fragments.js to the basket page's
scripts whenever the collect-or-deliver choice is shown, so the page doesn't
depend on the theme's head loading it. FragmentCoverageTest checks these two fragments in every theme.
Adding a fragment¶
- Pick a fragment that takes no parameters, in a template whose name is the
same in every theme, so each theme's own copy is used. Give its root element
data-fragment="<id>". Ids are kebab-case and global: the script replaces every element on the page with that id. A part of an extension's template can be one too: putth:fragmenton the part itself, have it work out what it reads frommodel(it doesn't see theth:witharound it), and render it with the extension's model asmodel(see the basket page). - Add an entry to
StorefrontFragmentwith the id and the view name. - In the endpoint, call
FragmentResponses.varyOnFragmentHeader(response)on every response, askFragmentRequest.requested(request, allowed)for the ids it serves, and when the list isn't empty returnFragmentResponses.fragments(orelsewhere) with only the model those fragments need. - Tell
FragmentCoverageTestwhich template includes the fragment on a page. The test renders every fragment for every theme whose head loadsfragments.js, and fails when one has nodata-fragmentroot or isn't included, unless the gap is listed with its reason. A fragment the script only reads and never swaps in (facet-total) is listed as read-only instead. The test also checks that every listing page that loadsfacet-sheet.jsloadsfragments.js, in the theme's head or on the page, and that the extension fragment wrapper draws an extension with itsext-root in every theme whose head loads the helper.
For an extension, there is nothing to add to the enum: give it a fragmentId
and @RenderIsolation(..., fragmentId = true) as described under
Extensions as fragments.
The client helper¶
nova/js/fragments.js adds NovaUi.fragments. The Brock-family heads load it,
then nova/js/add-to-basket.js (see Add to basket), before
nova/js/ui-components.js, which adds the rest of NovaUi without replacing
it. Nova's, Ridge's and Diorama's heads load the first two, for the shoppable
image block's add to basket. An extension whose script uses the helper can
require it too (@settBuilder/themes/nova/js/fragments.js), as the restaurant
ones and the full basket do. In a Brock-family theme the file then runs twice
(once from the footer, then from the head's deferred copy, which replaces
NovaUi.fragments with an identical helper), so read window.NovaUi.fragments
when you use it rather than keeping it from load time.
NovaUi.fragments.request(url, { ids, method, body, key })¶
Sends the request with the header and returns a promise of { els, notice, location }, where els maps each id to its new element. It rejects on anything the fallback list above names. A request with the same key as one still running aborts the earlier one (the rejection then has aborted set).
NovaUi.fragments.swap(result, { transition, focus, announce, status })¶
Replaces every [data-fragment=<id>] on the page with the new copy. There is no morphing. If focus was inside what was replaced, it goes back to the element with the same id or data-focus-key; failing that, to focus (an element, or a function called with the new elements). announce is written to status, an aria-live region, after clearing it, so the same words are read again. transition wraps the swap in a view transition, unless the shopper prefers reduced motion. Each new element fires novaui:swapped (bubbling, with { id, el }).
NovaUi.fragments.submit(form, { ids, submitter, key, fallbackUrl, swap })¶
Sends the form's fields and the button that submitted it, then follows a 204's location or swaps the fragments. swap is swap()'s options, or a function of the result that returns them (to choose the announcement once the notice is known). On failure:
- the request never reached the server (
fetchitself failed): the form is submitted normally, as it would be without the script; - the server answered (another status, a redirect, a fragment missing or cut
off): the change may already have been made, so a POST is never sent again.
The helper goes to
fallbackUrl, or else reloads the current page. A GET form goes to its own URL.
Pass fallbackUrl for any POST whose outcome a page shows (the mini basket
passes the basket page).
NovaUi.fragments.supported()¶
Whether the browser has what the helper needs. Without it, keep the plain link or form.
Rules¶
- View names only come from the allowlist. Never build a view name from the request. The view keeps Thymeleaf's check that refuses a view name containing an expression that also appears in the request.
- No scripts in fragments. The helper removes any
<script>in a response before swapping, so it never runs. Behaviour belongs on delegated listeners (on the document or a container that stays) and on thenovaui:swappedevent. - No shopper-facing words in the script. Announcements come from the page's
markup (
data-text-*ordata-msg-*attributes), as everywhere on the storefront. - Fragment requests are not page views. Anything that records a view or a
search checks
FragmentRequest.isFragment(request)first.BadgerBaseController.recordPageViewdoes, for every storefront controller, and so do search term analytics and listing impressions (SearchController.isCountPreview). - Every response varies on the header, including redirects and pages, on any endpoint that can answer with fragments.
The restaurant menu and ordering status¶
The restaurant menu (restaurantMenu) and the ordering status
(orderingStatus, and Bistro's header strip) are the first extensions that
answer as fragments. Both extensions load nova/js/fragments.js themselves, so
they don't depend on the theme's head loading it.
Without the helper, the menu keeps its plain links and forms.
- The item sheet. Add asks the item's URL (
?item=<dish>) for the menu's ownext-id. The page answers with the menu in its item view, and the sheet shows the form from it. On failure, the shopper goes to the item page. - Adding a dish and changing a line. The sheet's form and the basket panel's
quantity and remove forms go through
NovaUi.fragments.submitforrestaurant-basket(extensions/restaurantMenu/basket :: panel, which reads onlyorder), with the basket page as the fallback. A refusal the basket page explains (a choice missing, a kitchen not taking orders) arrives as a 204 and the shopper goes there.notEnoughStockis announced in the panel. Every copy of the panel (beside the menu and in the phone sheet) is replaced; focus goes back to the same button on the same line, else the panel's title. - Prices still being worked out. The panel is asked for again from the page
(
restaurant-basket), up to five times; if that fails, the page reloads. - A postcode check that changes the restaurant. The script asks the page
for each status block on it: the
orderingStatusbanner by itsext-id, and Bistro's strip asordering-status(fragment/nav :: ordering-status, from theorderingStatusattributeOrderingStatusInterceptoradds). It swaps them in, wires the new collection / delivery switches and shows the checked area. If that fails, the page reloads.
The menu used to get its basket panel from an rmView=basket view of the page
and the item form and status by parsing whole pages. Both are gone.
Bistro's own mini basket drawer is still refreshed by bistro.js (it listens for
rm:basket-updated), and Tend has no ordering status in its header.
The mini basket¶
The mini basket in the Brock-family themes (nova/ui/mini-basket.html) is the
first user. Its quantity, remove and clear forms call NovaUi.fragments.submit
for mini-basket-content and header-basket, with the basket page as the
fallback, and show a stock notice in its alert.
Whichever script swapped the basket fragments in (the drawer's own forms, an add
to basket, Bistro), the mini basket follows the novaui:swapped events: a new
header link is marked as controlling the drawer again, and new drawer content
has its prices polled while they are still being worked out.
Bistro and Tend write their own header basket links into their navigation
instead of including the theme's mini-basket fragment, so those links aren't
replaced. The mini basket keeps their count in step from the drawer's
data-item-count, and their aria-label (which also states the count): each
link carries its label's message unformatted in data-label-pattern
(#{bistro.basket.aria}, with no arguments), which
NovaUi.addToBasket.relabel(link, count) fills in with the new count, in the
page's language.
Add to basket¶
nova/js/add-to-basket.js adds NovaUi.addToBasket, the one add to basket the
themes and the shoppable image block share. It sends an add-to-basket form (a
form that posts to /basket) as it is, through NovaUi.fragments.request,
asking for header-basket always and mini-basket-content where the page has
the drawer (Nova's pages have no drawer, and every theme can draw the header
basket). The fragments are swapped in, then the caller confirms the add its own
way.
NovaUi.addToBasket({ describe, added, fallbackUrl, swap })listens for every add-to-basket form submitted on the page, unless the submit was already prevented (a variant picker still missing an option, the shoppable image's own forms).describe(form)reads what is being added before the request, since the chosen options can change after.added(ctx)is called after the swap with{ form, item, button, header, content, result }:headerandcontentare the fragments as the server drew them, so a theme reads the new count and subtotal fromheadereven where its page shows its own links (Bistro, Tend). It returns false, and leaves the forms to post normally, where the browser can't add in the background.NovaUi.addToBasket.send(form, { submitter, item, added, busy, omit, ids, fallbackUrl, swap })sends one form. The submitter's name and value are sent, as a browser would.busy(on)shows the request in progress (by default the button getsaria-busyand is disabled); the form is marked either way, so a second press while it is busy sends nothing.omitnames fields not to send (the shoppable image's two-choice buttons, which only find the SKU).
What comes back, and where it leads:
- the fragments: swapped in, then
added(ctx); X-Badger-Notice(nothing could be added, such as a sold-out product): the basket page with the notice as itserror, as the redirect without script shows it;- a 204: its location (a refusal the basket page explains, a payment in progress);
- a request that never reached the server: the form is submitted normally;
- anything else once the server has answered (another status, a redirect, a missing fragment, a confirmation that fails to draw): the add may already be in the basket, so it is never sent again, and the shopper goes to the basket page.
Two adds can overlap (two cards pressed in quick succession). Neither is aborted, since an aborted post may or may not have reached the server; an answer that arrives after a later add's has been swapped in is not swapped over it.
The Brock-family themes open their "added to basket" pop-over from added. A
form marked data-basket-describe (the quick add dialog) describes itself
instead of going through the theme's describe(form): its data-item-name, the
shown [data-item-price], the picture in [data-item-image] and the checked
[data-item-option]s' data-label (NovaUi.addToBasket.describeSelf). The
shoppable image block confirms in its own panel. Nova's header basket is a
dropdown whose root is the header-basket fragment, so its count, label and
list are swapped in. Ridge and Diorama write their own basket links and have
no drawer: a background add there leaves their count as it was until the next
page, as before (FragmentCoverageTest lists these gaps).