Storefronts

Any Swell app can add features to storefronts by declaring them under storefront in its swell.json: embed blocks, data sources, form actions and product ratings. A storefront that supports extensions reads the declarations of the store's installed, active apps, from the version each store has installed, and merchants use them in its editor. Each extension works on a storefront that supports it. This page describes what a supporting storefront does; see Storefront support for which storefronts do today.

An app reaches a storefront in three ways:

ExtensionKeyWhat it doesApp code in the page
Embedsstorefront.embedsPuts the app's own UI on a page: a script, and blocks merchants place in the editor.Yes
Data sourcesstorefront.dataGives the theme the app's data, which the theme renders with its own markup on the server.No
Actionsstorefront.actionsLets the theme post a form to one of the app's functions. The storefront applies the answer: cart lines, a message, a redirect.No
App pagesstorefront.pagesGives the storefront page types of the app's own, at addresses it owns, rendered in every theme.No

Use an embed for interactive UI that runs your code, such as a booking calendar or a packages list. Use a data source for content that appears in many places or that search engines must see, such as a rating or a customer's quotes. Use an action for a form whose logic stays in your app, such as a quick order by SKU.

All three sit next to each other in swell.json:

{
  "storefront": {
    "embeds": {
      "version": 1,
      "script": "frontend://embed.js",
      "blocks": [
        "…"
      ]
    },
    "data": [
      "…"
    ],
    "actions": [
      "…"
    ]
  }
}

The app is always named by its installation's app slug, the id in its swell.json. A declaration never names its own app, so it can't claim another app's id.

Any app type can declare extensions. An app that only adds storefront extensions uses the default type, admin, or integration when it connects an outside service. Don't use storefront: that type makes the app a storefront of its own.

Swell validates extension declarations, stores them with each app version, and runs the app proxy and the signed context for every storefront. Each extension works on a storefront that supports it, and any storefront app may implement them as this page documents. Today:

ExtensionWaveProxima
Embed blocks, scriptYesNo
Embed blocks, componentYesNo
Data sourcesYesNo
ActionsYesNo
Product ratingsYesNo
App pagesYesNo

Other storefront apps can host embed blocks with the Apps SDK (see Hosting blocks in your storefront). swell app push validates embeds, data sources and actions from Swell CLI 2.9.39, and refuses a declaration that breaks a rule.

In Wave, the editor lists blocks under Apps in its Add section panel, and its AI agent can place them. Wave's themes use ui-kit's AppEmbed, app_data fields and AppAction, and its action route is /__site/actions/<app>/<action>. A product rating change shows within about a minute, and a theme shows ratings once it's republished with a version of Wave that has them. Proxima doesn't run extensions, so a Proxima theme can't use an app's blocks, data, actions or ratings. For app pages, Wave reserves its own first segments (such as products, categories, collections, pages, blogs and policies), uses a theme's app.<app>.<page> layout or its App page layout, signs shoppers in at /account/login, lists app pages in /sitemap-app-pages.xml, and shows them in an App pages group in the editor.

Wave's App form section shows an action's fields with no theme code: the merchant adds the section and picks the form in the editor. Wave's AI agent uses the installed apps' actions and data sources when it builds pages, and builds nothing for a form or feature no installed app offers.

An embed block is a widget a merchant places on a page, like a section. The app declares its blocks and the script that renders them. The storefront loads the script only on pages that place one of the app's blocks.

{
  "storefront": {
    "embeds": {
      "version": 1,
      "script": "frontend://embed.js?v=3",
      "connect": [
        "https://api.example.com"
      ],
      "blocks": [
        {
          "id": "packages",
          "label": "Packages",
          "description": "Your treatment packages, as cards or a compact strip.",
          "icon": "package",
          "pages": [
            "home",
            "product",
            "content"
          ],
          "props": [
            {
              "id": "layout",
              "type": "select",
              "label": "Layout",
              "default": "grid",
              "options": [
                {
                  "value": "grid",
                  "label": "Cards"
                },
                {
                  "value": "compact",
                  "label": "Compact strip"
                }
              ]
            },
            {
              "id": "limit",
              "type": "number",
              "label": "Packages shown",
              "min": 1,
              "max": 24
            }
          ]
        }
      ]
    }
  }
}

To add a block, run swell create block <id>. It adds the block to storefront.embeds in swell.json and scaffolds its code:

  • --render script (the default): writes frontend/public/embed.js, which registers the block with the block registry and renders into a shadow root with the theme tokens. When the declaration has no script yet, the command also sets "script": "frontend://embed.js" and "integrity": "auto". If the script file exists, it prints the registration to add to it.
  • --render component: writes components/<Name>.tsx, named from the id (gift_card_form becomes GiftCardForm), sets the block's render and component, and adds the component dependencies. The component sets no target.
swell create block packages

swell create block gift_card_form --render component -l "Gift card form"

Then add the block's props in swell.json and run swell app push. See Swell CLI for the command's flags.

KeyDescription
version1. Optional; only version 1 exists.
scriptRequired when any block runs in the page. A frontend:// link to a file your app's frontend serves, at most 500 characters. Path characters: letters, digits and . _ ~ / % -; query characters: letters, digits and . _ ~ = & % -. The storefront loads it from the installation's frontend origin.
integrityOptional. "auto", or a sha256-, sha384- or sha512- hash of the script with the digest's exact base64 length. The storefront sets it on the script element.
connectOptional list of at most 10 https://host[:port] origins the script calls. The app proxy is on the page's own origin and needs no entry.
imgOptional list of at most 10 https origins, or data:, the script loads images from.
blocks1 to 20 blocks.

No other keys are allowed.

KeyDescription
idBlock id, 1 to 40 characters of a-z, 0-9 and _. Unique in the app.
labelThe name the editor lists, 1 to 80 characters.
descriptionOptional, 1 to 300 characters.
iconOptional icon name, 1 to 40 characters of a-z, 0-9 and -. The editor draws names it knows and a generic app mark otherwise.
renderscript (default) runs the block in the page with your script. component runs it in a frame on your app's own origin.
componentRequired for a component block, and only there: the name of a top-level file in your app's components/ directory.
pagesOptional list of page types the block may be placed on, each once. Defaults to every page type except account.
propsOptional list of at most 20 fields the merchant sets in the editor.

The page types are home, product, category, category_list, search, cart, content (content pages and policies), blog, blog_post, account (account and sign-in pages) and not_found. A block in the cart drawer counts as on the cart page. On a page type the block doesn't list, the storefront refuses to place it and shows only its fallback.

Each prop is a field in the editor's inspector: {id, type, label, description?, default?, options?, min?, max?}.

  • id: a letter followed by up to 39 letters, digits or underscores, unique in the block.
  • label: 1 to 80 characters. description: 1 to 300 characters.
  • type: one of text, textarea, url, number, boolean or select.
  • default: a value of the prop's type. Text defaults are at most 500 characters; a number default is within min and max; a select default is one of its option values.
  • options: select only, 1 to 50 {value, label}, each value once, values 1 to 80 characters.
  • min and max: number only, with min at most max.

A prop the merchant leaves unset is absent from the block's props, so your block applies its own default. The saved values are a flat JSON object of at most 4,096 bytes.

The storefront's editor lists every block of the store's installed apps, with its icon, label, app name and description, and shows one field per prop when a merchant places it. A block a page type doesn't allow is listed as unavailable there, with the reason. For example, an editor can list them under Apps in its panel for adding sections, and an AI agent can place them with valid settings.

A theme section can also place a block. In themes built with ui-kit, use the AppEmbed component. Its children are the fallback shoppers see before the block mounts, without JavaScript, and when the app isn't installed:

<AppEmbed app="my_app" block="packages" props={{ layout: "grid" }} minHeight={240}>
  <p>Browse our packages.</p>
</AppEmbed>

Either way, the storefront renders the block as one element:

<div class="uk-app-embed" data-app-embed="<app>/<block>" data-app-props="<json>">…fallback…</div>

Only the storefront's renderer writes data-app-* attributes. It refuses them anywhere else: in theme code, AI-written code and store data. On a page whose app or block isn't installed, the element loses them and only the fallback shows. The editor canvas never runs app scripts or frames: it shows a labelled placeholder. A placed block whose app is later uninstalled stays on the page, showing its fallback, until the merchant deletes it, and the editor warns about it on publish.

Installing an app changes no page: merchants place blocks themselves. A block can say where it usually goes with position, and the storefront's editor can then offer to add it there in one click. position needs Swell CLI 2.9.47 or later.

{
  "id": "downloads",
  "label": "Your downloads",
  "pages": ["account"],
  "position": { "page": "account", "after": "account_view" }
}
  • page: a page type, as in pages. The block's pages must allow it.
  • after or before, one at most: a section type. The block goes next to the first section of that type, or at the end of the page when there is none. Leave both out to add it at the end of the page.
  • section: for a block with "placements": ["inline"], the type of the section it goes inside. after and before then name a block type in it, as in { "page": "product", "section": "product_details", "after": "product_title" }.
  • Section types differ between themes. A position the editor can't read is ignored, and the block still works.

In Wave, for example, the editor offers the block two ways, and never adds it by itself. Until the block is on the storefront, the editor shows a suggestion with Add and Not now. And a link adds it: https://<store>.swell.store/admin/storefronts/<storefront id>/editor?add=<app>:<block>, with the app's ID and the block's id. The editor adds the block to the draft, selects it and offers Undo, or selects it if it's already there. The merchant publishes to show it to shoppers. Put the link where merchants finish setting up your app.

To build the link, read the store's storefront IDs with the Backend API from your app's functions: GET /:storefronts with fields=id,name,primary. primary: true marks the storefront the store's domain shows. The section types in Swell's Wave themes include account_view, product_details, cart_items and cart_summary.

The storefront loads each app's script at most once per page, only on a page that holds one of its script blocks or may show one in the cart drawer. The script registers its blocks with the block registry and never searches the page itself:

(window.SwellAppBlocks = window.SwellAppBlocks || []).push({
  app: 'my_app',
  blocks: {
    packages: {
      mount(element, context) {
        const root = element.shadowRoot || element.attachShadow({ mode: 'open' });
        // render into root with context.props
        return () => root.replaceChildren(); // optional cleanup
      },
    },
  },
});

The storefront calls mount for every placed element of that block already on the page and for every one added later, such as in a cart drawer, and calls the returned cleanup when the element leaves the page. The order in which scripts load doesn't matter. context holds:

FieldDescription
propsThe block's saved settings.
app, blockThe app and block ids.
storefront{storeId, storefrontId, currency?, mode}. mode is live or preview. currency is absent when it is the store's own.
proxyThe app proxy's path on the page's origin, /.swell/apps/.
page{type, id?}: the page type the block is on, and, on a product, category, content page or blog post, that record's Swell id. A block in the cart drawer gets {type: "cart"} with no id, whatever page the drawer opens over.

A script block must touch only its own elements: no global CSS, no globals other than SwellAppBlocks, and no changes to the rest of the page. Render into a shadow root. Keep the script small, since every shopper on the page downloads it, and load heavy parts when the shopper interacts.

The storefront sets these CSS custom properties on every block element. They inherit into a shadow root. Use each with a fallback:

PropertyValue
--swell-color-text, --swell-color-mutedBody text, secondary text
--swell-color-background, --swell-color-surfacePage background, raised surfaces such as cards
--swell-color-accent, --swell-color-on-accentButtons and links, text on them
--swell-color-borderHairlines and inputs
--swell-font-body, --swell-font-headingFont families the page has loaded
--swell-radiusCorner radius of buttons and cards
--swell-spaceThe theme's base spacing unit

Swell caches app frontend files by URL, so give a changed script a new URL, for example with a v query parameter, and update integrity with it.

With "integrity": "auto", swell app push does both. It hashes the file the frontend:// link names in frontend/public/, sets a sha384 integrity, and sets the link's v parameter to the first 12 hex characters of that hash. The app keeps its current script and integrity until push has deployed the frontend that serves the new file, then takes the new ones. Your local swell.json keeps "auto".

"auto" needs a frontend:// script. swell create block sets "integrity": "auto" for a new script. It needs Swell CLI 2.9.41 or later.

An explicit integrity on a frontend:// script must match the file in frontend/public/. When it doesn't, swell app push fails and names the hash the file has. Set integrity to that hash, or to "auto".

A block with "render": "component" runs one of your App Components in a frame on your app's installation origin. The page can't see inside the frame, and the component can't see the page. Use it for sensitive input, such as card details, or for state the page must not see, and only for a few instances per page. The component is a top-level file in components/ named by the block's component. It gets the block's props as params, the theme tokens in context.tokens, and calls your app with props.fetch. An app whose blocks are all component blocks needs no script.

A component block declares its props in swell.json, like a script block, not in the component's config. The editor renders the block's fields from the declaration, and the component gets only their values, as params. The component sets no target: the storefront finds it by the block's component name.

{
  "id": "gift_card_form",
  "label": "Gift card form",
  "render": "component",
  "component": "GiftCardForm",
  "props": [
    {
      "id": "amounts",
      "type": "text",
      "label": "Amounts",
      "description": "Comma-separated."
    }
  ]
}

→ See Frontend for app frontends and components.

A script block calls your app through the app proxy at context.proxy, on the storefront's own origin, so there is no CORS and no list of allowed origins. Swell forwards /.swell/apps/<app>/<path> to your frontend's /app-api/storefront/<path> with a signed Swell-Context header. It forwards the method, query and body, and only the headers accept, accept-language, content-type, if-none-match, idempotency-key and x-app-authorization. Cookies are never forwarded.

import { verifySwellContext, isStorefrontRequest } from '@swell/apps-sdk';

export async function GET(request: Request) {
  const context = await verifySwellContext(request.headers);
  if (!isStorefrontRequest(context)) return new Response(null, { status: 403 });
  // context.storeId, context.storefrontId, context.storefrontHost, context.accountId
}

The context proves that the request came through one of the store's storefronts. It doesn't prove who the shopper is, since storefront pages are public: rate-limit requests, and check that accountId owns any private data you return. Component blocks call your app with props.fetch, which adds a token that the gateway turns into the same context.

On a page that holds a script block, the storefront adds to the page's Content Security Policy exactly the script's URL (script-src) and the declaration's connect and img origins. On a page that holds a component block, it adds the installation's frontend origin to frame-src. Pages without an app's blocks get none of its sources.

Storefronts read embed declarations strictly: a declaration that breaks any rule, including one bad block or prop, is left out whole, and none of the app's blocks show. swell app push refuses such a declaration and names each problem. Swell also checks the declaration when it receives the push, and refuses one that breaks a rule for its keys, version, frontend:// script, integrity, connect or img origins, or any block or prop, naming the problem.

If "integrity": "auto" reaches Swell unresolved, the push fails with a message to update the Swell CLI or set the hash yourself. Swell CLI 2.9.41 and later resolve it.

LimitValue
Apps with embeds per store10
Blocks per app20
Props per block20
Options per select prop50
connect and img origins10 each
Saved settings per placed block4,096 bytes of JSON

A storefront app can host embed blocks with the Apps SDK. It reads the store's installed blocks by the rules on this page, runs the block registry for script blocks, and mounts component blocks in frames. An app's declaration and block code are the same on every storefront.

→ See Apps SDK for hosting storefront app blocks.

A data source gives a theme data from your app. The storefront reads it on the server while it renders the page, and the theme renders it with its own markup, so no app script runs in the page and the content is in the HTML.

{
  "storefront": {
    "data": [
      {
        "id": "quotes",
        "label": "Your quotes",
        "scope": "account",
        "from": {
          "collection": "quotes",
          "where": {
            "account_id": "$account.id"
          },
          "fields": [
            "number",
            "status",
            "total",
            "date_expires"
          ],
          "sort": "date_created desc",
          "limit": 20
        },
        "sample": [
          {
            "number": "Q-1001",
            "status": "quoted",
            "total": 412.5,
            "date_expires": "2026-12-01"
          }
        ]
      },
      {
        "id": "terms",
        "label": "Payment terms",
        "scope": "account",
        "from": {
          "function": "storefront-terms"
        },
        "cache": 60,
        "sample": {
          "net_days": 30,
          "credit_limit": 5000,
          "credit_used": 1200
        }
      }
    ]
  }
}
KeyDescription
id1 to 40 characters of a-z, 0-9 and _. Unique among the app's data sources.
labelThe name the editor lists, 1 to 80 characters.
descriptionOptional, 1 to 300 characters.
scopestore, account, product or category. See below.
fromExactly one of {collection, where?, fields?, sort?, limit?} or {function}.
cacheOptional seconds, 0 to 3600. Defaults to 60, and to 0 for an account source read from a collection.
sampleRequired JSON value of at most 8 KB, in the shape the source returns. The editor canvas renders it.

The scope says what the data depends on:

  • store: the same for every shopper.
  • account: the signed-in customer's own data. A guest gets signed_out.
  • product: the product of the page. Only on product pages.
  • category: the category of the page. Only on category pages.
  • page: an app page's params. Function sources only, on app pages. See App pages.

A collection source reads one of your app's own models, named as in models/, 1 to 40 characters of a-z, 0-9, _ and -. The storefront reads /apps/<app>/<collection> on the server with its own credentials, in parallel with the page's other data. This is the recommended source for records a page renders.

  • where: a flat object of at most 10 fields. A value is a string of at most 200 characters, a number, a boolean, or a placeholder. Operators aren't allowed.
  • fields: 1 to 30 field names to return. Dotted paths are allowed, up to five levels.
  • sort: a field name, optionally followed by asc or desc.
  • limit: 1 to 100. Defaults to 20.

The storefront fills placeholders itself, and never from page or shopper input:

PlaceholderValueScope required
$account.idThe signed-in customer's account idaccount
$product.idThe page's product idproduct
$category.idThe page's category idcategory
$storefront.idThe storefront's idAny

A source with scope: account must filter on $account.id. The source's value is the read's results array.

A function source names one of your app's functions, 1 to 60 characters of a-z, 0-9 and -. Use it for data that must be computed, such as payment terms from orders and settings. The storefront calls the function as a public POST route, so its config must include route: { public: true, methods: ['post'] }. The request body is:

{
  "bridge": 1,
  "kind": "data",
  "id": "terms",
  "page": {
    "type": "product",
    "product_id": "…",
    "category_id": null
  },
  "locale": "en-US",
  "currency": "USD",
  "storefront_id": "…"
}

page.type is the kind of page being rendered, such as home, product or category. For an account source, the storefront sends the shopper's session, so req.session.account_id is the signed-in customer. Other scopes are called without a session. The function returns the JSON value itself.

A function source runs app code on every uncached render, which adds time to the page. Prefer a collection source for records, and keep a function source's cache above 0 where the data allows.

  • A source's value is plain JSON of at most 32 KB.
  • The storefront waits at most 3 seconds for a source while it renders. A slower, larger or non-JSON answer, or an error status, is error.
  • The storefront keeps a value for cache seconds per source and per account, product or category, in its own memory only. 0 means the value is never kept.
  • A page that shows an account source is the shopper's own: the storefront never keeps it in a shared cache and sends it with Cache-Control: private.
  • An app can declare up to 20 data sources, and a storefront reads data sources and actions from up to 20 apps per store. Each source is read on its own: one that breaks a rule is left out, and the app's other sources stay.

A theme section reads a data source through a field that names the app and the source. In themes built with ui-kit, it's a field of type app_data:

{
  "id": "quotes",
  "type": "app_data",
  "app": "my_app",
  "source": "quotes"
}

The section's prop of that name is {status, value}. value is the source's value when status is ok, and null otherwise. In the editor canvas, status is ok and value is the source's sample; the canvas never calls your app.

  • ok: the source answered.
  • signed_out: an account source and a guest.
  • missing_app: the app isn't installed, or doesn't declare the source.
  • error: the read failed, timed out or was too large, or the page has no product or category for the source's scope.

On anything but ok, the section renders its own empty state. The editor shows a "Needs the <app> app" placeholder on sections whose app is missing, and warns about them on publish.

A theme app names the apps its sections use in theme.apps in its own swell.json. A store can't install the theme, or use it on a storefront, without the apps it marks required: the theme's install dialog installs them, or buys them under their own price, in the same step. The editor warns on publish when an app a section uses is missing:

{
  "theme": {
    "storefront": {
      "app": "wave"
    },
    "apps": [
      {
        "id": "my_app",
        "required": true,
        "min_version": "1.0.0",
        "why": "Quick order and quotes"
      }
    ]
  }
}

id is the app's id from its swell.json: one of your own apps, or a published app. required defaults to false, and only required apps are shown and enforced. min_version is an optional x.y.z version, and why is 1 to 200 characters. A theme can name up to 10 apps, each once, and an entry takes no other keys. Every app a theme names must exist when the theme is pushed, so push the app first. See Required apps.

An app can give the storefront page types of its own, at addresses it owns, such as courses at /courses/<course> and their lessons at /courses/<course>/<lesson>, or bookings at /book/<service>. The storefront routes them, renders them in every theme, caches them and keeps signed-in pages private. The app declares the pages in storefront.pages, and answers their content from its data sources.

This courses app has a catalog page, a page per course, and lessons for signed-in, enrolled customers only:

{
  "id": "courses",
  "name": "Courses",
  "storefront": {
    "data": [
      {
        "id": "catalog", "label": "All courses", "scope": "store",
        "from": { "function": "storefront-catalog" }, "cache": 60,
        "sample": { "title": "Courses", "items": [{ "title": "Intro to pottery", "url": "/courses/intro-to-pottery" }] }
      },
      {
        "id": "course_list", "label": "Course addresses", "scope": "store",
        "from": { "function": "storefront-course-list" }, "cache": 300,
        "sample": [{ "course": "intro-to-pottery", "label": "Intro to pottery" }]
      },
      {
        "id": "course", "label": "Course", "scope": "page",
        "from": { "function": "storefront-course" }, "cache": 60,
        "sample": { "title": "Intro to pottery", "body": "<p>Six lessons at the wheel.</p>" }
      },
      {
        "id": "lesson", "label": "Lesson", "scope": "page",
        "from": { "function": "storefront-lesson" }, "cache": 60,
        "sample": { "title": "Centering the clay", "body": "<p>Wet your hands and press down.</p>" }
      }
    ],
    "pages": [
      { "id": "index", "label": "All courses", "path": "/courses", "data": ["catalog"], "primary": "catalog" },
      {
        "id": "course", "label": "Course", "path": "/courses/:course", "params": { "course": "slug" },
        "data": ["course"], "primary": "course", "list": "course_list", "sample": { "course": "intro-to-pottery" }
      },
      {
        "id": "lesson", "label": "Lesson", "path": "/courses/:course/:lesson",
        "params": { "course": "slug", "lesson": "slug" }, "requires": "account",
        "data": ["lesson"], "primary": "lesson", "sample": { "course": "intro-to-pottery", "lesson": "centering" }
      }
    ]
  }
}
KeyDescription
id1 to 40 characters of a-z, 0-9 and _. Unique among the app's pages.
labelThe name the editor lists, 1 to 80 characters.
path/ then a first segment the app owns (lowercase letters and digits, words joined by -, at most 40 characters), then literal segments or :. At most 5 segments and 3 params, with no trailing /.
paramsOptional. Each param's type: slug (1 to 100 characters of a-z, 0-9 and -, the default) or id (a 24-character lowercase hex id).
requiresnone (default) or account: only a signed-in shopper can open the page.
dataOptional. Up to 10 ids of the app's data sources the page uses, of scope store or page, or account on an account page.
primaryOne of data. Its answer decides whether the page exists. Required on a page with params.
listOptional, on a page with params. A store-scope source that returns the page's param sets: rows with each param and an optional label. The storefront uses it to pick records in the editor, link pages from menus and list them in the sitemap.
sampleRequired on a page with params: a value for each param, for the editor's preview.
indexOptional, defaults to true: search engines may index the page and the sitemap lists it. Can't be true on an account page.

Each page is read on its own: an unknown key or a broken rule leaves that page out, and the app's other pages, data sources and actions still work. An app can declare up to 20 pages.

The storefront refuses a page whose address it can't give the app:

  • A first segment the storefront uses itself, such as products, cart or account, or one that reads as a language tag, such as es or pt-br, since /es/… is a language prefix.
  • Two pages of the same app that could answer the same address. The later one is left out.
  • Another installed app's first segment. A first segment belongs to the app installed first.

The storefront checks an address's params against their types before it calls anything. An address that doesn't fit, such as one with capitals, a trailing / or an extra segment, gets the 404 page. App pages work under the shopper's language prefix too, such as /es/courses/intro-to-pottery.

A data source with scope: page is a function source that gets the page's checked params. Its request body includes:

{
  "page": {
    "type": "app",
    "app": "courses",
    "id": "lesson",
    "params": { "course": "wheel-throwing", "lesson": "centering" }
  }
}

Read the params from page.params. A collection source can't use them: prove in the function that the record exists and that the shopper may see it. On an account page the function also gets the shopper's session, so req.session.account_id is the signed-in customer. A page-scope value is kept for its cache seconds per page and params, and per account on an account page.

  • {"status": "not_found"}: the storefront shows its 404 page.
  • {"status": "forbidden"}: the 404 page too. On an account page a signed-out shopper is asked to sign in first and comes back after.
  • Anything else is the page's data. An optional seo object sets the page's title (at most 200 characters), description (at most 400), image (an https URL) and noindex: true.
  • An error, a timeout or an answer over 32 KB gets a 503 page, which is never cached.

The lesson function checks who is signed in and whether they're enrolled:

export const config: SwellConfig = {
  description: 'App page: a lesson',
  route: { public: true, methods: ['post'] },
};

export async function post(req: SwellRequest) {
  const { course, lesson } = req.body?.page?.params ?? {};
  // Who is signed in comes from the session, never from the body
  const accountId = req.session?.account_id;
  if (!accountId) return { status: 'forbidden' };

  const enrolled = await req.swell.get('/apps/courses/enrollments', {
    where: { account_id: accountId, course_slug: course },
    limit: 1,
  });
  if (!enrolled.count) return { status: 'forbidden' };

  const found = await req.swell.get('/apps/courses/lessons', {
    where: { course_slug: course, slug: lesson },
    limit: 1,
  });
  const l = found.results[0];
  if (!l) return { status: 'not_found' };

  return {
    title: l.title,
    body: l.body_html,
    image: l.image,
    seo: { title: `${l.title} | ${l.course_title}` },
  };
}
  • Layout: the theme's own layout for the page type when it has one, else a general app page layout, so every theme shows app pages with no changes. The general layout shows the answer's title, body, image and items: at most 100 of {title, url, text, image}, where url is a path on the storefront. Answer in that shape to look right in any theme. A theme's sections can read the whole answer.
  • Account pages: a signed-out shopper signs in and comes back. The page is private, never cached and never indexed.
  • Caching: a public page is cached like a product page, per address, language and currency, unless one of its sources has a cache under 60.
  • Search engines: the title, description, canonical link and social previews come from seo, else from the answer's title and text. Public, indexable pages, and each param set list returns, up to 500 per page type, are listed in the storefront's sitemap.
  • Editor: app pages are listed with the storefront's pages and previewed with their sample, or with a record from list. Menus can link them, and publishing warns when a menu links a page whose app is gone.

A newly installed app's pages can take up to a minute to appear.

A reviews app can give every theme its product ratings and recent reviews, with no theme code. Declare storefront.product_rating, naming two product fields the app keeps and, optionally, a data source with the recent reviews:

{
  "storefront": {
    "data": [
      {
        "id": "reviews",
        "label": "Recent reviews",
        "scope": "product",
        "from": {
          "collection": "reviews",
          "where": { "product_id": "$product.id", "status": "approved" },
          "fields": ["rating", "title", "body", "name", "date_published"],
          "sort": "date_published desc",
          "limit": 10
        },
        "sample": [
          { "rating": 5, "title": "Love it", "body": "Fits well and arrived fast.", "name": "Sam", "date_published": "2026-11-20" }
        ]
      }
    ],
    "product_rating": { "average": "rating", "count": "review_count", "reviews": "reviews" }
  }
}
KeyDescription
averageA field the app keeps on each product, read as $app..: the average rating, a number from 0 to 5, shown to one decimal.
countAnother field the app keeps on each product: the number of reviews, a whole number.
reviewsOptional. The id of one of the app's own data sources with scope: product, for the recent reviews.

Field names are 1 to 60 characters of a-z, 0-9 and _, starting with a letter, and average and count must differ. A declaration that breaks a rule, or has any other key, is left out, and the app's data sources and actions still work.

Keep both fields current on each product whenever a review is approved, edited or removed, as public fields of your product model, so they come with the product. A product has no rating when either field is missing or isn't a number, or when the count is 0.

The reviews source's rows carry rating (1 to 5), title, body, name (the reviewer's display name) and date_published (an ISO date), newest first. The storefront uses at most 10, and skips a row without a numeric rating or a body. The source is read and cached like any product-scope source, so a theme section can also show it with a data source field.

  • Stars and the review count on product cards and on the product page, in every theme, with a label such as "Rated 4.3 out of 5, 128 reviews".
  • In the product page's structured data, the average and count as aggregateRating, and each review row as a Review, for search engines.

A rating change reaches shoppers as the product's pages are refreshed. When more than one installed app declares product_rating, the storefront uses the one installed first.

An action is a form a theme posts to one of your app's functions. The storefront checks the form, calls the function, and applies the answer itself: it adds cart lines through Swell's own cart, so Swell prices them, shows a message on the next page, or redirects. Your app never touches the shopper's cart or session.

{
  "storefront": {
    "actions": [
      {
        "id": "quick_order",
        "label": "Quick order",
        "function": "storefront-quick-order",
        "requires": "account",
        "fields": [
          {
            "id": "lines",
            "type": "textarea",
            "max": 20000,
            "required": true
          }
        ],
        "effects": [
          "cart_add",
          "message"
        ]
      }
    ]
  }
}
KeyDescription
id1 to 40 characters of a-z, 0-9 and _. Unique among the app's actions.
label1 to 80 characters.
descriptionOptional, 1 to 300 characters.
functionThe app function the storefront calls, 1 to 60 characters of a-z, 0-9 and -.
requiresnone (default) or account. The storefront sends a guest to sign in for an account action, then back to the form's page.
fields1 to 30 form fields. The storefront drops every other submitted field.
effectsOne or more of cart_add, message, redirect and reload. The storefront applies only the effects listed.

Each field is {id, type, required?, max?, options?}. id is a lowercase letter followed by up to 39 characters of a-z, 0-9 and _. max is the most characters, and is allowed only on text, textarea and hidden fields.

TypeDefault maxHighest maxValue the function gets
text5005,000Trimmed string
textarea5,00050,000Trimmed string, line breaks kept
email254254String with an @ and a domain
number3030Number
boolean--true or false (a checked box is true)
select100100One of options: 1 to 100 strings of 1 to 100 characters
hidden500500String

An app can declare up to 20 actions. Like data sources, an action that breaks a rule is left out on its own.

A storefront can build a form from your declaration alone, with no theme code for your app. Write it for that: give each field an id in plain words, since the field's label is its id in words (competitor_price shows as "Competitor price"); list the fields in the order shoppers fill them in; and write label and description for a merchant choosing among the store's forms.

In themes built with ui-kit, a section posts to an action with the AppAction component:

<AppAction app="my_app" action="quick_order" returnTo={site.page.path} flash={flash}>
  {({ values, errors }) => (
    <>
      <textarea name="lines" defaultValue={values.lines} />
      {errors.lines ? <p role="alert">{errors.lines}</p> : null}
      <button type="submit">Add to cart</button>
    </>
  )}
</AppAction>

It renders a form that posts to the storefront's action route for that app and action, with a hidden _return field holding returnTo, the path to come back to. Name each input after a declared field's id. flash is the page's site.app_flash when it names this app and action. AppAction shows its form error above the fields, and children given as a function get the shopper's values and the errors per field. Only AppAction may post to the action route: the storefront refuses any other form, button or link that points there.

A theme can also let the merchant choose the form. A section field of type app_action stores the app and action in the template:

// the section's field
{ "id": "form", "type": "app_action", "label": "Form" }

// what the template stores
{ "form": { "app": "my_app", "action": "quick_order" } }

The section gets the action as the app declares it: status, app, action, name (the app's name), label, description, requires, effects and fields, each with its id, type, label, required, max and options. status is missing_app when the app isn't installed or no longer declares the action, and the section then renders nothing. app_action fields and the core app_form section in Wave themes need @swell/wave-theme-core 1.1.0 or later, on stores running Wave 1.0.16 or later.

Before it calls your function, the storefront refuses a post that:

  • comes from another origin or from a frame;
  • isn't a URL-encoded form of at most 64 KB;
  • names an action the app doesn't declare;
  • comes from a guest when the action requires an account;
  • goes over 20 posts a minute from the same shopper to the same app.

The storefront then checks each declared field for its type, max, options and required, and drops undeclared fields. A field that fails comes back on the form with the shopper's values and an error, and your function isn't called. These checks don't replace your own: the function route is public, so anyone can call it with any body.

The storefront calls the function as a public POST route with the shopper's session, so req.session.account_id is the signed-in customer, or empty for a guest. The function's config must include route: { public: true, methods: ['post'] }. The body is:

{
  "bridge": 1,
  "kind": "action",
  "id": "quick_order",
  "input": {
    "lines": "SKU-1, 4\nSKU-2, 12"
  },
  "cart_id": "…",
  "locale": "en-US",
  "currency": "USD",
  "storefront_id": "…"
}

input holds only the declared fields, already checked. cart_id is the shopper's cart as the storefront knows it, or null: check that the cart belongs to the signed-in account before acting on it.

A JSON object with the effects to apply. The storefront waits at most 10 seconds:

{
  "cart_add": [
    {
      "product_id": "…",
      "variant_id": "…",
      "quantity": 4
    }
  ],
  "message": {
    "text": "4 lines added",
    "tone": "success"
  },
  "redirect": "/account/quotes",
  "reload": true
}
KeyDescription
cart_addAt most 100 lines of {product_id, variant_id?, quantity}, quantity 1 to 9999. The storefront adds them to the shopper's cart through Swell, so Swell prices them, including group prices and tiers. Never send a price. If Swell refuses some lines, the shopper sees an error message instead of yours.
message{text, tone}: text of 1 to 300 characters, tone info (default), success or error. Shown once, on the next page.
redirectA path on the storefront, at most 500 characters, starting with / and not // or /\. Anything else is ignored. Without a redirect, the shopper goes back to the form's page.
reloadtrue shows the form's page again, with fresh data.
errorsAn object of declared field ids, or _form, to messages of 1 to 300 characters. The storefront shows the form again with the shopper's values and these errors, and applies no other effect.

The storefront ignores keys the action doesn't list in effects. An answer that isn't a JSON object, has invalid cart_add lines, has a non-2xx status or times out shows a generic error on the form. A function that refuses returns errors with a 2xx status.

The storefront carries a message, the errors and the shopper's values to the next page in a one-time cookie, which that page reads and clears. It shows a message at the start of the page's content. A theme reads errors and values from site.app_flash, {app, action, message?, errors?, values?}, and passes it to AppAction as flash. Values of hidden fields are never carried back.

Treat every storefront call as public. Data and action functions are public routes that anyone can call with any body, so don't authorize on anything in it: kind, id, page, input, cart_id and storefront_id are claims. Only req.session.account_id says who is signed in.

A signed-in account isn't permission to see everything. Check that the records you return or change belong to that account, and if only some customers may use a feature, such as approved business buyers, check the account's group on your own server. A theme setting that hides pages or prices doesn't protect Swell's Storefront API, public function routes, the app proxy or checkout, so apps that limit who may order enforce it in their functions and model hooks.

This app lets signed-in customers save products by SKU. It declares one data source, read straight from its own saved-items collection, and one action, answered by a function.

swell.json:

{
  "id": "saved_items",
  "name": "Saved items",
  "type": "admin",
  "version": "1.0.0",
  "description": "Customers save products by SKU and see them on the storefront",
  "permissions": [],
  "storefront": {
    "data": [
      {
        "id": "saved_items",
        "label": "Saved items",
        "description": "The signed-in customer's saved items, newest first.",
        "scope": "account",
        "from": {
          "collection": "saved-items",
          "where": {
            "account_id": "$account.id"
          },
          "fields": [
            "product_id",
            "name",
            "sku",
            "date_created"
          ],
          "sort": "date_created desc",
          "limit": 20
        },
        "sample": [
          {
            "product_id": "sample-product",
            "name": "Sample tee",
            "sku": "TEE-1",
            "date_created": "2026-11-13T12:00:00.000Z"
          }
        ]
      }
    ],
    "actions": [
      {
        "id": "save_item",
        "label": "Save an item",
        "description": "Saves a product by its SKU, and can add it to the cart too.",
        "function": "storefront-save-item",
        "requires": "account",
        "fields": [
          {
            "id": "sku",
            "type": "text",
            "required": true,
            "max": 64
          },
          {
            "id": "add_to_cart",
            "type": "boolean"
          }
        ],
        "effects": [
          "cart_add",
          "message",
          "reload"
        ]
      }
    ]
  }
}

models/saved-items.json:

{
  "label": "Saved item",
  "plural": "Saved items",
  "fields": {
    "account_id": {
      "type": "objectid",
      "required": true
    },
    "product_id": {
      "type": "objectid",
      "required": true
    },
    "name": {
      "type": "string"
    },
    "sku": {
      "type": "string"
    }
  }
}

functions/storefront-save-item.ts:

export const config: SwellConfig = {
  description: 'Storefront action: save an item by SKU',
  route: { methods: ['post'], public: true },
};

export async function post(req: SwellRequest) {
  const body = (req.body ?? {}) as { bridge?: unknown; kind?: unknown; id?: unknown; input?: Record<string, unknown> };
  if (body.bridge !== 1 || body.kind !== 'action' || body.id !== 'save_item') {
    return { errors: { _form: "This form isn't available." } };
  }

  // Who is signed in comes from the session, never from the body
  const accountId = (req.session as { account_id?: string } | undefined)?.account_id;
  if (!accountId) return { errors: { _form: 'Sign in to save items.' } };

  const sku = typeof body.input?.sku === 'string' ? body.input.sku : '';
  const products = await req.swell.get('/products', { where: { sku, active: true }, fields: 'id,name', limit: 1 });
  const product = products?.results?.[0];
  if (!product) return { errors: { sku: `${sku} isn't in the catalog.` } };

  const where = { account_id: accountId, product_id: product.id };
  const saved = await req.swell.get('/apps/saved_items/saved-items', { where, limit: 1 });
  if (!saved?.results?.length) {
    await req.swell.post('/apps/saved_items/saved-items', { ...where, name: product.name, sku });
  }

  return {
    message: { text: `Saved ${product.name}.`, tone: 'success' },
    reload: true,
    // The storefront adds the line through Swell's own cart, which prices it
    ...(body.input?.add_to_cart === true ? { cart_add: [{ product_id: product.id, quantity: 1 }] } : {}),
  };
}

A theme section that shows the saved items and the form:

import { AppAction } from 'ui-kit';
import type { SiteInfo } from 'ui-kit';

export const schema = {
  label: 'Saved items',
  fields: [{ id: 'saved', type: 'app_data', app: 'saved_items', source: 'saved_items' }],
} as const;

type Item = { product_id: string; name: string; sku: string };
type Props = { site?: SiteInfo; saved?: { status: string; value: unknown } };

export default function SavedItems({ site, saved }: Props) {
  if (saved?.status === 'signed_out') return <p><a href="/account/login">Sign in</a> to see your saved items.</p>;
  if (saved?.status !== 'ok' || !Array.isArray(saved.value)) return null;
  const items = saved.value as Item[];
  const raw = site?.app_flash;
  const flash = raw?.app === 'saved_items' && raw.action === 'save_item' ? raw : null;
  return (
    <section>
      <h2>Saved items</h2>
      <ul>{items.map((item) => <li key={item.product_id}>{item.name} ({item.sku})</li>)}</ul>
      <AppAction app="saved_items" action="save_item" returnTo={site?.page.path} flash={flash}>
        {({ values, errors }) => (
          <>
            <input name="sku" defaultValue={values.sku} aria-invalid={errors.sku ? true : undefined} />
            {errors.sku ? <p role="alert">{errors.sku}</p> : null}
            <label><input type="checkbox" name="add_to_cart" /> Add to cart</label>
            <button type="submit">Save</button>
          </>
        )}
      </AppAction>
    </section>
  );
}

When a customer submits the form, the storefront checks that they're signed in and that sku is at most 64 characters, then calls the function. A SKU that isn't in the catalog comes back on the form as an error under the field. Otherwise the storefront adds the product to the cart when the box is checked, shows "Saved …" on the next page, and shows the page again with the new item in the list.

swell app push validates storefront.embeds, storefront.data and storefront.actions and refuses a declaration that breaks a rule, naming each problem, including a component block whose file isn't in components/. It also warns when a declared function isn't in functions/ or isn't a public POST route, and when a collection source isn't in models/.

Test extensions on a store's test environment, on a storefront that supports them:

1
Push the app

Run swell app push and install the app on the store's test environment.

2
Open the storefront's editor

Open the editor on a storefront in the same environment. Your embed blocks are listed with the blocks merchants can place, and sections that use your data sources render their sample.

3
Preview as a shopper

Open the storefront's preview, sign in as a test customer, and use the forms. Your functions' logs show each call the storefront makes.

swell app push
swell logs