# Storefront extensions

Source: https://developers.swell.is/storefronts/storefront-extensions

Any Swell app can add features to storefronts by declaring them under `storefront` in its `swell.json`: embed blocks, data sources and form actions. A storefront app reads the declarations of the store's installed, active apps, from the version each store has installed, and merchants use them in its editor. Today [Wave](https://developers.swell.is/storefronts/wave-app) is the only storefront app that hosts them, so this page describes them as Wave runs them.

> **Warning:** Embed blocks follow the app block standard in `@swell/apps-sdk/blocks`, which any storefront app can host. Today only Wave hosts embed blocks, data sources and actions; Proxima doesn't support any of them. `swell app push` validates all three from Swell CLI 2.9.39, and refuses a declaration that breaks a rule.

## Overview

An app reaches a storefront in three ways:

| Extension | Key | What it does | App code in the page |
| --- | --- | --- | --- |
| Embeds | storefront.embeds | Puts the app's own UI on a page: a script, and blocks merchants place in the editor. | Yes |
| Data sources | storefront.data | Gives the theme the app's data, which the theme renders with its own markup on the server. | No |
| Actions | storefront.actions | Lets the theme post a form to one of the app's functions. Wave applies the answer: cart lines, a message, a redirect. | 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`:

```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.

## Embeds

Supported today in: Wave. Not supported in Proxima.

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. Wave loads the script only on pages that place one of the app's blocks.

```json
{
  "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.

```txt
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](https://developers.swell.is/apps/cli) for the command's flags.

### Declaration

| Key | Description |
| --- | --- |
| version | 1. Optional; Wave reads only version 1. |
| script | Required when any block runs in the page. A frontend://<path> link to a file your app's frontend serves, at most 500 characters. Path characters: letters, digits and . _ ~ / % -; query characters: letters, digits and . _ ~ = & % -. Wave loads it from the installation's frontend origin. |
| integrity | Optional. "auto", or a sha256-, sha384- or sha512- hash of the script with the digest's exact base64 length. Wave sets it on the script element. |
| connect | Optional 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. |
| img | Optional list of at most 10 https origins, or data:, the script loads images from. |
| blocks | 1 to 20 blocks. |

No other keys are allowed.

### Blocks

| Key | Description |
| --- | --- |
| id | Block id, 1 to 40 characters of a-z, 0-9 and _. Unique in the app. |
| label | The name the editor lists, 1 to 80 characters. |
| description | Optional, 1 to 300 characters. |
| icon | Optional icon name, 1 to 40 characters of a-z, 0-9 and -. Wave draws names it knows and a generic app mark otherwise. |
| render | script (default) runs the block in the page with your script. component runs it in a frame on your app's own origin. |
| component | Required for a component block, and only there: the name of a top-level file in your app's components/ directory. |
| pages | Optional list of page types the block may be placed on, each once. Defaults to every page type except account. |
| props | Optional 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, Wave refuses to place it and shows only its fallback.

### Props

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.

### Placing a block

Wave lists every block of the store's installed apps under **Apps** in the editor's **Add section** panel, with its icon, label, app name and description. Picking one adds an App block section to the page, and the inspector shows one field per prop. Wave's AI agent can place blocks too, with valid settings. A block a page type doesn't allow shows in the panel as disabled, with the reason.

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

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

Either way, Wave renders the block as one element:

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

Only Wave's renderer writes `data-app-*` attributes. Wave 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 Wave warns about it on publish.

### The block script

Wave 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 Wave's block registry and never searches the page itself:

```javascript
(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
      },
    },
  },
});
```

Wave 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:

| Field | Description |
| --- | --- |
| props | The block's saved settings. |
| app, block | The app and block ids. |
| storefront | {storeId, storefrontId, currency?, mode}. mode is live or preview. currency is absent when it is the store's own. |
| proxy | The app proxy's path on the page's origin, /.swell/apps/<app>. |

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.

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

| Property | Value |
| --- | --- |
| --swell-color-text, --swell-color-muted | Body text, secondary text |
| --swell-color-background, --swell-color-surface | Page background, raised surfaces such as cards |
| --swell-color-accent, --swell-color-on-accent | Buttons and links, text on them |
| --swell-color-border | Hairlines and inputs |
| --swell-font-body, --swell-font-heading | Font families the page has loaded |
| --swell-radius | Corner radius of buttons and cards |
| --swell-space | The 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"`.

### Component blocks

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.

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

→ See [Frontend](https://developers.swell.is/apps/frontend) for app frontends and components.

### Calling your backend

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.

```typescript
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.

### Content Security Policy

On a page that holds a script block, Wave 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.

### Validation and limits

Wave reads 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.

| Limit | Value |
| --- | --- |
| Apps with embeds per store | 10 |
| Blocks per app | 20 |
| Props per block | 20 |
| Options per select prop | 50 |
| connect and img origins | 10 each |
| Saved settings per placed block | 4,096 bytes of JSON |

### Other storefronts

Other storefront apps can host embed blocks with the Apps SDK. It reads the store's installed blocks by the same rules, 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 host. Data sources and actions are read by Wave only.

→ See [Apps SDK](https://developers.swell.is/apps/swell-apps-sdk) for hosting storefront app blocks.

## Data sources

Supported today in: Wave. Not supported in Proxima.

A data source gives a theme data from your app. Wave 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.

```json
{
  "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
        }
      }
    ]
  }
}
```

### Declaration

| Key | Description |
| --- | --- |
| id | 1 to 40 characters of a-z, 0-9 and _. Unique among the app's data sources. |
| label | The name the editor lists, 1 to 80 characters. |
| description | Optional, 1 to 300 characters. |
| scope | store, account, product or category. See below. |
| from | Exactly one of {collection, where?, fields?, sort?, limit?} or {function}. |
| cache | Optional seconds, 0 to 3600. Defaults to 60, and to 0 for an account source read from a collection. |
| sample | Required 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.

### Reading a collection

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 -. Wave 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.

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

| Placeholder | Value | Scope required |
| --- | --- | --- |
| $account.id | The signed-in customer's account id | account |
| $product.id | The page's product id | product |
| $category.id | The page's category id | category |
| $storefront.id | The storefront's id | Any |

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

### Calling a function

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. Wave calls the function as a public POST route, so its config must include `route: { public: true, methods: ['post'] }`. The request body is:

```json
{
  "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 Wave is rendering, such as `home`, `product` or `collection`. For an `account` source, Wave 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.

### Limits and caching

- A source's value is plain JSON of at most 32 KB.
- Wave waits at most 3 seconds for a source while it renders. A slower, larger or non-JSON answer, or an error status, is `error`.
- Wave 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: Wave never keeps it in a shared cache and sends it with `Cache-Control: private`.
- An app can declare up to 20 data sources, and Wave reads data sources and actions from up to 20 apps per store. Wave reads each source on its own: one that breaks a rule is left out, and the app's other sources stay.

### Using a data source in a theme

A theme section declares a field of type `app_data` naming the app and the source:

```json
{
  "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 Publish warns about them.

A theme app names the apps its sections use in `theme.apps` in its own `swell.json`. When a merchant installs the theme, Swell installs every companion app it names, required or optional, and the theme's install dialog lists them with their permissions. A required app that isn't a companion is installed separately, with its price shown. The dashboard, and Publish in the Wave editor, warn when a required app is missing:

```json
{
  "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`, `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. An app made to come with a theme is a companion app: see [Companion apps](https://developers.swell.is/storefronts/companion-apps).

## Actions

Supported today in: Wave. Not supported in Proxima.

An action is a form a theme posts to one of your app's functions. Wave 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.

```json
{
  "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"
        ]
      }
    ]
  }
}
```

### Declaration

| Key | Description |
| --- | --- |
| id | 1 to 40 characters of a-z, 0-9 and _. Unique among the app's actions. |
| label | 1 to 80 characters. |
| description | Optional, 1 to 300 characters. |
| function | The app function Wave calls, 1 to 60 characters of a-z, 0-9 and -. |
| requires | none (default) or account. Wave sends a guest to sign in for an account action, then back to the form's page. |
| fields | 1 to 30 form fields. Wave drops every other submitted field. |
| effects | One or more of cart_add, message, redirect and reload. Wave 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.

| Type | Default max | Highest max | Value the function gets |
| --- | --- | --- | --- |
| text | 500 | 5,000 | Trimmed string |
| textarea | 5,000 | 50,000 | Trimmed string, line breaks kept |
| email | 254 | 254 | String with an @ and a domain |
| number | 30 | 30 | Number |
| boolean | - | - | true or false (a checked box is true) |
| select | 100 | 100 | One of options: 1 to 100 strings of 1 to 100 characters |
| hidden | 500 | 500 | String |

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

### Placing a form in a theme

A theme section posts to an action with the ui-kit `AppAction` component:

```typescript
<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 `/__site/actions/<app>/<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 `/__site/actions/`: Wave refuses any other form, button or link that points there.

### What Wave checks

Before it calls your function, Wave 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.

Wave 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. Wave's checks don't replace your own: the function route is public, so anyone can call it with any body.

### What the function receives

Wave 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:

```json
{
  "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 Wave knows it, or `null`: check that the cart belongs to the signed-in account before acting on it.

### What the function returns

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

```json
{
  "cart_add": [
    {
      "product_id": "…",
      "variant_id": "…",
      "quantity": 4
    }
  ],
  "message": {
    "text": "4 lines added",
    "tone": "success"
  },
  "redirect": "/account/quotes",
  "reload": true
}
```

| Key | Description |
| --- | --- |
| cart_add | At most 100 lines of {product_id, variant_id?, quantity}, quantity 1 to 9999. Wave 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. |
| redirect | A path on the storefront, at most 500 characters, starting with / and not // or /\. Anything else is ignored. Without a redirect, Wave goes back to the form's page. |
| reload | true shows the form's page again, with fresh data. |
| errors | An object of declared field ids, or _form, to messages of 1 to 300 characters. Wave shows the form again with the shopper's values and these errors, and applies no other effect. |

Wave 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.

### Messages and errors

Wave 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. Wave 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.

## Who the shopper is

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.

## Example: saved items

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`:

```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`:

```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`:

```typescript
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,
    // Wave 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:

```typescript
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, Wave 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 Wave 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.

## Testing

`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/`.

There is no local Wave storefront for testing extensions. Test them on a store's test environment:

**1. Push the app**

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

**2. Open the Wave editor**

Open the editor on a Wave storefront in the same environment. Embed blocks appear under **Apps** in the **Add section** panel. 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 Wave makes.

```txt
swell app push
swell logs
```
