> For the complete documentation index, see [llms.txt](https://docs.scaleflex.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.scaleflex.com/developers-headless/studio/template-builder/storage-modes.md).

# Storage modes

The widget has two modes, and they differ in one thing: who stores the template document. Everything else - rendering, fonts, the asset picker - works the same way in both. See [How rendering works](https://docs.scaleflex.com/developers-headless/studio/template-builder/how-rendering-works.md) for why that is.

|                                     | DAM-backed                      | Stateless             |
| ----------------------------------- | ------------------------------- | --------------------- |
| Who stores the template             | Scaleflex, as a file in the DAM | You do                |
| `template-id` means                 | A DAM file uuid                 | Any string you choose |
| Versioning, tenancy, access control | The DAM's                       | Yours                 |
| Works with a Hub session            | Yes                             | Yes                   |
| Works with a security template      | No                              | Yes                   |

### Which to choose

**Stateless**, if your application already has somewhere to put a document and its own idea of who may edit it. You keep your storage, your versioning, your tenancy and your access control, and no user of yours needs a Scaleflex identity. This is the usual choice for an external integration.

**DAM-backed**, if you want templates to live in the DAM alongside the assets they use, and your users already have Hub sessions. This is how the DAM's own **Edit template** action works.

### DAM-backed

Set `template-id` to a DAM file uuid. The deployment loads the template itself, and **Save** uploads a new version and reports the resulting uuid:

```html
<sfx-template-builder
  base-url="https://templates.example.com"
  token="PROJECT_TOKEN"
  sass-key="SASS_KEY"
  session-uuid="SESSION_UUID"
  template-id="TEMPLATE_UUID"
  style="display:block;height:800px"
></sfx-template-builder>
```

```js
builder.addEventListener('save', (e) => {
  const { uuid, name } = e.detail // the new version's uuid
})
```

Leave `template-id` empty to open the new-template flow instead.

You never pass `content` in this mode, and there is nothing to store on save - the `save` event is a notification, not a handoff.

Unsaved edits are also kept as a local draft in the author's browser, and offered back when the template is reopened there. See [Preview and save](https://docs.scaleflex.com/studio/template-builder/building-a-template/preview-and-save.md#getting-unsaved-changes-back) in the user guide.

### Stateless

Set `stateless`. You pass the template in, the author edits it, and you get the edited template back. Nothing is stored on the Scaleflex side unless you opt into [a rendering copy](https://docs.scaleflex.com/developers-headless/studio/template-builder/storing-a-rendering-copy.md).

The editor keeps no local draft in this mode: the document is yours, so it never writes it to the author's browser. If your page can lose unsaved edits (a reload, a route change), keep them yourself, for example by watching `dirtychange`.

The whole flow is three steps: fetch the XML from your endpoint, pass it in, take the edited XML back out.

```html
<sfx-template-builder
  stateless
  base-url="https://templates.example.com"
  token="PROJECT_TOKEN"
  sec-template="SEC_TEMPLATE_KEY"
  style="display:block;height:800px"
></sfx-template-builder>

<script type="module">
  const builder = document.querySelector('sfx-template-builder')
  const id = 'your-own-id-42'

  // 1 - get the template from your API.
  const { content, name, templateQuery } = await fetch(`/api/templates/${id}`)
    .then((r) => r.json())

  // 2 - pass it in.
  builder.load({ templateId: id, name, content, templateQuery })

  // 3 - take the edit back out and store it.
  builder.addEventListener('save', async (e) => {
    const { templateId, content, name, templateQuery } = e.detail

    const ok = await fetch(`/api/templates/${templateId}`, {
      method: 'PUT',
      headers: { 'content-type': 'application/json' },
      body: JSON.stringify({ content, name, templateQuery }),
    }).then((r) => r.ok)

    builder.confirmSave(ok)
  })

  // Loading a different template discards unsaved edits - check first.
  builder.addEventListener('dirtychange', (e) => {
    unsavedBanner.hidden = !e.detail.isDirty
  })
</script>
```

`templateId` is **your** identifier, not a DAM uuid. The deployment never resolves it against anything; it is carried alongside the content and handed straight back on save, so use whatever key maps to your own record.

### Reporting a failed save

The editor clears its unsaved-changes state as soon as it emits `save`. Receiving that event says nothing about whether you stored anything, so tell it when you did not:

```js
builder.addEventListener('save', async (e) => {
  try {
    await yourApi.saveTemplateXml(e.detail.templateId, e.detail.content)
    builder.confirmSave(true)
  } catch (err) {
    builder.confirmSave(false, 'Could not save - please try again.')
  }
})
```

The editor restores its dirty flag and warns the author instead of showing a failed write as saved. The React wrapper does this for you: return or resolve to `false` from `onSave`, or throw.

Acking is optional - a host that never calls `confirmSave` keeps the optimistic behavior. But only `ok: false` carries information, and without it a failed write is invisible to the author.

### Swapping templates

{% hint style="warning" %}
Assigning a new `content`, `templateId`, `templateName` or `templateQuery` reloads the editor and **discards unsaved edits without prompting**. The host is treated as authoritative. Watch `dirtychange`, or read the `isDirty` property, and ask the author first.
{% endhint %}

Re-assigning an identical template is a no-op, so a host re-render cannot destroy work by accident. The id is part of that identity check: moving between two records whose content is byte-identical does reload, so a save can never land on the record you navigated away from.

### Starting a template from scratch

A template your author has not created yet has no XML to pass in, and you should not have to write one. In stateless mode, set `new-template` instead of `content` and the widget supplies the empty document itself.

```html
<sfx-template-builder
  stateless
  new-template
  template-name="Untitled"
  base-url="https://templates.example.com"
  token="PROJECT_TOKEN"
  sec-template="SEC_TEMPLATE_KEY"
  style="display:block;height:800px"
></sfx-template-builder>
```

Or on an element that is already showing something else:

```js
builder.createNew({ templateId: 'your-own-id-43', name: 'Untitled' })
```

```tsx
<TemplateBuilder stateless newTemplate templateName="Untitled" ... />
```

The editor opens with the **Add first layout** window over it, where the author names the first layout and picks its canvas size, preset and background. Closing the window leaves the author in the editor on an empty canvas, with a button that reopens it. Nothing is sent to you either way.

Save is refused until at least one layout exists, so the first `save` you receive already carries a complete, well-formed document. Store it as `content` and every later open is the ordinary load flow above.

* **`templateId` is optional.** Pass one if your record already exists and you want it echoed back. Otherwise the `save` payload arrives without an id and you allocate one when you store it.
* **`templateQuery` comes back empty.** A new document has no layouts and no variables, so there is no render for a query to select. You get one on the first save - persist it then.
* **`content` wins when both are set**, so a host that renders one element for both cases can simply pass the XML when it has one.
* **Empty `content` on its own does not start a blank template.** It means "the host has nothing yet", and the editor keeps waiting - which is what lets you mount the builder while your fetch is still in flight. Only `new-template` turns that wait into a document.

Calling `createNew()` again while the blank template is already open does nothing, because resending would discard whatever the author has built since. Close and reopen the editor to genuinely start over.

{% hint style="info" %}
**To ship your own starting point** - a house style, a standard canvas size, a locked logo layer - pass it as ordinary `content`. A starter template is just a template. `BLANK_TEMPLATE_XML` is exported from `@scaleflex/template-builder` if you want the empty document as a base.
{% endhint %}

### Where to go next

* [Storing a rendering copy](https://docs.scaleflex.com/developers-headless/studio/template-builder/storing-a-rendering-copy.md) - getting a CDN URL out of a stateless save
* [The render URL](https://docs.scaleflex.com/developers-headless/studio/template-builder/render-url.md) - what `templateQuery` is for
* [Authentication](https://docs.scaleflex.com/developers-headless/studio/template-builder/authentication.md) - the credential each mode accepts
