# Unlayer Documentation
> Unlayer is an embeddable, white-label drag-and-drop editor SDK that lets your users design responsive emails, landing pages, documents, and popups inside your own application. It pairs the visual builders with built-in AI — an assistant that edits designs from a chat prompt and an importer that turns HTML or screenshots into editable templates — plus a server-side Cloud API for exporting designs to HTML, PDF, images, and ZIP. These docs cover embedding and configuring the JavaScript builders (with React, Angular, and Vue wrappers), the AI features, deep white-label customization, the Cloud API, developer tools (CLI, Hyper Elements for transactional emails, landing pages, invoices, and PDFs in React code, MCP server, and AI coding-assistant Skills), and the portable design JSON data model.
This file contains all documentation content in a single document following the llmstxt.org standard.
## Vanilla JS
# Vanilla JS Setup
This guide covers embedding Unlayer directly with plain HTML and JavaScript. No framework or build tools required.
---
## Step 1: Add the Embed Script
Include the Unlayer embed script in your HTML page:
```html
Unlayer Editor
```
---
## Step 2: Initialize the Editor
```html
```
---
## Step 3: Add Export and Save Buttons
```html
Export HTML
Save Design
```
---
## Complete Example
```html
Unlayer Editor
Export HTML
Save Design
```
---
## Configuration Options
Pass additional options to customize the builder:
```javascript
unlayer.init({
id: 'editor-container',
displayMode: 'email',
appearance: {
theme: 'modern_light',
},
features: {
textEditor: {
spellChecker: true,
},
},
});
```
---
## Loading a Saved Design
```javascript
// After the editor is ready
unlayer.addEventListener('editor:ready', function () {
var savedDesign = /* fetch from your backend */;
unlayer.loadDesign(savedDesign);
});
```
---
## What's Next
- Explore the full [Builders documentation](/builder/installation) for advanced options.
- Consider using a [framework wrapper](/builder/react-component) for richer integration.
---
## Get Started with Unlayer
Unlayer helps developers add content creation to their applications. Let users design emails, pages, images, and documents with drag-and-drop builders, while your app uses APIs and AI to generate, save, export, and automate content. Ship a complete content workflow without building the entire stack yourself.
Pick a product and follow the step-by-step guide, or choose your framework below.
## Framework Setup
Already know your stack? Wire up the SDK in your framework.
## How Unlayer Fits Together
---
## Export HTML
Now that you have set up the editor in your application and users are creating content, it's time to save the resulting work i.e HTML.
This is how you can export the design's HTML.
:::tip Save Button
Most applications will add a save button that calls this export function.
:::
```javascript
unlayer.exportHtml(function (data) {
var json = data.design; // design json
var html = data.html; // final html
// Do something with the json and html
});
```
## Callback Parameters
The exportHtml callback returns the following parameters.
| Name | Description |
| :--------- | :-------------------------------------------------------------------------------------------------------------------------------------------- |
| **design** | This is the JSON of the design |
| **html** | This is the full HTML of the design, starting with the opening `` tag to the closing `` tag. |
| **chunks** | This includes the chunks of HTML separately in case you want to build your own layout. Check the [chunk parameters](#chunk-parameters) below. |
---
## Chunk Parameters
The following chunks of HTML are available.
| Name | Description |
| :-------- | :--------------------------------------------------------------------------------------------------------------------------------------------------- |
| **body** | This is the body part of the HTML that is added inside the `` tags. |
| **css** | This is the CSS required for the design to render properly. You can add it inside the `` tags. |
| **js** | This is the JS required for the design to render properly. You can add it inside the `` tags. |
| **fonts** | This includes any web fonts or [custom fonts](../../advanced-configuration/font-management/custom-fonts.md) used in the design so you can load them. |
---
## Export Options
You can also pass certain options to this function as a second parameter.
### Cleanup
By default, we clean up the final HTML and remove unused HTML class names and CSS styles. If you want to disable that feature, you can pass `cleanup: false`.
```javascript
unlayer.exportHtml(
function (data) {
var json = data.design;
var html = data.html;
},
{
cleanup: true,
},
);
```
### Minify
By default, the HTML output is not minified or compressed. However, it is recommended to export the HTML minified and compressed as it can reduce the file size by up to 25%.
```javascript
unlayer.exportHtml(
function (data) {
var json = data.design;
var html = data.html;
},
{
minify: true,
},
);
```
### Outlook Support
Email exports include compatibility markup for classic Outlook for Windows and legacy Internet Explorer by default. If your recipients use email clients that render standard HTML and CSS, pass `outlookSupport: false` to reduce the exported HTML size.
```javascript
unlayer.exportHtml(
function (data) {
// Send or save data.html
},
{
minify: true,
outlookSupport: false,
},
);
```
This removes conditional comments and their Outlook-only content, including layout tables, VML backgrounds and buttons, and Outlook image copies. The normal HTML content is preserved. The option also applies to conditionals in custom HTML and custom exporters, and to `chunks.body` and `chunks.tags`.
Only use this option when you can accept reduced layout, image scaling, background image, and button compatibility in classic Outlook for Windows. This also removes Outlook's image-scaling safeguards and conditionals around web-font links. Content hidden on desktop may also appear in classic Outlook when its conditional hiding markup is removed. Modern Outlook clients that use standard HTML rendering keep the normal HTML version. Other display modes and AMP HTML are unchanged; an AMP export's normal HTML fallback honors the option.
The option applies to that export call. Preview, including Inbox Previews, and Send Test Email keep the default compatibility markup. Editor versions released before this option ignore it.
### Reducing Email Size
Start with `minify: true` and keep the default cleanup enabled. Use fewer rows and columns where possible, remove unused content, and avoid repeating large blocks of inline HTML or CSS. Use `outlookSupport: false` only if the compatibility tradeoff above fits your recipients.
Measure the UTF-8 byte size of the final HTML after your email provider adds tracking links or other markup:
```javascript
const bytes = new TextEncoder().encode(html).length;
```
Leave room below Gmail's approximately 102 KB clipping limit. Minification and the Outlook opt-out reduce markup but do not guarantee that a long email will avoid clipping. Remote image file sizes are separate from the HTML size; embedded image data contributes to it.
### Merge Tags
If you want the [Merge Tags](../../advanced-configuration/dynamic-content/merge-tags.md) in your design to be replaced by different values, you can pass the `mergeTags` object to export options.
```javascript
unlayer.exportHtml(
function (data) {
var json = data.design;
var html = data.html;
},
{
mergeTags: {
first_name: 'John',
last_name: 'Doe',
},
},
);
```
### Inline Styles
Inline Styles options can be used to Inline the global css styles for links. This is useful in some instances for the email builder where Gmail or some other clients may not respect the link styles. By default, this is set to `false`.
```javascript
unlayer.exportHtml(
function (data) {
var json = data.design;
var html = data.html;
},
{
inlineStyles: true,
},
);
```
---
## Cloud API
You can also use our Cloud API if you want to export a design to HTML from a server-to-server API call. [Learn More](/server/cloud-api/reference#tag/export/operation/exportHtml)
---
## Export Image
Similar to the [Export HTML](./export-html.md) function, you can also export a design in image format. This would upload the generated image to your connected [File Storage](../../files-storage/file-storage/overview.md) and send the link to the callback function.
Note: Unlike HTML or plain text, images are not generated on the client. This function uses our cloud API to generate the image.
Each call counts toward your workspace's monthly [export allowance](/server/cloud-api/export-allowances). When the allowance is used up, the callback receives an `error` message and no `url`.
```javascript
unlayer.exportImage(function (data) {
var json = data.design; // design json
var imageUrl = data.url; // image url
// Do something with the image url
});
```
## Callback Parameters
The exportImage callback returns the following parameters.
| Name | Description |
| :--------- | :------------------------------------- |
| **design** | This is the JSON of the design |
| **url** | This is the URL of the generated image |
---
## Export Options
You can also pass certain options to this function as a second parameter.
### Merge Tags
If you want the [Merge Tags](../../advanced-configuration/dynamic-content/merge-tags.md) in your design to be replaced by different values, you can pass the `mergeTags` object to export options.
```javascript
unlayer.exportImage(
function (data) {
var json = data.design; // design json
var imageUrl = data.url; // image url
},
{
mergeTags: {
first_name: 'John',
last_name: 'Doe',
},
},
);
```
---
### Full Page
If you want the exported image to be the full page design, you can use this option. It is enabled by default.
```javascript
unlayer.exportImage(
function (data) {
var json = data.design; // design json
var imageUrl = data.url; // image url
},
{
fullPage: false,
},
);
```
---
## Cloud API
If you want to generate an image on the server-side, you can use our [Cloud API](/server/cloud-api/reference#tag/export/operation/exportImage).
```javascript
const fetch = require('node-fetch');
let url = 'https://api.unlayer.com/v2/export/image';
let options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: 'Basic BASE64-ENCODED-API-KEY',
},
body: JSON.stringify({
displayMode: 'email',
design: {}, // json of your design
mergeTags: { first_name: 'John', last_name: 'Doe' },
}),
};
fetch(url, options)
.then((res) => res.json())
.then((json) => console.log(json))
.catch((err) => console.error('error:' + err));
```
Learn more at [Cloud API reference](/server/cloud-api/reference#tag/export/operation/exportImage).
### Document designs
For a design built with the [Document Builder](../../builders/document-builder/overview.md) (`displayMode: 'document'`), the image is the first page of the document as the [PDF export](./export-pdf.md) shows it: the same page size, margins, header and footer. The header and footer appear when your plan includes them, as in the PDF.
To change the paper, pass `pageSize` and `documentOrientation`. They work as in the [PDF export](./export-pdf.md#page-format), with the same plan rules and the same `403` and `400` responses.
The image is as wide as the page, for example 794 pixels for A4, multiplied by `deviceScaleFactor` when you pass it. For document designs the scale counts as at least 1 and at most 3, so 0.5 still gives 794 pixels and 4 gives 2382. `fullPage` doesn't apply, and later pages aren't included; export a PDF to get every page. In the editor, `unlayer.exportImage` doesn't support document designs, so use the Cloud API.
### Response
The API response will return an uploaded image URL.
```json
{
"success": true,
"data": {
"url": "https://.../1593082715347-8LCcNZuuBpU4D92W.png"
}
}
```
---
## Export PDF
Similar to the [Export HTML](./export-html.md) function, you can also export a design in PDF format. This would upload the generated PDF to your connected [File Storage](../../files-storage/file-storage/overview.md) and send the link to the callback function.
In the [Document Builder](../../builders/document-builder/overview.md), the PDF is rendered in the browser and stored like a server export, on plans that include PDF export. These PDFs don't count toward your export allowance, and in Unlayer's storage they are deleted after 7 days. Our cloud API renders the few the browser can't deliver, such as one over 25 MB, and those count. To get the PDF itself instead of a link, use [`dataUrl`](#data-url). See [PDF Rendering](../../builders/document-builder/pdf-rendering.md).
:::warning Document Builder links can expire after 7 days
A Document Builder `url` that points to Unlayer's storage stops working 7 days after the export when the browser rendered the PDF, which is most of the time. PDFs that Unlayer's servers render instead (on a free plan, or when the browser can't build or upload the PDF) and PDFs stored in your own Amazon S3 bucket stay until you delete them. The callback doesn't say which one you got, so if you keep PDFs longer than 7 days, save the file itself: download it from `url` within 7 days, or pass [`dataUrl: true`](#data-url) and store the PDF yourself. Links from the other display modes don't expire.
:::
In the other display modes, this function uses our cloud API to generate the PDF.
Each PDF our cloud API generates counts toward your workspace's monthly [export allowance](/server/cloud-api/export-allowances). When the allowance is used up, the callback receives an `error` message and no `url`.
```javascript
unlayer.exportPdf(function (data) {
var json = data.design; // design json
var pdfUrl = data.url; // pdf url
// Do something with the PDF url
});
```
## Callback Parameters
The exportPdf callback returns the following parameters.
| Name | Description |
| :----------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **design** | This is the JSON of the design |
| **url** | This is the URL of the generated PDF, or the PDF itself as a `data:` URL with [`dataUrl`](#data-url) |
| **offline** | `true` when a document was rendered in the browser in offline mode: `url` is then a `data:` URL, not an upload |
| **error** | Why no PDF was produced. `url` is then `null` or absent |
| **warnings** | What a document's PDF misses or draws differently, such as an image that couldn't be loaded, when it was rendered in the browser. Absent when there's nothing to report |
---
## Export Options
You can also pass certain options to this function as a second parameter.
### Merge Tags
If you want the [Merge Tags](../../advanced-configuration/dynamic-content/merge-tags.md) in your design to be replaced by different values, you can pass the `mergeTags` object to export options.
```javascript
unlayer.exportPdf(
function (data) {
var json = data.design; // design json
var pdfUrl = data.url; // pdf url
},
{
mergeTags: {
first_name: 'John',
last_name: 'Doe',
},
},
);
```
In the [Document Builder](../../builders/document-builder/overview.md), substituted values can change how tall each row is. The browser paginates each PDF from its rendered content, with the values and `language` you pass, so when those differ from what the canvas displays (a merge tag's sample, or its name when it has no sample), the PDF's page breaks can differ from the canvas.
---
### Data URL
Pass `dataUrl: true` to receive the PDF itself in `url`, as a `data:` URL, instead of a link to a stored file. Use it when you store or send the PDF yourself.
```javascript
unlayer.exportPdf(
function (data) {
var pdfDataUrl = data.url; // data:application/pdf;base64,...
},
{
dataUrl: true,
},
);
```
In the [Document Builder](../../builders/document-builder/overview.md), where the browser renders the PDF, nothing is uploaded. When the browser can't build the PDF, the callback receives an `error` instead: when the editor is hidden with `display: none`, which leaves the browser nothing to measure, when the PDF's fonts can't be loaded, or when the document is too large for the browser renderer (hundreds of dense pages). Without `dataUrl`, Unlayer's servers render those. In the other display modes, our cloud API renders the PDF and stores it in your File Storage, and the editor reads it back to return it. If it can't be read, the callback receives an `error` and no `url`.
Browsers don't open a `data:` URL in a new tab or window. To show the PDF, convert it to a `Blob` and open an object URL, or download it with a link that has a `download` attribute.
---
### Page Format
When using the [Document Builder](../../builders/document-builder/overview.md) (`displayMode: 'document'`), you can override the page format that the PDF will be rendered at without modifying the saved design. This is useful for generating the same design at different paper sizes — for example, rendering a US customer's invoice as Letter and an EU customer's as A4 from a single template.
:::info Availability
In the editor SDK and Export API v3, `pageSize` and `documentOrientation` overrides require a plan that includes PDF page-format overrides. Legacy plans use A4 portrait for document-mode exports. They can omit the fields or explicitly pass the A4 portrait no-op; a different format is refused: `exportPdf` receives an `error`, and Export API v3 returns a `403` response.
The deprecated Export API v2 keeps its original `pageSize` contract for backward compatibility. Existing PDF customers, including legacy plans, can continue to use its full supported format list. The newer `documentOrientation` option still requires PDF page-format overrides.
All versions still require PDF export access.
:::
| Option | Type | Description |
| :------------------------ | :------------------------------------------------------------------------------------------------------------------------- | :----------------------------------------------------------------------------------------------------------- |
| **`pageSize`** | `'Letter'` \| `'Legal'` \| `'Tabloid'` \| `'Ledger'` \| `'A0'` \| `'A1'` \| `'A2'` \| `'A3'` \| `'A4'` \| `'A5'` \| `'A6'` | Paper size for the PDF. Requires PDF page-format overrides on v3; retained for existing PDF customers on v2. |
| **`documentOrientation`** | `'portrait'` \| `'landscape'` | Page orientation override. Requires a plan that includes PDF page-format overrides. |
When `pageSize` is omitted, document-mode exports use the design's saved page size and orientation when the plan includes page-format controls. Projects without this feature use A4 portrait instead; non-default page values stored in their designs are ignored. The saved setting is named `body.values.documentSize`; it is not a separate export parameter. Saved formats use their standard physical paper dimensions consistently across Export API v2 and v3.
Page margin comes from the design's saved `body.values.documentMargin`, including when `pageSize` overrides the paper. The default `'auto'` uses the format's standard margin (A5 uses a tighter margin than A4), and a pixel value applies as saved. Margin isn't a per-call option. See [Page Format](../../builders/document-builder/page-format.md).
When `pageSize` is used without `documentOrientation`, it keeps the named PDF format's natural orientation instead of inheriting the orientation stored in the design. Ledger is naturally landscape; every other listed format is naturally portrait. Projects with PDF page-format overrides can pass `documentOrientation: 'portrait'` to rotate Ledger.
All plans with PDF export access can export without a per-call format override:
```javascript
unlayer.exportPdf((data) => console.info(data));
```
Plans with PDF page-format overrides can select another format through the editor SDK or Export API v3:
```javascript
unlayer.exportPdf((data) => console.info(data), { pageSize: 'Letter' });
```
Legacy integrations calling Export API v2 directly can also continue sending `pageSize`.
An unsupported `pageSize` isn't replaced by another paper size: `exportPdf` receives an `error`, and the Export API returns a `400` response.
```javascript
unlayer.exportPdf(
function (data) {
var json = data.design;
var pdfUrl = data.url;
},
{
pageSize: 'Letter',
documentOrientation: 'landscape',
},
);
```
When an override changes the page geometry, the PDF is paginated using the override's dimensions rather than the editor's currently-displayed pagination. The result will differ from what you see on the canvas if the override's geometry doesn't match the design's saved values — that's intentional.
Existing v2 integrations continue using `pageSize` for PDF export. New v3 integrations need PDF page-format override access to select a non-A4 document format.
---
### Watermark
When using the [Document Builder](../../builders/document-builder/overview.md), you can stamp a text watermark over every page of the PDF. For example, you can mark a draft you send to a client for review. The watermark is drawn on top of the finished pages, so your content and layout stay exactly as designed.
:::info Availability
Custom watermarks require a current paid plan that includes Document Watermarks; legacy plans don't include them. They work on document-mode PDFs (`displayMode: 'document'`) through the editor SDK, Export API v3 and the deprecated Export API v2.
On free plans, document PDFs and the editor canvas carry an Unlayer watermark on every page. Free plans don't include Document Watermarks, so a request for a custom watermark is refused, as described below.
:::
| Option | Type | Description |
| :------------- | :-------------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------- |
| **`text`** | `string` | Required. Plain text, printed literally on a single line (HTML isn't interpreted). 1 to 100 characters. |
| **`position`** | `'diagonal'` \| `'center'` \| `'top'` \| `'bottom'` | Where the watermark sits on each page. `diagonal` runs corner to corner; `top` and `bottom` place it along that edge. Defaults to `'diagonal'`. |
| **`opacity`** | `number` | From `0.05` to `1`. Defaults to `0.2`. |
| **`color`** | `string` | Color as `#RGB`, `#RRGGBB` or `rgb(r, g, b)` with 0–255 channels. Defaults to `#808080`. |
The text size is chosen automatically so the watermark fits the page.
Watermark a single export:
```javascript
unlayer.exportPdf(
function (data) {
var pdfUrl = data.url;
},
{
watermark: {
text: 'Draft for client review',
position: 'diagonal',
opacity: 0.2,
color: '#808080',
},
},
);
```
To watermark every PDF by default, including the document preview and its **Download PDF** button, set `features.watermark` when you initialize the editor:
```javascript
unlayer.init({
// ...
displayMode: 'document',
features: {
watermark: { text: 'Draft', position: 'top' },
},
});
```
The editor also draws this default on every page of the canvas and its page thumbnails, where the PDF will place it, so you design with it in view. The canvas watermark is only a guide in the editor and is never part of the exported HTML.
A `watermark` passed to a single call replaces the default for that call, and `watermark: false` turns it off:
```javascript
unlayer.exportPdf((data) => console.info(data), { watermark: false });
```
You can also set the watermark for one preview:
```javascript
unlayer.showPreview({ watermark: { text: 'Draft v2' } });
```
If you request a watermark on a plan without Document Watermarks, or with invalid options, `exportPdf` doesn't create a PDF and its callback receives an `error` instead of a `url`. `showPreview` refuses it the same way: the preview shows that error instead of the document, and its **Download PDF** button doesn't download. An `unlayer.init` default that can't apply, including one with invalid options, is skipped with a console warning instead, so exports and previews keep working.
---
## Cloud API
If you want to generate the PDF on the server-side, you can use our [Cloud API](/server/cloud-api/reference#tag/export/operation/exportPdf).
```javascript
const fetch = require('node-fetch');
let url = 'https://api.unlayer.com/v2/export/pdf';
let options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: 'Basic BASE64-ENCODED-API-KEY',
},
body: JSON.stringify({
displayMode: 'email',
design: {}, // json of your design
mergeTags: { first_name: 'John', last_name: 'Doe' },
}),
};
fetch(url, options)
.then((res) => res.json())
.then((json) => console.info(json))
.catch((err) => console.error('error:' + err));
```
Learn more at [Cloud API reference](/server/cloud-api/reference#tag/export/operation/exportPdf).
For document-mode designs, set `displayMode: 'document'`. This v2 endpoint preserves `pageSize` for existing PDF customers, including legacy plans. Passing `documentOrientation` still requires PDF page-format override access. On Export API v3, selecting a non-A4 document format requires that access as well. Page margin comes from the design's `body.values.documentMargin` and isn't a separate request field.
```javascript
body: JSON.stringify({
displayMode: 'document',
design: {}, // json of your document design
pageSize: 'Letter',
documentOrientation: 'landscape',
});
```
To watermark a document PDF from your server, pass `watermark` to Export API v3. It takes the same options as the [editor SDK](#watermark) and requires a plan that includes Document Watermarks. When the watermark has been applied, the response `data` includes `"watermark": "custom"`. Free plans don't include PDF export, so the API returns a `403` response. On a free plan with PDF export enabled, whose document PDFs always carry the Unlayer watermark, it includes `"watermark": "unlayer"` instead, even when you don't pass `watermark`. The deprecated v2 endpoint accepts the same `watermark` field and returns the same confirmation.
```javascript
let url = 'https://api.unlayer.com/v3/templates/export/pdf';
let options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: 'Bearer unlayer_sk_your_api_key',
},
body: JSON.stringify({
displayMode: 'document',
design: {}, // json of your document design
watermark: { text: 'Confidential', position: 'top', opacity: 0.4 },
}),
};
```
An API key is scoped to one project. With a [Personal Access Token](/server/authentication), add `?projectId=YOUR_PROJECT_ID` to the URL. See the [Export PDF reference](/server/cloud-api/reference#tag/export/operation/exportPdf) for every request field.
### Response
The API response will return an uploaded pdf URL.
```json
{
"success": true,
"data": {
"url": "https://.../1593082715347-8LCcNZuuBpU4D92W.pdf"
}
}
```
---
## Export Plain Text
Similar to [Export HTML](./export-html.md), you can also export a design in plain text. This is useful if you want to send an email in multiple formats for different email clients.
```javascript
unlayer.exportPlainText(function (data) {
var json = data.design; // design json
var text = data.text; // final text
// Do something with the json and text
});
```
## Callback Parameters
The exportPlainText callback returns the following parameters.
| Name | Description |
| :--------- | :---------------------------------------- |
| **design** | This is the JSON of the design |
| **text** | This is the full plain text of the design |
---
## Export Options
You can also pass certain options to this function as a second parameter.
### Omit Content
You can configure which parts of the design you want to omit in the plain text. For example, you can choose to ignore images, links, or preheader text.
```javascript
unlayer.exportPlainText(
function (data) {
var json = data.design;
var text = data.text;
},
{
ignoreLinks: true,
ignoreImages: true,
ignorePreheader: true,
},
);
```
| Name | Description |
| :------------------ | :---------------------------------------------- |
| **ignoreLinks** | Links and buttons will not be included |
| **ignoreImages** | Image alt text will not be included |
| **ignorePreheader** | Pre-header text for emails will not be included |
### Merge Tags
If you want the [Merge Tags](../../advanced-configuration/dynamic-content/merge-tags.md) in your design to be replaced by different values, you can pass the `mergeTags` object to export options.
```javascript
unlayer.exportPlainText(
function (data) {
var json = data.design;
var text = data.text;
},
{
mergeTags: {
first_name: 'John',
last_name: 'Doe',
},
},
);
```
---
## Export ZIP
Similar to the [Export HTML](./export-html.md) function, you can also export a design as a ZIP file. This generates a bundle ZIP file that also includes all the images required by your design and uploads it to your connected [File Storage](../../files-storage/file-storage/overview.md).
Note: Unlike HTML or plain text, ZIP file is not generated on the client. This function uses our cloud API to generate the ZIP file.
Each call counts toward your workspace's monthly [export allowance](/server/cloud-api/export-allowances). When the allowance is used up, the callback receives an `error` message and no `url`.
```javascript
unlayer.exportZip(function (data) {
var json = data.design; // design json
var fileUrl = data.url; // zip file url
// Do something with the ZIP url
});
```
## Callback Parameters
The exportZip callback returns the following parameters.
| Name | Description |
| :--------- | :---------------------------------------- |
| **design** | This is the JSON of the design |
| **url** | This is the URL of the generated ZIP file |
---
## Export Options
You can also pass certain options to this function as a second parameter.
### Merge Tags
If you want the [Merge Tags](../../advanced-configuration/dynamic-content/merge-tags.md) in your design to be replaced by different values, you can pass the `mergeTags` object to export options.
```javascript
unlayer.exportZip(
function (data) {
var json = data.design; // design json
var fileUrl = data.url; // zip file url
},
{
mergeTags: {
first_name: 'John',
last_name: 'Doe',
},
},
);
```
---
## Cloud API
If you want to generate the ZIP file on the server-side, you can use our [Cloud API](/server/cloud-api/reference#tag/export/operation/exportZip).
```javascript
const fetch = require('node-fetch');
let url = 'https://api.unlayer.com/v2/export/zip';
let options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: 'Basic BASE64-ENCODED-API-KEY',
},
body: JSON.stringify({
displayMode: 'email',
design: {}, // json of your design
mergeTags: { first_name: 'John', last_name: 'Doe' },
}),
};
fetch(url, options)
.then((res) => res.json())
.then((json) => console.log(json))
.catch((err) => console.error('error:' + err));
```
Learn more at [Cloud API reference](/server/cloud-api/reference#tag/export/operation/exportZip).
### Response
The API response will return an uploaded zip file URL.
```json
{
"success": true,
"data": {
"url": "https://.../1593082715347-8LCcNZuuBpU4D92W.zip"
}
}
```
---
## Installation
This page will help you get started with Unlayer. You'll be up and running in a jiffy!
## Step 1: Add JavaScript Library
To get started, you need to add the Unlayer JavaScript library to your web app. This library will load everything needed to run the builder.
```html
```
If you are using **React**, **Angular** or **Vue**, check our components available on npm:
- [React Component](../libraries/react-component.md)
- [Angular Component](../libraries/angular-component.md)
- [Vue Component](../libraries/vue-component.md)
---
## Step 2: Add a Container for the Editor
The Unlayer editor needs a container element on your page. Add a blank div where the editor will be displayed.
```html
```
:::info Recommended Size
For the best experience, ensure the container is at least **1024px** wide and **700px** high. The editor will expand to fill the entire container.
:::
---
## Step 3: Initialize the Editor
Now, let’s initialize the editor inside the container you just created by passing its id and configuration options.
```javascript
unlayer.init({
id: 'editor-container', // ID of the container created in previous step
projectId: 1234, // Add your project ID here
displayMode: 'email', // Can be 'email', 'web', 'document' or 'popup'
});
```
### Where to get the Project ID?
1. Log in to the **[Developer Console](https://console.unlayer.com/)**
2. Create a **Project**
3. You can find the project ID in **Project > Settings**
---
### Premium previews in Developer Console
When you open a project in Developer Console, the editor may let you try
capabilities that are not included in your current plan. **Premium** badges on
individual controls identify the capabilities you are previewing. Hover a badge
to preview an interactive card with the first current plan that includes that
capability, or click or tap the badge to keep the card open. Escape and outside
clicks dismiss it. Workspace owners can open upgrade options from the card;
other members are prompted to ask a workspace owner to upgrade. Plan names and
allowances reflect the live plan catalog and your account-specific limits.
Standalone badges are keyboard-focusable, so their plan guidance does not
require a pointer. Badges inside buttons and other interactive controls share
the control's keyboard stop instead of adding a nested stop.
If one action depends on several premium capabilities, the guidance names the
first current plan that includes all of them for your account. Premium cards
open only when you interact with a badge; using a previewed capability does not
open one automatically. These markers only appear in Developer Console and do
not appear in your embedded editor.
### Configuration Options
Here's a breakdown of some commonly used configuration options for `unlayer.init()`:
| Attribute | Required | Description |
| -------------------------------------------------------------------------------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **id** _string_ | Yes | This is the HTML div id of the container where the editor will be embedded. |
| **displayMode** _string_ | No | This decides which builder to load. Available values: `email`, `web`, `document`, `popup`. Default value is `web`. We have these builders available: [Email Builder](../builders/email-builder/overview.md), [Page Builder](../builders/page-builder/overview.md), [Document Builder](../builders/document-builder/overview.md), [Popup Builder](../builders/popup-builder/overview.md) |
| **projectId** _integer_ | No | This is the project ID from Unlayer. You can get it from the project settings page. |
| **locale** _string_ | No | This is the locale you want to load the editor in. We have many translations available. [Learn more](../advanced-configuration/localization.md) |
| **appearance** _object_ | No | These are the appearance options to change the look and feel of the editor. [Learn more](../customization/appearance/overview.md) |
| **user** _object_ | No | This is the info of the user who is using the editor. You can pass `id`, `name` and `email`. [Learn More](../advanced-configuration/end-user-identification.md). |
| **mergeTags** _array_ | No | This is an array of objects. You can pass the merge tags to display in the editor. [Learn more](../advanced-configuration/dynamic-content/merge-tags.md) |
| **designTags** _object_ | No | You can pass design tags in this object. [Learn more](../advanced-configuration/dynamic-content/design-tags.md) |
| **specialLinks** _object_ | No | You can pass special links in this object. [Learn More](../advanced-configuration/link-management/special-links.md) |
| **tools** _object_ | No | These are the options for tools and custom tools. [Learn more](../tools/overview.md) |
| **blocks** _array_ | No | This is an array of objects. You can pass custom blocks here. [Learn more](../blocks/custom-blocks.md) |
| **editor** _object_ | No | These are some editor options for different functions of the editor. [Learn more](../customization/editor-behavior/overview.md) |
| **fonts** _object_ | No | You can pass custom fonts here. [Learn More](../advanced-configuration/font-management/overview.md) |
| **customJS** _array_ | No | Custom JavaScript URL or source. [Learn more](../customization/appearance/custom-js-css.md) |
| **customCSS** _array_ | No | Custom CSS URL or source. [Learn more](../customization/appearance/custom-js-css.md) |
| **textDirection** _string_ | No | This is the text direction of html output which can be `rtl` or `ltr`. |
---
### Multiple Instances
You can create multiple instances of the editor on the same page, or if you have a single page application.
```javascript
const editor = unlayer.createEditor({
id: 'editor-container',
projectId: 1234, // Add your project ID here
displayMode: 'email',
});
editor.loadDesign({});
editor.exportHtml(function (data) {});
```
---
## Step 4: Deploy to Production
To access project settings and premium features in production:
1. Log in to **[Developer Console](https://console.unlayer.com)** and go to your project.
2. **Pass the `projectId`** when initializing the builder. You can find the project ID in console under Project > Settings.
3. **Add Allowed Domains**: Ensure your builder only works on specific domains. Go to Project > Settings > Deployment and add your allowed domains under “Allowed Domain(s)” section as shown below.
---
## Load and Save Designs
The builder provides APIs to **load**, **save**, and even **auto-save** designs in your application. This allows developers to manage and persist user-created designs seamlessly. When the builder is initialized, it loads with a blank design.
:::info JSON Format
All designs are loaded and saved in the JSON format
:::
## Load Design
To load a pre-existing design or template into the editor, you can use the `unlayer.loadDesign()` method. The design is passed as a JSON object.
**Example:**
```javascript
var design = {...}; // template JSON
unlayer.loadDesign(design);
```
- **design**: This is the JSON object that contains the design structure. When this method is called, the editor will load the specified design or template into the builder.
---
## Save Design
To save a design, you can use the `unlayer.exportHtml()` method. This method will export both the design’s HTML and its JSON structure. You can then save either or both, depending on your requirements.
**Example:**
```javascript
unlayer.exportHtml(function (data) {
var json = data.design; // The design JSON structure
var html = data.html; // The final HTML of the design
// Save the JSON and/or HTML
});
```
- **data.design**: This contains the design’s JSON structure, which can be stored for later use or modifications.
- **data.html**: This is the final HTML output that you can use to render the design on the web or in emails.
---
## Auto-Saving a Design
If you want to automatically save the design whenever the user makes changes, you can listen for the [`design:updated`](../advanced-configuration/events-callbacks.md#design-updated) event. This event is triggered every time the user updates the design in the editor.
**Example:**
```javascript
unlayer.addEventListener('design:updated', function (updates) {
// Design has been updated by the user
unlayer.exportHtml(function (data) {
var json = data.design; // The updated design JSON
var html = data.html; // The updated HTML
// Auto-save the JSON and/or HTML here
});
});
```
- **design:updated event**: This event is fired whenever the user modifies the design in the editor.
- **Auto-save logic**: After detecting changes, the design can be saved automatically in the background by exporting the design JSON and/or HTML.
---
## Best Practices for Saving Designs
- **Use the JSON**: The JSON structure is ideal for storing the design in a database because it allows you to reload and edit the design later.
- **Use the HTML**: The HTML can be used for rendering the final output on a website or in an email. It is typically not modifiable once saved.
---
## Example Use Cases
1. **Loading a Pre-Existing Template**: You might have a saved design template that you want to load into the editor for further customization by the user. The `unlayer.loadDesign()` method makes it easy to load and edit.
2. **Saving User-Generated Designs**: When a user finishes creating a design, you can save both the JSON for reloading/editing purposes and the HTML for displaying or sending as an email.
3. **Auto-Saving in Real-Time**: To avoid losing any user changes, set up auto-saving that listens for the `design:updated` event and automatically saves the current state of the design.
## Related
- **[AI Agents](/ai/agents)** — let agents read, validate, and update the design in an open builder. Requires Builder 1.519.0 or later.
---
## Version Management
Unlayer provides flexibility for developers by offering different release channels for the builder and the ability to lock the builder to a specific version. By using these options, you can control which version of the builder is loaded in your application, whether it be the latest cutting-edge version or a stable release.
This is especially useful for developers who want to:
- Use the latest features and improvements as soon as they are available.
- Ensure stability by locking their application to a known stable version.
- Lock the builder to a specific version number to prevent unexpected updates.
---
## Release Channels
Unlayer supports two main release channels:
1. **Stable**: The default and most reliable release channel. This version contains thoroughly tested features and is recommended for production environments. It provides maximum stability and minimal changes over time.
2. **Latest**: The edge version that contains the latest features, bug fixes, and improvements. It is updated more frequently and includes the most recent changes. This is ideal for developers who want to test new features early.
---
## Using a Release Channel
You can specify which release channel or version of the builder to load by passing the version option when initializing the builder. By default, the builder loads the stable version unless otherwise specified.
```javascript
unlayer.init({
version: 'latest', // Specify 'stable' or a specific version number
});
```
### Options for version:
- **stable**: Loads the stable release of the Unlayer builder. This is the default option and is recommended for most production environments.
- **latest**: Loads the latest edge release, which includes new features, improvements, and bug fixes. This version may be less stable but includes the most up-to-date changes.
- **Specific Version Number**: You can lock the builder to a specific version by specifying a version number (e.g., 1.63.2). This is useful if you want to ensure that the builder doesn’t automatically update to a newer version, preventing potential breaking changes.
---
## Changelog
:::info Changelog
A versioned changelog is available here: [Changelog](/changelog)
:::
---
## Example Use Cases
### Production Environment
In a production environment, you may want to load the stable version to ensure that your users experience a reliable and consistent builder.
```javascript
unlayer.init({
version: 'stable', // Stable and reliable for production
});
```
### Development Environment
In a development or staging environment, you might use the latest release channel to test new features and improvements as they become available.
```javascript
unlayer.init({
version: 'latest', // Use the latest version for testing new features
});
```
### Version Locking
If your application relies on a specific version of the builder and you want to avoid any unexpected changes due to updates, you can lock the builder to a specific version number.
```javascript
unlayer.init({
version: '1.63.2', // Lock to a specific version
});
```
---
## Best Practices
- For production environments, we recommend using the **stable** release channel to minimize the risk of introducing bugs or instability due to frequent updates.
- Use the **latest** release channel in development environments to experiment with the newest features and provide feedback on upcoming changes.
- Lock the builder to a specific version if you require strict control over the features and stability of the editor in your application.
---
## Notes
- You can switch between release channels at any time by updating the version parameter in your initialization script.
- Version locking is ideal for applications where stability and predictability are critical, and you want to avoid the possibility of automatic updates affecting the end-user experience.
---
## Minimap
:::info Availability
The document minimap requires a plan that includes the Document Minimap feature.
:::
The minimap is a floating thumbnail navigator that mirrors the document's pages alongside the canvas. It docks opposite the tools panel — so it sits on the right when the tools panel is on the left, and vice versa — and follows the canvas as the layout adapts. It gives end-users a quick visual overview of multi-page documents and lets them jump between pages with a single click.
The minimap is only rendered when `displayMode` is `'document'` **and** the design spans two or more pages. Single-page documents don't need a navigator, so the panel stays hidden until the design overflows onto a second page; it'll appear and disappear automatically as the page count changes.
## Enable / Disable
The minimap is **enabled by default** in document mode. Set `features.minimap` to `false` on `unlayer.init` to hide it:
```javascript
unlayer.init({
displayMode: 'document',
features: {
minimap: false,
},
});
```
---
## Document Builder
The Document Builder allows developers to embed a powerful drag-and-drop editor into their web applications, enabling end-users to create and edit documents. The builder provides extensive tools and customization options for creating structured content such as reports, proposals, contracts, and more.
:::info Availability
The document minimap, page-format controls, and `documentOrientation` export override each require a plan that includes the corresponding feature. Projects without page-format controls use fixed A4 portrait pages in the editor. Integrations calling the deprecated Export API v2 continue using `pageSize` to select the exported paper size, as described in [Export PDF](../../get-started/export/export-pdf.md#page-format).
Repeated page headers and footers require a plan that includes both Header and Footer Support and repeated headers and footers in documents.
:::

---
# Integration
After [installing](../../get-started/installation.md) our JavaScript library, use the following code snippet to initiate the email editor. You have to pass `displayMode` as `document`, and replace your project id.
```javascript
unlayer.init({
id: 'editor-container',
displayMode: 'document',
projectId: 1234, // REPLACE
});
```
---
# Builder In Action
Once the document builder is initialized, it will look like this.
---
# Tools for Documents
The builder comes with the following tools out of the box.
- **Columns**: It allows your users to add columns to your design in order to have a better design arrangement.
- **Button**: Add any type of button in your email. You can change colors and styles.
- **Divider**: It gives your users appropriate spacing at any point they want in their design.
- **Heading**: Add headings (from level 1-6) to the design.
- **Image**: To make your emails attractive, you can add images using this tool.
- **Social**: It is a built-in tool that lets users add their social media icons to your design.
- **Text**: Text is a built-in tool so users can add text to their designs.
- **Page Break**: To create multi-page documents, users can use this tool, which adds a dark dotted line to represent the start of a new page. The forced boundary is preserved in exported document HTML and PDF exports, including server-side Cloud API exports.
The empty area of a newly created page accepts the Columns tool, so users can continue building directly on that page.
When two Page Breaks are consecutive, the later Page Break is highlighted on the canvas and listed in the Audit tab because consecutive Page Breaks may cause rendering issues in the exported PDF. The Preview button also shows a warning, and detection works when the Page Breaks are placed in separate rows.
Rows with multiple columns stay together when they fit on a page. If a content block, table row, or complete multi-column row is taller than the printable page area, the Audit tab warns that the block may be split during PDF export.
---
# Page Format
End-users can pick the paper size and orientation from the body's property panel and the editor's top toolbar, and set the page margin from the property panel. You can change the defaults, restrict the available choices, or hide the pickers entirely — see [Page Format](/builder/latest/document-builder/page-format).
---
# Minimap
A thumbnail minimap floats over the canvas and appears automatically as soon as a document spans two or more pages, letting end-users jump between pages with a single click. The panel docks opposite the tools panel, so it follows the editor's layout. It's enabled by default — see [Minimap](/builder/latest/document-builder/minimap) for the opt-out and behavior details.
---
# Exporting PDF
Once the document is ready to be exported, you can use the [Export PDF](../../get-started/export/export-pdf.md) method to export it into a PDF file.
The document preview includes a **Download PDF** button in its toolbar. It renders the same PDF as [Export PDF](../../get-started/export/export-pdf.md) with the preview's language and merge tag values, and downloads the file directly. Free plans don't include PDF export, so on a free plan the button saves the preview itself, which carries the Unlayer watermark, and doesn't run an export. On other plans without PDF export, the button isn't shown.
Document PDFs are rendered in the end-user's browser and don't count toward your export allowance. See [PDF Rendering](./pdf-rendering.md) for how fonts, images, custom tools and watermarks are drawn.
On plans that include Document Watermarks, you can stamp your own text watermark on previews and exports. On free plans, document PDFs and the editor canvas carry an Unlayer watermark on every page. See [Watermark](../../get-started/export/export-pdf.md#watermark).
---
## Page Format
:::info Availability
Page-format controls require a plan that includes Document Page Format Controls. Projects without this feature use fixed A4 portrait pages and don't show these controls. Their documents keep either the standard `'auto'` margin or no margin (`0`); non-default sizes, orientations, and custom margins supplied through editor configuration, `loadDesign`, or `setBodyValues` are normalized back to A4 portrait with the `'auto'` margin.
:::
The document builder lets end-users pick the paper size, orientation, and margin for their design. These properties live on the body and surface when `displayMode` is `'document'`:
- the body's property panel under **Document → Size / Orientation / Margin**, and
- the editor's top toolbar (the Size and Orientation dropdowns next to the device buttons).
The values flow through the design JSON as `body.values.documentSize`, `body.values.documentOrientation`, and `body.values.documentMargin`, and [Export PDF](../../get-started/export/export-pdf.md) reads them when rendering.
`documentMargin` defaults to `'auto'`, which uses the selected size's standard margin (48px for A5, 96px for every other size). Switch it to a pixel value, such as `'60px'`, to use the same margin on every side of the page in the editor, in PDF export, and in HTML export, where it insets the exported page body on screen. A margin can be at most 250px and never more than a quarter of the page's shorter side.
Documents saved before page-format settings were introduced have no saved `documentMargin`. They load and export with no page margin (`0`), as they did when they were created.
`documentSize` is the saved editor setting. To choose a paper size for one PDF export without changing the saved design, pass `pageSize` to `exportPdf`. See [Export PDF](../../get-started/export/export-pdf.md) for API availability.
You can customize both settings through the standard `tools.bodies.properties` configuration on `unlayer.init`, the same shape used for any other tool option. The body tool registers itself under the plural id `bodies` — `tools.body` (singular) is silently ignored.
## Changing the Default Values
Set `editor.defaultValue` to change what new documents start with. End-users can still change the value from the property panel and top toolbar.
```javascript
unlayer.init({
displayMode: 'document',
tools: {
bodies: {
properties: {
documentSize: {
editor: { defaultValue: 'Letter' },
},
documentOrientation: {
editor: { defaultValue: 'landscape' },
},
documentMargin: {
editor: { defaultValue: '72px' },
},
},
},
},
});
```
| Property | Type | Default |
| :-------------------- | :------------------------------------------------------------------- | :----------- |
| `documentSize` | `'A3'` \| `'A4'` \| `'A5'` \| `'Legal'` \| `'Letter'` \| `'Tabloid'` | `'A4'` |
| `documentOrientation` | `'portrait'` \| `'landscape'` | `'portrait'` |
| `documentMargin` | `'auto'` \| a pixel value such as `'72px'` | `'auto'` |
## Restricting Available Choices
For the size and orientation pickers, set `widgetParams.allowedValues` to limit which options end-users can choose from. Labels are still pulled from the built-in schema, so locale and translations keep working. Both the property panel and the top toolbar honor the same list.
```javascript
unlayer.init({
displayMode: 'document',
tools: {
bodies: {
properties: {
documentSize: {
editor: {
defaultValue: 'Letter',
widgetParams: { allowedValues: ['A4', 'Letter'] },
},
},
documentOrientation: {
editor: {
widgetParams: { allowedValues: ['portrait'] },
},
},
},
},
},
});
```
## Hiding the Pickers
Pass `widgetParams.allowedValues: []` to remove the picker from both the property panel and the top toolbar entirely. `editor.defaultValue` controls new documents and designs where the property is missing; it does not overwrite a value already stored in a loaded design.
```javascript
unlayer.init({
displayMode: 'document',
tools: {
bodies: {
properties: {
documentSize: {
editor: {
defaultValue: 'Letter',
widgetParams: { allowedValues: [] }, // hide picker; default new documents to Letter
},
},
documentOrientation: {
editor: {
defaultValue: 'portrait',
widgetParams: { allowedValues: [] }, // hide picker; default new documents to portrait
},
},
},
},
},
});
```
If you need to enforce one page format for existing designs as well, normalize the saved `body.values.documentSize` and `body.values.documentOrientation` before calling `loadDesign`, or call `setBodyValues` after loading. Hiding the controls only prevents end-users from changing the stored value in the editor UI.
:::info
These overrides set what end-users see in the editor. To render an existing design at a different page format from a single `exportPdf` call without changing the editor's defaults, use the per-call options described in [Export PDF → Page Format](../../get-started/export/export-pdf.md#page-format).
:::
---
## PDF Rendering
In the Document Builder (`displayMode: 'document'`), PDFs are rendered in the end-user's browser: [`exportPdf`](../../get-started/export/export-pdf.md), the document preview, and the preview's **Download PDF** button. The PDF uses the same exported HTML, fonts, merge tags and language as a server export, and the same page format and margins.
The preview renders on every plan. `exportPdf` and **Download PDF** need a plan that includes PDF export. Without it, `exportPdf` receives an `error` instead of a `url`. On a free plan, **Download PDF** then saves the preview, which carries the Unlayer watermark; on other plans without PDF export, it isn't shown.
Rendering in the browser means:
- **No export allowance.** PDFs the editor renders don't count toward your workspace's [export allowance](/server/cloud-api/export-allowances). The [Cloud API](/server/cloud-api) still renders PDFs on Unlayer's servers, and those count.
- **Same result for `exportPdf`.** The PDF is stored in your [File Storage](../../files-storage/file-storage/overview.md) like a server export, and the callback receives its `url`. In Unlayer's storage, a PDF rendered in the browser is deleted after 7 days, so save the file if you keep it longer (see [Export PDF](../../get-started/export/export-pdf.md)); in your own Amazon S3 bucket, it stays until you delete it, and so does every PDF Unlayer's servers render. Pass [`dataUrl: true`](../../get-started/export/export-pdf.md#data-url) to get the PDF itself instead, without uploading it. A PDF over 25 MB, one over the limit on uploads from one network, one the storage can't take at that moment (the upload takes over 2 minutes or fails on Unlayer's side), or a document too large for the browser renderer (hundreds of dense pages) is rendered and stored by Unlayer's servers instead, like a server export, and counts toward your export allowance. **Download PDF** of a document too large for the browser renderer also comes from Unlayer's servers. In offline mode (the `offline: true` init option, used with an offline license and locally bundled assets), nothing is uploaded: `url` is a `data:` URL of the PDF and the result includes `offline: true`.
- **Fewer round trips.** The preview and **Download PDF** don't wait on the export service.
- **Files loaded ahead.** Once the design hasn't changed for a couple of seconds, the editor reads its fonts and the images it can read directly, so the first PDF waits less for them. The browser keeps them for as long as their servers allow, as it does any file. Your `fetchImage` callback and the image proxy are never called ahead: what only they can read loads when a PDF is built. **Download PDF** saves the PDF the preview shows when nothing changed since the preview built it and all its fonts, images and effects loaded. A document whose custom tools or HTML blocks run scripts, link or import a stylesheet of their own, frame another page, or use an SVG sprite sheet from another file is built again, since those can give something else each time.
## What the browser draws
A background image repeated in more than a million tiles, such as a dot smaller than a pixel across a page, is drawn once, and may look slightly different from the editor. The browser console says so.
CSS effects that PDF boxes can't hold, such as blur, drop-shadow and SVG filters on a box, masks, clip-paths, 3D transforms and vertical text, are drawn as images the browser paints, as Chrome prints filters, and so are boxes inside a line of text that hold blocks or are transformed. Their text is written over the image, word by word where the image shows it, so it can still be found, selected and copied. Color filters such as grayscale and sepia, flat transforms, rounded clips and blend modes are drawn as they are.
A block taller than a page breaks across pages as when a browser prints the document: boxes side by side, such as a row's columns or a table's cells, break each on its own lines, CSS columns fill each page's columns in turn, and a table repeats its header and footer on each page, when each is at most a quarter of the page's height for content.
The browser renderer's own failures don't go to Unlayer's servers: when its code can't be downloaded, it fails on a document, or it takes over 2 minutes, `exportPdf` receives an `error` instead of a `url`, and the preview and **Download PDF** show it.
A browser can't measure a page it isn't laying out, which is what Chrome does for an editor hidden with `display: none`, such as one in a closed tab or panel, including one hidden while a PDF is being built. Unlayer's servers then render the PDF, and it counts toward your export allowance. An editor hidden any other way, for example with `visibility: hidden` or moved off-screen, still renders in the browser. Offline or with `dataUrl`, where nothing may be uploaded, `exportPdf` receives an `error` instead: show the editor and try again.
In offline mode, an image the browser can't load stops the PDF: the `exportPdf` callback receives an `error` instead of a `url`, and the preview and **Download PDF** show the reason; see [Images](#images).
On a free plan, every page carries the Unlayer [watermark](../../get-started/export/export-pdf.md#watermark). The browser draws it on the preview, **Download PDF** and `dataUrl` PDFs, as Unlayer's servers stamp it. When a free plan includes PDF export, `exportPdf` without `dataUrl` is rendered on Unlayer's servers, which stamp the watermark, and counts toward your export allowance. On plans that include Document Watermarks, a custom watermark, passed to the call or set as the `features.watermark` default, is drawn in the browser, exactly where and how the servers would stamp it.
The plan decides the watermark, so the editor creates document PDFs only once it has loaded your plan. A PDF asked for while the project loads waits for it, up to 15 seconds. If the plan can't be loaded, for example because the editor couldn't start its session or runs offline without a license, `exportPdf` receives an `error` instead of a `url`, and the preview and **Download PDF** show it. If `unlayer.loadProject` fails afterwards, PDFs keep using the plan of the project the editor started with.
## Fonts
The PDF uses the document's web fonts, including your custom fonts. Serve a custom font's files with [CORS](https://developer.mozilla.org/docs/Web/HTTP/CORS) headers, as browsers require for web fonts. Its stylesheet doesn't need them: when the editor can't read it directly, it reads it through Unlayer's image proxy (not in offline mode). A font the editor can't read is replaced by the next font in its list. Every list ends with an open fallback font; if it can't be loaded either, the PDF's text can't be drawn, so Unlayer's servers render the PDF instead, and it counts toward your export allowance. Offline or with `dataUrl`, `exportPdf` receives an `error` instead.
System fonts can't be downloaded by the browser, so the PDF draws them with openly licensed fonts:
- Arial, Helvetica, Times New Roman, Courier New, Andale Mono, Georgia, Arial Black and Comic Sans MS are drawn with fonts whose letters have the same widths, so text wraps as in the editor. A few characters of the last three differ in width, such as fractions, some accented capitals in Georgia and the non-breaking space in Comic Sans MS, and text holding one can wrap differently.
- Impact is drawn with a close equivalent, and Verdana, Tahoma, Trebuchet MS, Book Antiqua, Symbol and Terminal with a similar sans-serif, serif or monospace font. Their text can wrap differently than in the editor.
To print one of those exactly, add your licensed copy of the font as a custom font.
Text in scripts whose letters join, stack or reorder, such as Arabic, Urdu, Hebrew, the Indic scripts, Thai, Lao, Khmer, Myanmar and Tibetan, is shaped by HarfBuzz, the engine browsers use, so it looks and wraps as in the editor. The editor loads it (about 170 KB) only for a document with such text. If it can't, for example because the download fails, that text is still drawn and the browser console says so, but some letter clusters can differ from the editor.
The renderer runs WebAssembly, which it also loads fonts with. If a Content Security Policy applies to the page that runs the editor, its `script-src` must allow `'wasm-unsafe-eval'`. Without it, the fonts can't be loaded, so Unlayer's servers render every PDF, and they count toward your export allowance; offline or with `dataUrl`, `exportPdf` receives an `error` instead of a `url`.
When a font has no bold or italic file, the PDF fakes the bold or slants the text, as browsers do.
Characters none of the document's fonts has, such as emoji and some symbols, are drawn as small images, in the fonts the browser shows them in on screen. They can still be selected, searched and copied as text.
## Custom tools
Custom tools render in the browser from the HTML their exporter returns, like the built-in tools:
- **Shadows.** Box shadows and text shadows are drawn. PDF text can't be blurred, so a blurred text shadow is drawn sharp and lighter.
- **Form controls and embedded content.** Fields, buttons, drop-down lists, checkboxes, radio buttons, sliders, progress bars and meters are drawn as Chrome prints them. A video shows its `poster` image. A frame shows the page written into it, with `srcdoc` or by a script. A frame of another site, which browsers don't let a page read, an `` or `` that isn't an image, and an empty `` keep an empty box their size.
- **Scripts.** Scripts in the exported HTML run before the PDF is drawn, as they do on Unlayer's servers. They run in an isolated frame, with no access to the editor, its storage or the end-user's session, until the page stops changing and has no request, timer, interval or animation frame left to wait for, for up to 5 seconds. They get storage and cookies of their own, kept only while they run. The PDF shows the page they leave, with what they typed, ticked or chose in form fields, even if a script fails or is still working after 5 seconds, and anything they drew on a `` becomes an image. If the editor's page doesn't allow inline scripts in frames, for example because of a Content Security Policy, the PDF shows the page without running them. The browser console and the `warnings` of the `exportPdf` result say what went wrong. A script that never returns, such as an endless loop, freezes the page it runs in, as it does on the canvas: the browser can't stop it.
## Images
The browser loads each image directly when its host sends [CORS](https://developer.mozilla.org/docs/Web/HTTP/CORS) headers. When it can't, it asks your `fetchImage` callback, if you registered one, and then Unlayer's image proxy (not in offline mode). An image none of them can load is left empty, as on the canvas when its own server refuses it (for example with a `404`), and the browser console and the `warnings` of the `exportPdf` result say so. An image whose host doesn't answer has no size the PDF could keep for it: it's read the same ways, and when none of them loads it, it's left out, and the `warnings` say so.
Register `fetchImage` to load images from hosts without CORS headers through your own backend. The callback receives the image's URL and calls `done` with the image as a `Blob`, or with an `error`, including when your backend answers with an error status, so the editor goes on to the image proxy:
```javascript
unlayer.registerCallback('fetchImage', function (data, done) {
fetch('/my-image-proxy?url=' + encodeURIComponent(data.url))
.then((response) => {
if (!response.ok)
throw new Error('Image request failed: ' + response.status);
return response.blob();
})
.then((blob) => done({ blob }))
.catch((error) => done({ error }));
});
```
Each step has a time limit: 20 seconds to load directly, 20 seconds for `fetchImage` to call `done`, and 25 seconds through the image proxy. Images over 25 MB are redrawn smaller to fit, and images over 100 MB are left empty.
In offline mode, there's no image proxy and no server to fall back to: an image the browser can't read, directly or through `fetchImage`, stops the PDF, and `exportPdf` returns an `error` that says so. An image its own server refuses is still left empty. Register `fetchImage`, or serve your images with CORS headers.
---
## Quickstart
# Document Builder Quickstart
This guide walks you through embedding Unlayer's drag-and-drop document builder into your web application. The document builder lets your users create reports, proposals, contracts, and other structured documents.
---
## Step 1: Install the SDK
Add the script tag to your HTML:
```html
```
```bash
npm install react-email-editor
```
```bash
npm install angular-email-editor
```
```bash
npm install vue-email-editor
```
---
## Step 2: Initialize the Editor
Set `displayMode` to `document` to load the document builder.
:::info Recommended Size
For the best experience, ensure the editor container is at least **1024px** wide and **700px** high. The editor will expand to fill the entire container.
:::
```html
```
```jsx
function App() {
const emailEditorRef = useRef(null);
const onReady = () => {
console.log('Editor is ready');
};
return (
);
}
export default App;
```
**app.module.ts**
```typescript
@NgModule({
imports: [ EmailEditorModule ],
})
```
**app.component.ts**
```typescript
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
})
export class AppComponent {
@ViewChild(EmailEditorComponent)
private emailEditor: EmailEditorComponent;
options = {
displayMode: 'document',
projectId: 1234, // Replace with your project ID
};
editorLoaded() {
console.log('Editor is ready');
}
exportHtml() {
this.emailEditor.editor.exportHtml((data) =>
console.log('exportHtml', data),
);
}
}
```
**app.component.html**
```html
Export
```
```html
```
### Where to get the Project ID?
1. Log in to the **[Developer Console](https://console.unlayer.com/)**
2. Create a **Project**
3. You can find the project ID in **Project > Builder > Settings**
---
## What's Next
- [Load & Save Designs](/builder/load-and-save-designs) — Load templates and persist user work.
- [Export Designs](/builder/export-designs) — Export as HTML, PDF, images, and more.
- [Deploy to Production](/builder/installation#step-4-deploy-to-production) — Set up allowed domains and go live.
---
## @unlayer/pdf
`@unlayer/pdf` renders a document to a PDF in your own code, in Node or in a browser, with no Unlayer editor on the page and no browser on the server. You describe the document as JSON, the **PDF spec**, and the package lays it out, splits it into pages and returns the PDF. It's the same engine the Document Builder [renders PDFs](./pdf-rendering.md) with.
Use it when your code or an AI agent writes the document. Rendering with it doesn't call Unlayer's export service, so it doesn't count toward your [export allowance](/server/cloud-api/export-allowances).
```sh
npm install @unlayer/pdf
```
## Render a PDF in Node
```ts
nodeFontEnvironment,
nodeGlyphEnvironment,
nodeImageEnvironment,
} from '@unlayer/pdf/node';
const spec = {
version: 1,
page: {
width: 595.28,
height: 841.89,
margins: { top: 48, right: 48, bottom: 48, left: 48 },
},
flow: [
{
type: 'text',
unit: { key: 'title', kind: 'content' },
style: { fontFamily: 'Arial', fontSize: 24, fontWeight: 700 },
children: ['Invoice 1042'],
},
{
type: 'text',
unit: { key: 'total', kind: 'content' },
style: { fontFamily: 'Arial', fontSize: 12, marginTop: 12 },
children: ['Total due: $240.00'],
},
],
};
const session = createPdfSession({
fonts: nodeFontEnvironment(),
images: nodeImageEnvironment(),
glyphs: nodeGlyphEnvironment(),
});
const { pdf, pageCount, warnings } = await renderPdf(spec, session);
await writeFile('invoice.pdf', pdf);
```
The session keeps the fonts and images it loads, up to the [limits](#limits), so reuse it across renders. Two documents rendered with one session can give the same family name to different font files, and each draws in its own. Pass your web fonts to `renderPdf` to use them in the spec:
```ts
await renderPdf(spec, session, {
fonts: [
{
label: 'Montserrat',
value: "'Montserrat',sans-serif",
url: 'https://fonts.googleapis.com/css?family=Montserrat:400,700',
},
],
});
```
When documents come from untrusted callers, pass your own `fetchText`, `fetchBytes` and `fetchImage` to the environments, because the defaults fetch any URL a document names.
## Render a PDF in a browser
```ts
browserFontEnvironment,
browserGlyphEnvironment,
browserImageEnvironment,
} from '@unlayer/pdf/browser';
// Your bundler's asset URL syntax.
const session = createPdfSession({
fonts: browserFontEnvironment({ harfbuzzUrl, harfbuzzSubsetUrl }),
images: browserImageEnvironment(),
glyphs: browserGlyphEnvironment(),
});
const { pdf } = await renderPdf(spec, session);
```
Images need CORS headers, or a `fetchImage` override on the image environment that loads them through your own proxy. Fonts need CORS headers too, or `fetchText` and `fetchBytes` overrides on the font environment. Under a Content Security Policy, `script-src` must allow `'wasm-unsafe-eval'`.
## The result
| Field | Description |
| :----------- | :------------------------------------------------------------------------- |
| `pdf` | The PDF, as a `Uint8Array` |
| `pageCount` | How many pages it has |
| `warnings` | What the PDF changes or leaves out, as codes |
| `units` | Each block of the flow, with the page it starts on and the height it takes |
| `bodyHeight` | The height the flow has on each page, in points |
`renderPdf` throws when the spec is invalid or past a [limit](#limits) (`InvalidPdfSpecError`), when the margins, header and footer leave no room for the page body, or when the fallback font, Arimo, can't be loaded. Anything else is drawn as closely as the engine can, and `warnings` lists it:
| Code | What happened |
| :----------------- | :---------------------------------------------------------------------------------------------------- |
| `missingGlyphs` | Characters no font can draw were left out |
| `glyphFailed` | Characters the environment failed to draw as images were left out; a later render tries again |
| `imageFailed` | Images that failed to load keep an empty box |
| `imageUnsupported` | Images this environment cannot load, decode or convert, or past a [limit](#limits), keep an empty box |
| `imageUnfiltered` | Images whose filter cannot be drawn were drawn without it |
| `fontFallback` | Fonts that are not available were drawn with the next font of their stack |
| `shapingFallback` | HarfBuzz could not be loaded, so text in complex scripts was shaped without it |
| `duplicateUnitKey` | Repeated unit keys were renamed |
| `oversizedUnit` | A unit taller than a page continues across pages |
| `splitLines` | Page cuts through a unit taller than a page go through lines of text |
In a browser, text in complex scripts drawn without `harfbuzzUrl` isn't listed, and some of its letter clusters can differ from a browser's.
## Limits
A spec past one of these limits is refused with `InvalidPdfSpecError`. Each entry of its `issues` gives the `path` of what goes past the limit and a `message`, and the limits that a well-formed document can reach also give a `code`:
| Limit | Value | `code` |
| :------------------------------------------------- | :-------------------------------------------------------------------------- | :----------------- |
| A length, offset or font size | 1,000,000 points | |
| A `transform` | 1,000 characters | |
| A color | 100 characters | |
| Each value of a length or position | 32 characters, its unit included | |
| Boxes and spans inside each other | 200 levels | `nestedTooDeep` |
| Pages | 10,000 | `tooManyPages` |
| Size of a document | 2,000,000 characters, each node counting as 20 and each line break as 5 | `documentTooLarge` |
| Header, footer and `fixed` nodes | Count towards that size once per page, as each page lays them out | `documentTooLarge` |
| A unit taller than a page that holds a page number | 50,000,000 characters: its size times its pages | `documentTooLarge` |
| Links and image text | 50,000,000 characters written, counted each time a line or page writes them | `documentTooLarge` |
Any other string in a spec, such as a link, a style value or the title, counts towards the size only past its first 1,000 characters, so ordinary values add nothing. Image sources don't count: they have the byte limits below.
`isDocumentTooLarge(error)` is true for `documentTooLarge` and `tooManyPages`, so you can tell a document too large for this engine from a spec that's wrong:
```ts
try {
const { pdf } = await renderPdf(spec, session);
} catch (error) {
if (!isDocumentTooLarge(error)) throw error;
// Too large for this engine: split the document, or render it another way.
}
```
A document past the size limit is refused before anything loads. Pages and what gets written are only known once its fonts and images have loaded and it has been measured, so `tooManyPages` and the limit on written text come after that work.
An image past a limit keeps an empty box and is reported as `imageUnsupported`, and the download stops at the limit. Set these on the image environment:
| Option | What it limits | Default |
| :---------------------- | :------------------------------------------------------------ | :------ |
| `timeoutMs` | Downloading and converting one image | 15 s |
| `maxImageBytes` | One image file | 100 MiB |
| `maxDocumentImageBytes` | What one document reads of its images, embedded ones included | 1 GiB |
| `maxCacheBytes` | What a session keeps of images | 256 MiB |
Once a document has downloaded `maxDocumentImageBytes`, every image still downloading keeps an empty box too. A `fetchImage` of your own gets `signal`, which aborts at the timeout, `maxBytes` and `reserveBytes` as its second argument. Call `reserveBytes(bytes)` with each chunk's size as it arrives: when it returns `false`, the document is past its limit, so stop reading and reject. All three are optional, since the limits also hold on what `fetchImage` returns: an image over `maxImageBytes`, or past what the document may read, isn't drawn.
A font environment stops at 100 MiB for a font file and 10 MiB for a stylesheet, and its `maxCacheBytes` (256 MiB by default) limits what a session keeps of fonts. What a session has let go of, the ones used longest ago first, it loads again when a document needs it.
To hear each time that happens, pass `onCacheDrop` to `createPdfSession`. It's called for every image, font stylesheet, font file or character drawn as an image (an emoji, a symbol) the session lets go of, and an error it throws is ignored. If you keep PDFs to show again instead of rendering the same document twice, render again after a drop: the file is downloaded again, and it may have changed at its URL.
## Let an AI agent write the document
Give the agent one tool whose input schema is `pdfSpecJsonSchema()`, and put `pdfSpecInstructions()` in its system prompt with the font stacks you render with. The schema describes every field, and the instructions explain how pages, units, tables, fonts and images work together. Check each spec the agent writes, and send the problems back until it's valid:
```ts
pdfSpecInstructions,
pdfSpecJsonSchema,
validatePdfSpec,
} from '@unlayer/pdf';
const system = `${pdfSpecInstructions()}
Font stacks you can use: 'Lato',sans-serif (400 and 700, upright and italic)`;
const inputSchema = pdfSpecJsonSchema();
// For each spec the agent writes with its tool:
const { spec, issues } = validatePdfSpec(toolInput);
// No spec: return `issues` (each with a path and a message) as the tool's error.
// A spec: render it with renderPdf.
```
The [package README](https://www.npmjs.com/package/@unlayer/pdf) has the rest: fallback fonts for other scripts and emoji in Node, image formats and their limits, and `debug: true`, which draws each node's boxes over the PDF.
---
## Inbox Previews
Inbox Previews show your users how an email renders in real email clients before they send it. In
the editor, open **Preview → Inbox** and select **Generate Previews**. Each email client in a run
costs one credit.
:::info Using an editor version before 1.479.0?
Those editors keep the previous Inbox Previews experience until **September 7, 2026 (00:00 UTC)**:
the account's default email clients and one credit per run. On that date they switch to the
experience described here on their own, with no version change on your side. Previews generated
before the switch stay available.
:::
## Choose the default email clients
In [Console](https://console.unlayer.com), open the project and go to **Builder Settings → Inbox
Previews**. Pick the email clients your users start with and the region where previews are
processed. Filters show how many clients are selected per platform, for example **15/104**.
These are project defaults. Any editor can override them with init config. Before a run and beside
its results, the Inbox panel shows how many clients the next run previews, for example **This run:
6 devices**; editors opened from Console also get a **Manage email clients** link there. Embedded
editors never show the link.
## Override the project defaults
Use `features.inboxPreviews` to give one editor its own clients or region:
```javascript
unlayer.init({
id: 'editor-container',
displayMode: 'email',
projectId: 1234,
features: {
inboxPreviews: {
enabled: true,
clients: [
'gmailcom-lm_chrcurrent_win10',
'iphone16gmail_26',
'outlook19',
],
dataRegion: 'eu',
usageTemplateId: 456,
},
},
});
```
- `clients` replaces the Console selection for this editor. The whole list runs or the request is
rejected; no client is silently dropped. Omit it to keep the project default.
- `dataRegion` is `us` or `eu`. Omit it to keep the project default.
- `usageTemplateId` tags this editor's runs with a template ID in the usage report. It doesn't load
anything.
- `inboxPreviews: true` keeps the project defaults; `inboxPreviews: false` hides the feature.
Email client IDs come from the [Inbox Previews API](/server/cloud-api/inbox-previews), which also
lets you change the project defaults from your backend.
## Usage {#credits}
Every email client in a run costs one credit. Three clients, three credits.
With credit enforcement on, the editor shows your balance and, when known, the cost before
generating. Saved email clients are checked against the current catalog, so the run cost may be
unavailable until generation. A remaining balance can still be too small for the full selection;
the editor keeps that balance visible when a run is blocked. It never runs a partial selection.
- Retrying a failed preview is free.
- **Generate new previews** starts a new paid run.
- At zero balance, the Inbox tab turns read-only and, in Console, links to the next step: claim
the trial, buy credits, or upgrade the plan.
### Get credits
Inbox Previews is available on the Scale, Optimize, and Enterprise plans. No plan includes credits,
so buy Inbox Previews Credits packs on the **Billing** page in [Console](https://console.unlayer.com).
To try the feature first, claim the one-time trial on the same page: 40 credits, enough for six runs
across six email clients. Anyone in the workspace can claim it, once per workspace. Trial credits
expire when your monthly usage resets. If you claim them in the last week before a reset, they last
until the reset after that instead. Trial credits are used before your pack credits, and the claim
card shows the expiry date before you claim.
### See your usage in Console
Open the project's **Usage** page in [Console](https://console.unlayer.com). It lists every
generation and its credits, with breakdowns by email client and by end user, and a CSV export.
The daily chart starts with **All**, showing per-device credits, per-generation credits, and
generations as separate bars. Select one metric to focus on it; its color stays the same. Gray bars
compare the selected metric with the preceding period of the same number of completed UTC days. Hover
over a day for exact counts, followed by the previous period and the change. Today is partial and is
excluded from comparisons; unknown historical credit details are not treated as zero.
Click a generation's client count to see which clients were in the run and which ones your users
actually looked at. Viewed clients come first with an eye icon; a crossed eye means nobody opened
that one. A click marker means someone picked that thumbnail on purpose, a skip marker means they
reached it by navigating the gallery, and no marker means the editor showed it by default.
Long runs are searchable.
To attribute usage to your users, pass a stable `user.id` in
[`unlayer.init`](/builder/end-user-identification).
### Know what your users look at
The editor fires `inbox-previews:viewed` whenever a generated screenshot is shown to the user.
```javascript
unlayer.addEventListener('inbox-previews:viewed', function (data) {
console.info(data.clientId, data.viewSource); // 'outlook19', 'gallery_click'
});
```
| Field | What it is |
| -------------- | ----------------------------------------------------------------------------- |
| `runId` | Shared by every screenshot of the same run |
| `clientId` | Email client ID, plus `displayName`, `category`, `browser`, `operatingSystem` |
| `viewSource` | `automatic`, `gallery_click`, or `navigation` |
| `autoSelected` | `true` when the editor picked the screenshot itself |
| `endUserId` | The `user.id` from `unlayer.init`, or `null` |
A client fires once per view source, so count unique `runId` and `clientId` pairs. The screenshot
and the email HTML are never included.
### Good to know
- Paid plans allow up to 20 email clients in one run, Free plans up to three when Inbox Previews is
enabled. Customer Success can set an account-specific exception, never above 20. A selection over
the limit is rejected before anything is generated.
- Extra credit packs need a current paid plan that includes Inbox Previews. If a plan change removes
the feature, pack credits wait until it comes back.
- If the preview service doesn't confirm a generation, no previews come back and the reserved
credits return to your allowance. Wait a few minutes before starting another run.
- View data exists only for recent editor versions. Older generations show views as unavailable,
not zero. Views are analytics, not billing records.
- The CSV adds `viewed_email_client_ids`, `automatically_viewed_email_client_ids`,
`interactively_viewed_email_client_ids`, `click_viewed_email_client_ids`,
`navigation_viewed_email_client_ids`, and `view_tracking_available`.
- Retrying a failed preview doesn't cost credits, since that client was already paid for in the
run. It does render again on our side, so retries count toward the project's monthly safety
allowance.
- End-user attribution is kept for 13 months. Remove one user's attribution earlier through the
[Inbox Previews API](/server/cloud-api/inbox-previews#remove-end-user-attribution).
- Email HTML is never stored in the usage report or shared with provider support.
## Limits
Each project has short request limits and a monthly safety allowance for device renders. When a
limit is reached, the editor says which one and what to do: wait, reduce the selection, upgrade, or
ask your account administrator to contact Customer Success.
Blocked requests are stopped before anything is generated, so they use neither credits nor renders.
When the service knows when a limit resets, the response carries a `Retry-After` header.
---
## Email Builder
With Unlayer’s email builder, your users don't have to spend hours in a designer's office creating emails. They can just drag and drop! Once the email is designed, your users can use your application to send it to their audiences.
Our email builder gives you full control over the email design. It lets you customize every aspect of the email, from the layout to the content and images. Your users can use images, merge tags, and other elements to customize their email. They can also preview the email before sending, and export the HTML code for further editing.

You can explore our [full template library](https://unlayer.com/templates).
## Why Use Email Builders?
With a drag-n-drop email builder, users can create and select multiple email templates, change the content, include pictures, and link to files. Furthermore, they can name the template and change its structure and styling. Once your users select a template, they can customize the content by editing it in the editor. Rich template selection in email builders allows customizing the email to suit the audience and branding.
Our email builder also **improves deliverability** and ensures that the email looks great in all **email clients**, especially older ones such as Outlook.
## Integration
After [installing](../../get-started/installation.md) our JavaScript library, use the following code snippet to initiate the email editor. You have to pass `displayMode` as `email`, and replace your project id.
```javascript
unlayer.init({
id: 'editor-container',
displayMode: 'email',
projectId: 1234, // REPLACE
});
```
## Builder In Action
Once the builder is initialized, it will look like this (the screenshot follows your light / dark mode preference):
## Tools for Email
The builder comes with the following tools out of the box:
- **Columns:** It allows your users to add columns to your design in order to have a better design arrangement.
- **Button:** Add any type of button in your email. You can change colors and styles.
- **Divider:** It gives your users appropriate spacing at any point they want in their design.
- **Heading:** Add headings (from level 1-6) to the design.
- **HTML:** This tool will give your users room to add custom HTML to the design.
- **Image:** To make your emails attractive, you can add images using this tool.
- **Menu:** Menu is a built-in tool used to create navigation menus.
- **Social:** It is a built-in tool that lets users add their social media icons to your design.
- **Text:** Text is a built-in tool so users can add text to their designs.
- **Timer:** Timer is used to create countdown timers. This tool creates a countdown GIF image to run a real time countdown.
- **Video:** It lets users add YouTube or Vimeo videos to their designs. This tool automatically generates thumbnails of videos for emails and ensures that it renders correctly on all platforms.
You can create [custom tools](../../tools/custom-tools/overview.md) to extend the functionality.
## Email Client Limits
Email clients don't all support the same styles. Use [Inbox Previews](inbox-previews.md) to check a design in the clients your users care about.
- **Letter spacing:** Some versions of Outlook for Windows, including recent Outlook for Microsoft 365 builds, ignore letter spacing, so the text shows with normal spacing there. Most other email clients apply it. When letter spacing is set in an email design, the builder shows a note under the Letter Spacing property.
---
## Quickstart(Email-builder)
# Email Builder Quickstart
This guide walks you through embedding Unlayer's drag-and-drop email builder into your web application — from installation to saving the finished design.
---
## Step 1: Install the SDK
Add the script tag to your HTML:
```html
```
```bash
npm install react-email-editor
```
```bash
npm install angular-email-editor
```
```bash
npm install vue-email-editor
```
---
## Step 2: Initialize the Editor
:::info Recommended Size
For the best experience, ensure the editor container is at least **1024px** wide and **700px** high. The editor will expand to fill the entire container.
:::
```html
```
```jsx
function App() {
const emailEditorRef = useRef(null);
const onReady = () => {
console.log('Editor is ready');
};
return (
);
}
export default App;
```
**app.module.ts**
```typescript
@NgModule({
imports: [ EmailEditorModule ],
})
```
**app.component.ts**
```typescript
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
})
export class AppComponent {
@ViewChild(EmailEditorComponent)
private emailEditor: EmailEditorComponent;
options = {
displayMode: 'email',
projectId: 1234, // Replace with your project ID
};
editorLoaded() {
console.log('Editor is ready');
}
exportHtml() {
this.emailEditor.editor.exportHtml((data) =>
console.log('exportHtml', data),
);
}
}
```
**app.component.html**
```html
Export
```
```html
```
### Where to get the Project ID?
1. Log in to the **[Developer Console](https://console.unlayer.com/)**
2. Create a **Project**
3. You can find the project ID in **Project > Builder > Settings**
---
## What's Next
- [Load & Save Designs](/builder/load-and-save-designs) — Load templates and persist user work.
- [Export Designs](/builder/export-designs) — Export as HTML, PDF, images, and more.
- [Deploy to Production](/builder/installation#step-4-deploy-to-production) — Set up allowed domains and go live.
---
## Test Email
The Unlayer Email Builder offers a feature that allows end-users to send a test email directly from the preview mode. This can be useful for testing the email design without having to export the content first. To enable the “Send Email” button in preview mode, the following steps must be followed:
---
## How to Enable?
To enable this feature, make sure the following steps have been taken.
### 1. Email Mode
This feature is only available when the builder is running in email mode. Ensure that the builder is properly configured with `displayMode` set to `email`.
### 2. Identify the User
For security and functionality purposes, the end-user must be identified with a valid email address. You can pass the email address of the end-user using the email property during the builder’s initialization. This helps identify the user for sending the email. This is the email address that the email will be sent at.
```javascript
unlayer.init({
user: {
id: 1,
signature: 'XXX',
name: 'John Doe', // optional
email: 'john.doe@acme.com',
},
});
```
### 3. Setup Identity Verification
Ensure that identity verification is enabled for the end-user. Identity verification helps to securely handle the user’s email address and prevent impersonation. [Learn More](../../advanced-configuration/security-settings.md)
A signed [`featurePolicyToken`](../../advanced-configuration/security-settings.md#restricting-features-per-end-user) verifies the end-user the same way as `signature`, and can also deny `sendTestEmail` for that end-user. Pass `featurePolicyToken` instead of `signature` if your project requires end-user feature policies — a `signature` alone is then rejected.
### 4. Enable Feature
You can enable the feature by passing the following feature flag to `unlayer.init`.
```javascript
unlayer.init({
features: {
sendTestEmail: true,
},
});
```
---
## AI Assistant
The AI Assistant adds a chat panel to the Image Editor where users describe the edit they want in plain language — "remove the background", "increase brightness", "make it look vintage" — and the editor applies it to the image. The panel also offers one-click suggestions for common edits.
AI edits participate in the same undo/redo history as manual edits, so users can freely combine both. Each request edits the current image, including any overlaid layers. To search for stock photos, generate a new image, or upload several references in one conversation, use the [builder AI Assistant](/ai/assistant/how-it-works/image).
## Enabling the AI Assistant
Enable the assistant through the `features.ai` flag:
```javascript
window.ImageEditor.createEditor({
container: '#editor-container',
image: imageUrl,
projectId: 1234, // Required for AI features
features: {
ai: {
enabled: true,
assistant: true,
},
},
});
```
The Image Editor requires AI Assistant access on your project. It stays hidden when
`features.ai.assistant` or the legacy `features.ai.magicImage` switch is `false`, or when the
end-user's [signed feature policy](/builder/latest/security#restricting-features-per-end-user)
denies `ai.assistant` or `ai.magicImage`. Inside the Email Builder, the Image Editor inherits
the builder's feature configuration and authenticated session.
:::info Project ID Required
AI features require a `projectId`, AI Assistant access on the project, and available credits. Legacy Magic Image access alone no longer enables AI editing in the Image Editor. Feature flags cannot grant access that the plan does not include. Manual editing remains available without AI access.
:::
## Attributing AI usage to an end user
A standalone Image Editor created with `window.ImageEditor.createEditor()` authenticates separately
from the Email Builder. Pass a `user` so its AI usage can be attributed to the person who made it:
```javascript
window.ImageEditor.createEditor({
container: '#editor-container',
image: imageUrl,
projectId: 1234,
user: { id: 'user_123' }, // Add `signature` or `featurePolicyToken` if identity verification is on
features: { ai: { enabled: true, assistant: true } },
});
```
Without `user`, standalone Image Editor usage is still billed to your project but is reported with
`end_user_id: null` in the [AI Credits usage API](/server/cloud-api/ai-credits) — under the
`image_edit` feature type for edits, and `image_generation` for anything that creates a new image.
The Image Editor opened from the Email Builder inherits the parent editor's authenticated session and
end-user attribution, so it does not need separate user configuration.
AI edits without a `user.id` are deprecated, both standalone and when the Email Builder has no
`user.id`. A future version will hide them, the same way the builder's AI Assistant already works,
and the editor logs a console warning until then. Pass `user` to keep them.
See **[End-User Identification](/builder/end-user-identification)** for the `user` fields and
how to sign the id when identity verification is enabled.
## Image model and availability
The standalone chat supports `features.ai.image.model` and `features.ai.image.quality`. For example:
```javascript
window.ImageEditor.createEditor({
container: '#editor-container',
image: imageUrl,
projectId: 1234,
user: { id: 'user_123' },
features: {
ai: {
enabled: true,
assistant: true,
image: { model: 'openai', quality: 'medium' },
},
},
});
```
Omit `model` and `quality` to use the server defaults. Use `features.ai.assistant: false` or `features.ai: false` to disable the standalone chat. The builder Assistant's granular image controls (`enabled`, `upload`, `generation`, `editing`, `search`, `enableDesignImageTargeting`, and `altText` inside `features.ai.image`) do not control this separate chat. It does not currently forward `fallbackModels`.
## Panel State
When the AI Assistant is available, its panel starts open by default. Set `aiAssistantOpenState` to `'closed'` if you want users to open it themselves from the tool rail:
```javascript
window.ImageEditor.createEditor({
container: '#editor-container',
image: imageUrl,
projectId: 1234,
features: { ai: { enabled: true, assistant: true } },
aiAssistantOpenState: 'closed', // 'open' (default) or 'closed'
});
```
## Default Prompt
You can pre-fill the chat input with a prompt — useful when your application already knows what the user wants to do (for example, a "Remove background" button that opens the editor):
```javascript
window.ImageEditor.createEditor({
container: '#editor-container',
image: imageUrl,
projectId: 1234,
features: { ai: { enabled: true, assistant: true } },
aiAssistantOpenState: 'open',
defaultPrompt: 'Remove the background',
autoSubmitPrompt: true, // Submit immediately instead of just pre-filling
});
```
With `autoSubmitPrompt: false` (the default), the prompt is pre-filled and the user submits it themselves.
:::info
Auto-submit only happens when the panel is open — `autoSubmitPrompt: true` requires `aiAssistantOpenState: 'open'`. With the panel closed, the prompt is only pre-filled.
:::
## Customizing the Assistant's Strings
All AI Assistant copy — the panel title, input placeholder, progress messages, and the built-in suggestions — can be translated or overridden through the `translations` option using the `image_editor.ai_assistant.*` keys. See [Configuration → Custom Translations](./configuration.md#custom-translations) and the [Translation Reference](../../advanced-configuration/localization.md#translation-reference).
---
## API Reference
## Loader API
The embed script (`https://cdn.unlayer.com/image-editor/embed.js`) is a lightweight loader. It exposes `window.ImageEditor` and only downloads the full editor when first used.
| Member | Description |
| :---------------------- | :-------------------------------------------------------------------------------------------------- |
| `load(options?)` | Optionally preload the editor ahead of time. Accepts an optional `version` and returns a `Promise`. |
| `createEditor(options)` | Create and mount an editor. Loads the editor on first use. Returns `Promise`. |
Once the full editor bundle has loaded — after the first `load()` or `createEditor()` call — the loader dispatches an `image-editor-ready` event on `window`. Listen for it if you preload and want to know when the editor is ready (for example, to enable an "Edit" button).
To preload a specific published editor build, pass its version to `load`. An unavailable version falls forward to the current release:
```javascript
await window.ImageEditor.load({ version: '1.500.0' });
```
## Mount Options
`createEditor(options)` accepts:
| Option | Type | Description |
| :--------------------- | :--------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `container` | `string \| HTMLElement` | CSS selector or element to mount the editor into. **Required.** |
| `image` | `string` | Image URL or base64 data URL to edit. **Required.** |
| `projectId` | `number` | Your Unlayer project ID. Required for [AI features](./ai-assistant.md). |
| `user` | `object` | Who is editing (`id`, `name`, `avatar`, `email`, `signature`, `featurePolicyToken`). Pass `id` to attribute [AI usage](./ai-assistant.md#attributing-ai-usage-to-an-end-user) to them. |
| `features` | `object` | Feature flags for the AI Assistant, [tools](./configuration.md#tools), and tool-rail dock. |
| `credits` | `object` | Host-managed `ai` allowance. Low state warns; exhausted, disabled, or invalid state blocks AI prompts only. |
| `theme` | `'light' \| 'dark'` | Editor light or dark color scheme. Default: `'light'`. |
| `customTheme` | `CustomImageEditorTheme` | Resolved custom semantic color mapping. See [Theme](./configuration.md#theme). |
| `locale` | `string` | Language code (e.g. `'en'`, `'es'`, `'fr'`). See [Localization](./configuration.md#localization). |
| `translations` | `object` | Custom translations by locale. Editor keys use `image_editor.*`; shared credit notices use `labels.credits.*`. |
| `offline` | `boolean` | Prevent external requests. Use with an offline license and locally bundled assets. Default: `false`. |
| `licenseUrl` | `string` | URL of the encrypted license file used in offline mode. |
| `env` | `object` | Advanced runtime overrides for API and image-editor asset base URLs. |
| `defaultPrompt` | `string` | Pre-fill the AI chat input with this prompt. |
| `autoSubmitPrompt` | `boolean` | With an open panel and `defaultPrompt`, submit the prompt automatically instead of only pre-filling it. Default: `false`. |
| `aiAssistantOpenState` | `'open' \| 'closed'` | Whether the available AI Assistant panel is open when the editor is ready. Default: `'open'`. |
| `onCreditsPurchase` | `(request) => result \| Promise` | Purchase action used instead of `credits.ai.purchaseUrl`. A successful result refreshes the resource snapshot. |
| `onSave` | `(result) => void` | Called when the user saves. `result` has `dataUrl` (base64 string), `blob` (`Blob`), and optional `aiEdited` (true when the saved image contains an AI edit). Older pinned versions omit `aiEdited`. |
| `onCancel` | `() => void` | Called when the user cancels. |
| `onLoadError` | `() => void` | Called when the image fails to load into the canvas because of CORS, a missing resource, or a decode error. |
To restrict AI image features for individual end-users, generate a
[signed feature-policy token](/builder/latest/security#restricting-features-per-end-user) on your
server and pass it as `user.featurePolicyToken`. Setting `ai.magicImage` to `false` in that token prevents the
end-user from opening or calling the Image Editor's AI features. If you replace the token through
`updateOptions`, the editor authenticates the new policy before enabling AI again.
To clear a persisted end-user `name`, `avatar`, or `email`, set that field to `null` in the `user`
passed to `updateOptions`. This triggers a new session and sends the clear even when the field was
omitted when the editor was created. `updateOptions` replaces the entire `user` object, so preserve
its id and current credentials. Here, `currentUser` is the most recent user passed to `createEditor`
or `updateOptions`:
```javascript
editor.updateOptions({
user: {
...currentUser,
email: null,
},
});
```
Omitting a profile field keeps its stored value. Omitting `signature` or `featurePolicyToken` means
that credential is not sent again.
`createEditor` rejects if the container element cannot be found, or if an editor is already mounted in that container — call `destroy()` on the existing instance first.
Host credits are a client-side preflight only. Keep the authoritative end-user
ledger and enforcement in your backend. Refresh one resource in an open editor
with `setCredits`:
```javascript
editor.setCredits('ai', {
limit: 100,
used: 80,
unitLabel: 'edits',
purchaseUrl: 'https://app.example.com/billing/ai',
});
```
For an in-app checkout, return a settled result from `onCreditsPurchase`. The
editor creates `request.requestId` for idempotency, disables duplicate purchase
attempts while the handler is pending, and applies valid success snapshots:
```javascript
const editor = await window.ImageEditor.createEditor({
/* ... */
onCreditsPurchase: async (request) => {
const credits = await purchaseCredits(request.requestId);
return { status: 'success', credits };
},
});
```
Return `{ status: 'cancelled' }` when checkout is dismissed, or
`{ status: 'error', message? }` when it fails. `updateOptions({})` preserves the
current credits. Passing `updateOptions({ credits: undefined })` clears the
complete host-managed snapshot.
## Instance Methods
`createEditor` resolves with an editor instance:
| Method | Description |
| :------------------------------ | :---------------------------------------------------------------------------------------------------------------------------------- |
| `destroy()` | Unmount the editor and clean up. |
| `getImage()` | Return the current canvas as a data URL, or `null`. |
| `hasChanges()` | Return `true` if the canvas has unsaved edits relative to the input image. Useful for showing a confirmation prompt before closing. |
| `updateOptions(opts)` | Update options at runtime (e.g. `theme`, `customTheme`, `locale`, `translations`). Re-renders with the new options. |
| `setCredits(resource, credits)` | Replace one host-managed credit resource while preserving the rest of the current snapshot. |
| `reset(imageUrl?)` | Reset the editor state (chat, undo/redo history) and optionally load a new image. |
```javascript
const editor = await window.ImageEditor.createEditor({
/* ... */
});
editor.updateOptions({ theme: 'dark', locale: 'es' });
editor.reset('https://example.com/another-photo.jpg');
if (!editor.hasChanges()) {
editor.destroy();
}
```
---
## Configuration
The Image Editor is configured through the options you pass to `createEditor`. This page covers the most common customizations — see the [API Reference](./api-reference.md) for the full list of options.
## User
Pass `user` to identify the end user using the standalone Image Editor. It authenticates separately from the Email Builder, so `unlayer.init({ user })` does not identify users in a standalone `createEditor()` instance.
```javascript
window.ImageEditor.createEditor({
container: '#editor-container',
image: imageUrl,
projectId: 123,
user: { id: 'customer-42' },
features: { ai: { enabled: true, assistant: true } },
});
```
Use a stable `user.id` from your application. AI edits are reported under that ID as `end_user_id` in the [AI credits usage API](/server/cloud-api/ai-credits). Without it, edits are still billed to the project but appear with `end_user_id: null`. The editor logs a warning when AI is available without an end-user ID.
If your project enables [identity verification](/builder/end-user-identification), also provide the server-generated `user.signature`, or a signed [`user.featurePolicyToken`](/builder/latest/security#restricting-features-per-end-user). Projects that require end-user feature policies must use `user.featurePolicyToken`. Never expose your project's secret key in browser code. See [AI Assistant](./ai-assistant.md) for attribution and credit reporting details.
## Tools
All eight tool tabs are enabled by default: Filter, Crop, Resize, Draw, Text, Shapes, Stickers, and Frame. Rounded corners are configured as `corners`, but the control appears inside Crop rather than as a separate tab. **Flatten layers** is a toolbar action, not a configurable tool.
You can disable any tool through `features.imageEditor.tools`.
Here's an example if you want to disable the **Resize** tool:
```javascript
window.ImageEditor.createEditor({
container: '#editor-container',
image: imageUrl,
features: {
imageEditor: {
tools: {
resize: false,
},
},
},
});
```
### Customize Tool Icons
Each tool entry also accepts an object form so you can customize its icon while keeping the tool enabled. The `icon` field accepts a FontAwesome icon name (with or without the `fa-` prefix), an image URL (`http(s):`, `data:`, or absolute path), or inline SVG markup (must start with `… ' },
resize: { enabled: false },
},
},
},
});
```
When the icon string cannot be resolved, the editor falls back to the default icon for that tool.
### Tool Rail Position
The tool rail and its properties panel dock to the right by default. Set `dock` to move both to the left:
```javascript
window.ImageEditor.createEditor({
container: '#editor-container',
image: imageUrl,
features: {
imageEditor: {
dock: 'left', // 'left' | 'right'
},
},
});
```
## Theme
The editor supports light and dark color schemes via `theme`, plus custom colors via `customTheme`:
```javascript
const editor = await window.ImageEditor.createEditor({
container: '#editor-container',
image: imageUrl,
theme: 'dark', // 'light' (default) or 'dark'
});
```
You can switch the theme at runtime — for example, to follow your application's appearance setting — with `updateOptions`:
```javascript
editor.updateOptions({ theme: 'light' });
```
To use a custom theme, pass its resolved semantic color mapping through `customTheme`. The `primary_*` colors style surfaces, borders, and text; `accent_*` colors style selected and focused controls; and the `warning_*`, `destructive_*`, and `success_*` scales style status messages. Omitted colors retain the built-in palette. You can pass the same option to `updateOptions` to repaint an open editor.
```javascript
const customTheme = {
isDark: true,
mapping: {
colors: {
primary_01: '#faf5ff',
primary_02: '#f3e8ff',
primary_03: '#e9d5ff',
primary_04: '#d8b4fe',
primary_05: '#c084fc',
primary_06: '#a855f7',
primary_07: '#9333ea',
primary_08: '#7e22ce',
primary_09: '#6b21a8',
primary_10: '#581c87',
primary_11: '#3b0764',
accent_01: '#5b21b6',
accent_02: '#7c3aed',
accent_03: '#8b5cf6',
},
},
};
const editor = await window.ImageEditor.createEditor({
container: '#editor-container',
image: imageUrl,
customTheme,
});
editor.updateOptions({ customTheme: nextCustomTheme });
```
## Localization
Set the editor language with the `locale` option. These locales ship bundled with the editor (no extra network requests): `en`, `es`, `fr`, `de`, `it`, `pt`, `nl`, `ja`, `ko`, `zh`. The editor falls back to English when a locale is not available.
```javascript
window.ImageEditor.createEditor({
container: '#editor-container',
image: imageUrl,
locale: 'fr',
});
```
### Custom Translations
You can override any string — or supply translations for a new locale — through
the `translations` option. Editor-specific keys use the `image_editor.*`
prefix. Shared host-credit notices use `labels.credits.*` keys.
```javascript
window.ImageEditor.createEditor({
container: '#editor-container',
image: imageUrl,
locale: 'fr',
translations: {
fr: {
'image_editor.toolbar.save': 'Enregistrer',
'image_editor.tools.filter': 'Effets',
'image_editor.ai_assistant.placeholder':
'Décrivez ce que vous souhaitez modifier…',
'labels.credits.exhausted': 'Vous n’avez plus de {unitLabel}.',
},
},
});
```
For the full list of translation keys, see the [Translation Reference](../../advanced-configuration/localization.md#translation-reference) — the keys are shared with the in-builder image editor.
---
## Image Editor
Unlayer's Image Editor is a standalone, embeddable image editor for your web application. Your users can crop, resize, draw, add text, apply filters, and more — or simply describe an edit in plain language and let the [AI Assistant](./ai-assistant.md) make the change for them.
The Image Editor and its manual editing tools are free. The optional [AI Assistant](./ai-assistant.md) is a paid feature.
The editor mounts into any container element on your page, works with any image URL or base64 data URL, and hands the edited image back to your application when the user saves.
:::info Looking for the in-builder image editor?
The email, page, popup, and document builders already include this image editor — users open it by double-clicking any image. To configure that built-in experience through `unlayer.init`, see [Image Editor (in the builder)](../../files-storage/images/image-editor.md). This section covers embedding the image editor as a **standalone** product.
:::
## Integration
Add the embed script and create an editor — see the [Quickstart](./quickstart.md) for a complete walkthrough.
```html
```
Using React? The official [`@unlayer/react-image-editor`](../../libraries/react-image-editor.md) component manages the embed script, editor lifecycle, and prop updates for you.
## Tools
The editor comes with eight tool tabs out of the box:
- **Filter:** Apply effects like brightness, blur, noise, sharpen, color, and grayscale.
- **Crop:** Crop to a custom or fixed aspect ratio, rotate, flip, straighten, or round the image's corners.
- **Resize:** Change the image dimensions.
- **Draw:** Draw freehand on the image with configurable brushes.
- **Text:** Add and style text overlays.
- **Shapes:** Add geometric shapes to the image.
- **Stickers:** Add stickers from a built-in library.
- **Frame:** Add decorative frames around the image.
Text, shapes, stickers, and drawings remain editable until you save, export, send the image to the AI Assistant, or select **Flatten layers** in the toolbar. Each tool can be disabled or given a custom icon, and the tool rail can dock on either side of the canvas — see [Configuration](./configuration.md).
## AI Assistant
The optional [AI Assistant](./ai-assistant.md) adds a chat panel where users describe edits in natural language — "remove the background", "make it look vintage", "convert to black & white" — and the editor applies them. AI edits participate in the same undo/redo history as manual edits.
---
## Quickstart(Image-editor)
# Image Editor Quickstart
This guide walks you through embedding Unlayer's standalone Image Editor into your web application — from adding the script to handling the saved image.
:::tip Using React?
Use the official [`@unlayer/react-image-editor`](../../libraries/react-image-editor.md) component to manage script loading and the editor lifecycle.
:::
---
## Step 1: Add the Embed Script
Add the script tag to your HTML:
```html
```
This is a lightweight loader — it does not download the full editor until you create one. If you want to preload the editor ahead of time (for example, to make an "Edit" button feel instant), you can call:
```javascript
await window.ImageEditor.load();
```
Once the full editor has loaded — after the first `load()` or `createEditor()` call — the loader dispatches an `image-editor-ready` event on `window`. Listen for it if you preload and want to know when the editor is ready to use (for example, to enable an "Edit" button).
---
## Step 2: Add a Container
Add an element for the editor to mount into:
```html
```
:::info Recommended Size
For the best experience, ensure the editor container is at least **1024px** wide and **700px** high. The editor will expand to fill the entire container.
:::
---
## Step 3: Create the Editor
Call `createEditor` with the container, the image to edit, and your project ID. It **always returns a Promise** that resolves with the editor instance once mounted.
```html
```
### Where to get the Project ID?
1. Log in to the **[Developer Console](https://console.unlayer.com/)**
2. Create a **Project**
3. You can find the project ID in **Project > Builder > Settings**
### Identifying the user
The Image Editor authenticates separately from the Email Builder, so it needs its own
`user`. Pass one whenever you use AI features, so AI credit usage is attributed to the
person doing the editing rather than reported with `end_user_id: null`. See
**[End-User Identification](/builder/end-user-identification)**.
---
## Step 4: Handle the Saved Image
The `onSave` callback receives the edited image in two forms: a `dataUrl` for previews or inline use, and a `blob` for uploading to your server or storage.
```javascript
onSave: async (result) => {
const formData = new FormData();
formData.append('file', result.blob, 'edited.png');
await fetch('/api/upload', { method: 'POST', body: formData });
},
```
When you're done with the editor, clean it up with `destroy()`. If you show the editor in a modal, use `hasChanges()` to ask the user for confirmation before closing with unsaved edits:
```javascript
if (editor.hasChanges()) {
const close = confirm('Discard unsaved changes?');
if (!close) return;
}
editor.destroy();
```
---
## What's Next
- [React Image Editor](../../libraries/react-image-editor.md) — Use the official React component.
- [Configuration](./configuration.md) — Tools, icons, theme, and localization.
- [AI Assistant](./ai-assistant.md) — Natural-language image editing.
- [API Reference](./api-reference.md) — All mount options and instance methods.
---
## Embed Videos
Videos can be added to your page and played without having to leave the page. Unlayer editor supports video links from **YouTube** or **Vimeo**. The thumbnail is automatically fetched and embedded into your pages.
## Supported Platforms
- **YouTube**: Supports both standard youtube.com and shortened youtu.be links
- **Vimeo**: Supports standard vimeo.com links
## How to Embed a Video
1. Drag and drop the Video tool to your design
2. Click on the video to open the properties panel
3. Paste your YouTube or Vimeo video URL in the "Video URL" field
4. The video thumbnail will be automatically fetched and displayed
## Customization Options
You can customize the video player appearance with the following options:
- **Play Icon Type**: Choose between different play button styles
- **Play Icon Color**: Select the color of the play button
- **Play Icon Size**: Adjust the size of the play button
## Example URLs
```javascript
// YouTube URLs
https://www.youtube.com/watch?v=VIDEO_ID
https://youtu.be/VIDEO_ID
// Vimeo URLs
https://vimeo.com/VIDEO_ID
```
You can learn more about the video tool in the [documentation](../../tools/built-in-tools/video.md).
---
## Form Tool
Our page builder comes with a [Form tool](../../tools/built-in-tools/form.md) out of the box. This is helpful to capture information from visitors.
The form tool allows your users to create interactive forms on their web pages with just a few clicks. Each form is fully customizable - you can add multiple fields, rearrange their order, style their appearance, and configure form submission settings. Whether you need a simple contact form or a complex multi-field survey, the form tool provides all the necessary features to capture visitor information effectively.
## Available Fields
The form tool offers a variety of field types that you can add to your forms:
- **Email**: For collecting email addresses
- **Name**: For collecting user names
- **Phone Number**: For collecting contact numbers
- **Birthday**: For collecting dates of birth
- **Company**: For collecting organization names
- **Website**: For collecting website URLs
- **Zip Code**: For collecting postal codes
You can change the default available fields. [Learn More](../../tools/built-in-tools/form.md)
## How to Add Fields
1. Drag and drop the Form tool from the tools panel
2. Click on the form to open the properties panel
3. Under "Fields" section, click "Select..." to add new fields
4. Choose the desired field type from the dropdown menu
## Layout Customization
You can customize the form's appearance using the Layout options:
- **Width**: Adjust the form's width using the slider (0-100%)
- Each field can be customized with its own label and placeholder text
- Fields can be reordered
- Fields can be deleted
You can learn more about the form tool in the [documentation](../../tools/built-in-tools/form.md).
---
## Page Builder
Landing pages can help your users level up their sales funnels, nurture their audience, and convert visitors into customers. The most effective landing pages have a single focus, strong call to action, and are optimized for search engines and social media. Landing pages are often temporary or permanent and are part of a marketing strategy. A landing page might require visitors to fill out a form.

When creating a landing page, design plays a very important role. It should be clean and easy to navigate, giving visitors all the information they need.
The landing page should also be easy to convert with a single click. Information architecture is important as it can help your users to create a conversion-friendly page.
---
## How Is It Different from Email Builder?
Pages and email have many common functionalities. Our page builder has been designed from the ground up to output HTML that is optimized for all web browsers. In addition, your users will find a broad range of features for web pages, such as forms, embedded videos, and the ability to add scripts to your web pages.
Here are a few examples of web pages your customers can build with Unlayer:
- Product page
- Splash page
- Disclaimer page
- Registration page
- Newsletter subscription
- Customer survey
- Booking request
- Portfolio
- Thank you page
Our page builder also has the following features:
- Users can adjust the width of the page in **percentage** (%) or **pixels** (px)
- The side bar can be **collapsed** to get a **full page view**
- Users can preview their design in **different browsers**
- **HTML scripts** can also be added
- **[Embedded videos](./embed-videos.md)** can be played within the page
- **[Form tool](./form-tool.md)** is available to capture user input
---
## Integration
After [installing](../../get-started/installation.md) our JavaScript library, use the following code snippet to initiate the page builder. Just pass `displayMode` as `web`, and replace the project id.
```javascript
unlayer.init({
id: 'editor-container',
displayMode: 'web',
projectId: 1234, // REPLACE
});
```
## Editor In Action
The output screen of the page builder will look like this (the screenshot follows your light / dark mode preference):
---
## Quickstart(Page-builder)
# Page Builder Quickstart
This guide walks you through embedding Unlayer's drag-and-drop page builder into your web application. The page builder lets your users create landing pages, product pages, and other web content.
---
## Step 1: Install the SDK
Add the script tag to your HTML:
```html
```
```bash
npm install react-email-editor
```
```bash
npm install angular-email-editor
```
```bash
npm install vue-email-editor
```
---
## Step 2: Initialize the Editor
Set `displayMode` to `web` to load the page builder.
:::info Recommended Size
For the best experience, ensure the editor container is at least **1024px** wide and **700px** high. The editor will expand to fill the entire container.
:::
```html
```
```jsx
function App() {
const emailEditorRef = useRef(null);
const onReady = () => {
console.log('Editor is ready');
};
return (
);
}
export default App;
```
**app.module.ts**
```typescript
@NgModule({
imports: [ EmailEditorModule ],
})
```
**app.component.ts**
```typescript
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
})
export class AppComponent {
@ViewChild(EmailEditorComponent)
private emailEditor: EmailEditorComponent;
options = {
displayMode: 'web',
projectId: 1234, // Replace with your project ID
};
editorLoaded() {
console.log('Editor is ready');
}
exportHtml() {
this.emailEditor.editor.exportHtml((data) =>
console.log('exportHtml', data),
);
}
}
```
**app.component.html**
```html
Export
```
```html
```
### Where to get the Project ID?
1. Log in to the **[Developer Console](https://console.unlayer.com/)**
2. Create a **Project**
3. You can find the project ID in **Project > Builder > Settings**
---
## What's Next
- [Load & Save Designs](/builder/load-and-save-designs) — Load templates and persist user work.
- [Export Designs](/builder/export-designs) — Export as HTML, PDF, images, and more.
- [Deploy to Production](/builder/installation#step-4-deploy-to-production) — Set up allowed domains and go live.
---
## Popup Builder
Popups are small windows that appear on your screen. Usually, they appear in the foreground of your visual interface. They are used to promote products and services on a website. However, many people are still not convinced by its effectiveness. Here are some benefits of popups for websites.
- Increase user engagement
- Increase conversion
- Decrease bounce rate
- Give a highly interactive Call To Action (CTA)
Due to high demand, we at Unlayer decided to add this feature to our long list of design modules.

---
## Why are Popups Used?
Popups help build lists. Most popups aim to collect email addresses, these are then used to send marketing messages to site visitors. This can lead to a higher number of conversions. Increasing user engagement with popups is a powerful way to increase conversions and lead generation. These small windows usually elicit a response from the user.
## Composition of a Popup
Popups are traditionally composed of the following things;
- Square or Rectangular Window
- Close Button
- Eye-Catching Images
When designing a popup, make sure your users have the right focus. Make the copy clear and simple. People don't like to be confused or spammed with popups. The call-to-action should be the most critical part of the popup.
## Features
Below are some of the main features of Unlayer popup builder.
### Countdown Timers
A countdown timer is a stopwatch that can be embedded in the popup, this feature is used to increase the hype of any website or product before launch.

### Merge Tags (Personalized Content)
Using personalized content feature allows your users to tailor popups based on specific customers' information.
[Merge Tags](../../advanced-configuration/dynamic-content/merge-tags.md) can be defined during the initialization of the editor.

### Ready To Go HTML
Our editor creates HTML output for popups that is ready for any website. Copy, paste, and go.
---
## Integration
After [installing](../../get-started/installation.md) our JavaScript library, use the following code snippet to initiate the email editor. You have to pass `displayMode` as `popup`, and replace your project id.
```javascript
unlayer.init({
id: 'editor-container',
displayMode: 'popup',
projectId: 1234, // REPLACE
});
```
### Multiple Popups
If you want to be able to create multiple popups for the same page, you should give each popup a unique identifier. This can be done by passing `popupId` when [exporting HTML](../../get-started/export/export-html.md). Doing this will ensure that there is no CSS conflict with other elements of the page.
```javascript
unlayer.exportHtml(console.log, {
popupId: 'UNIQUE-ID',
});
```
## Editor In Action
Once the popup builder is initialized, it will look like this.
---
## Styling Options
The popup will be in the middle of the screen, and there will be a **Popup tab** for styling options. These options are divided into the following sections.
### Popup
Popup sections helps your users to;
- Set the exact **position** of the popup panel.
- Adjust the **width** and **height** of the popup box. Height is set to auto mode by default.
- If a user clicks on 'show more options', they will be given additional options to make the edges of your popup box rounded.

### Content
The content panel contains alignment controls and other options for width, fonts, and colors. Your users can:
- Align the **position** of your popup (horizontal or vertical)
- Resize the **width** of your content box
- Edit **font family**
- Edit **text color**
- Edit **background color**
If your user clicks on 'show more options' they will be given an additional option to add an image in the background of the content box.

### Overlay
In this section, your users can change the color of the **overlay**.

### Close Button
Styling and positioning of the close button is important. The close button should be prominently visible so users are not annoyed. In this panel, your users can;
- Set the position of your close button in any of the four corners
- Set the background color of the button
- Adjust the margins and borders

### Display Delay
Timing of when the popup appears is important for user experience. In this panel, your users can set the exact timing for when the popup should appear (in seconds).

---
## Quickstart(Popup-builder)
# Popup Builder Quickstart
This guide walks you through embedding Unlayer's drag-and-drop popup builder into your web application. The popup builder lets your users design popups, modals, and overlays for lead capture, promotions, and announcements.
---
## Step 1: Install the SDK
Add the script tag to your HTML:
```html
```
```bash
npm install react-email-editor
```
```bash
npm install angular-email-editor
```
```bash
npm install vue-email-editor
```
---
## Step 2: Initialize the Editor
Set `displayMode` to `popup` to load the popup builder.
:::info Recommended Size
For the best experience, ensure the editor container is at least **1024px** wide and **700px** high. The editor will expand to fill the entire container.
:::
```html
```
```jsx
function App() {
const emailEditorRef = useRef(null);
const onReady = () => {
console.log('Editor is ready');
};
return (
);
}
export default App;
```
**app.module.ts**
```typescript
@NgModule({
imports: [ EmailEditorModule ],
})
```
**app.component.ts**
```typescript
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
})
export class AppComponent {
@ViewChild(EmailEditorComponent)
private emailEditor: EmailEditorComponent;
options = {
displayMode: 'popup',
projectId: 1234, // Replace with your project ID
};
editorLoaded() {
console.log('Editor is ready');
}
exportHtml() {
this.emailEditor.editor.exportHtml((data) =>
console.log('exportHtml', data),
);
}
}
```
**app.component.html**
```html
Export
```
```html
```
### Where to get the Project ID?
1. Log in to the **[Developer Console](https://console.unlayer.com/)**
2. Create a **Project**
3. You can find the project ID in **Project > Builder > Settings**
---
## What's Next
- [Load & Save Designs](/builder/load-and-save-designs) — Load templates and persist user work.
- [Export Designs](/builder/export-designs) — Export as HTML, PDF, images, and more.
- [Deploy to Production](/builder/installation#step-4-deploy-to-production) — Set up allowed domains and go live.
---
## Hide Property Editors
In the builder, when an end-user selects a content item to edit, a panel opens that allows them to modify various properties of the selected content.
For example, the screenshot below shows a few properties such as: **Color**, **Text Align**, **Line Height**, **Underline**, **Padding**, etc.

As a developer, you have the ability to hide specific property editors from the editing panel. This is useful when you want to simplify the user interface or restrict access to certain configuration options based on your application’s needs.
## How to Hide?
To hide individual property editors, you can configure the properties object for the relevant tool. The following example demonstrates how to hide a specific property editor for the button tool:

```javascript
unlayer.loadEditor({
tools: {
button: {
properties: {
textAlign: {
editor: {
enabled: false,
},
},
},
},
},
});
```
### Example Explained:
- **tools**: The top-level object representing all the tools in the editor (such as images, text, etc.).
- **button**: Refers to the button tool
- **properties**: Represents the different properties within the button tool
- **textAlign**: Represents the specific property that controls the alignment (as shown in screenshot above)
- **editor.enabled**: By setting this to false, you are hiding the editor for this particular property from users.
---
## Use Cases
- **Simplifying the UI**: You can remove unnecessary property editors for a streamlined user experience.
- **Role-based Access**: Hide advanced property editors for users who do not need access to complex configuration options.
---
## Notes
- When an individual property editor is hidden, the end-user will no longer see or modify that specific property.
- This feature is useful for creating a simplified or restricted user experience, especially when certain property settings are not required.
---
## Hide Property Groups
In the builder, when an end-user selects a content item to edit, a panel opens that allows them to modify various properties of the selected content. These properties are organized into **Property Groups**, making it easier for end-users to navigate and edit specific content properties.
For example, the screenshot below shows two property groups called "**Text**" and "**Links**".

As a developer, you have the ability to hide specific property groups from the editing panel. This is useful when you want to simplify the user interface or restrict access to certain configuration options based on your application’s needs.
## How to Hide?
You can hide property groups by configuring the tools option when initializing the editor. The following example demonstrates how to hide a property group "**Button Options**" from the "**Button**" tool.

```javascript
unlayer.loadEditor({
tools: {
button: {
sections: {
buttonOptions: {
editor: {
enabled: false,
},
},
},
},
},
});
```
### Example Explained:
- **tools**: The top-level object representing all the tools in the editor (such as images, text, etc.).
- **button**: Refers to the button tool
- **sections**: Represents the different sections or groups of properties within the button tool
- **buttonOptions**: Represents the specific group of properties that control the button options in the screenshot above.
- **editor.enabled**: By setting this to false, you are hiding the editor for this particular property group from users.
---
## Use Cases
- **Simplifying the UI**: You can remove unnecessary property groups for a streamlined user experience.
- **Role-based Access**: Hide advanced property groups for users who do not need access to complex configuration options.
---
## Notes
- When a property group is hidden, the end-user will not be able to view or modify the properties within that group.
- Be cautious when hiding critical property groups, as it may limit the ability of your end-users to fully customize their content.
---
## Button
Button is a built-in tool so users can add buttons to their designs. This tool is supported for both display modes: emails and web pages.
:::warning
The text editor for buttons has been updated. Existing buttons in saved designs will continue using the legacy editor, while new buttons will use the updated editor.
:::
## Enable / Disable
Button tool is enabled by default but you can choose to disable it.
```javascript
unlayer.init({
tools: {
button: {
enabled: false,
},
},
});
```
---
## Link Types
Button tools comes with the following actions:
- Open Website
- Send Email
- Call Phone Number
- Send SMS
You can add custom link types as well. [Learn more](../../advanced-configuration/link-management/link-types.md)
---
## Default Values
Button tool comes with the following default values. You can choose to change any of these.
| Property | Default Value |
| :--------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| buttonColors | `{ color: "#FFFFFF", backgroundColor: "#3AAEE0", hoverColor: "#FFFFFF", hoverBackgroundColor: "#3AAEE0" }` |
| padding | `10px 20px` |
| textAlign | `center` |
| size | `{ autoWidth: true, fullWidthOnMobile: false, width: '50%', }` |
| lineHeight | `120%` |
| borderRadius | `4px` |
| containerPadding | `10px` |
| textJson | `{"root":{"children":[{"children":[{"detail":0,"format":0,"mode":"normal","style":"","text":"Button Text","type":"extended-text","version":1}],"format":"","indent":0,"type":"extended-paragraph","version":1,"textFormat":0,"isInlineTool":true}],"format":"","indent":0,"type":"root","version":1}}` |
Here are a few examples on how to change these default values.
### Text
```javascript
unlayer.init({
tools: {
button: {
properties: {
textJson: {
value:
'{"root":{"children":[{"children":[{"detail":0,"format":0,"mode":"normal","style":"","text":"Custom Text","type":"extended-text","version":1}],"format":"","indent":0,"type":"extended-paragraph","version":1,"textFormat":0,"isInlineTool":true}],"format":"","indent":0,"type":"root","version":1}}',
},
},
},
},
});
```
---
### Button Colors
```javascript
unlayer.init({
tools: {
button: {
properties: {
buttonColors: {
value: {
color: '#FFFFFF',
backgroundColor: '#3AAEE0',
hoverColor: '#FFFFFF',
hoverBackgroundColor: '#3AAEE0',
},
},
},
},
},
});
```
---
### Padding
```javascript
unlayer.init({
tools: {
button: {
properties: {
padding: {
value: '10px 20px',
},
},
},
},
});
```
---
### Text Alignment
```javascript
unlayer.init({
tools: {
button: {
properties: {
textAlign: {
value: 'center',
},
},
},
},
});
```
---
## Carousel
Carousel is a built-in tool that allows end-users to insert a rotating slider (image carousel) into their designs. This tool is supported for both display modes: emails and web pages. **For email designs, carousel is only supported with AMP enabled**.
### Usage
Enabling Carousel tool is a bit different than other built-in tools. Follow the steps below to enable and preview Carousel tool in your designs.
#### For Email Designs (AMP Required)
For email designs, the carousel tool requires AMP to be enabled:
- **Enable AMP for Carousel tool in the Builder Configuration**: To activate AMP, set the `amp` flag to `true` in the `unlayer.init()` function or the `options` prop if you're using the React component.
Here’s the code for reference.
**JavaScript Example**:
```js
unlayer.init({
id: 'editor-container',
projectId: 123456, // replace with project ID with yours
displayMode: 'email',
version: 'latest',
amp: true,
});
```
**React Example**:
```jsx
```
- **Use the Preview Mode to see Carousel in action**: You can preview the **carousel** tool within the builder by toggling the **AMP Preview** button in the editor UI.

- **Exporting HTML for Carousel functionality**: To export the HTML for Carousel tool, use the `exportHtml()` function with the `{ amp: true }` option. This will return both standard and AMP-compliant HTML in the export payload.
```js
unlayer.exportHtml(
function (data) {
var json = data.design;
var html = data.html;
var ampHTML = data.amp.html; // extract the HTML with AMP
console.log('Design JSON:', json);
console.log('Design AMP HTML:', ampHTML);
console.log('Design HTML:', html);
},
{ amp: true }, // enables AMP in the HTML output, used for Carousel tool
);
```
#### For Web Page Designs
For web page designs, simply set the `displayMode` to `web` in your builder configuration:
**JavaScript Example**:
```js
unlayer.init({
id: 'editor-container',
projectId: 123456, // replace with project ID with yours
displayMode: 'web',
version: 'latest',
});
```
**React Example**:
```jsx
```
---
## Columns
Columns tool is different from other built-in tools. It is not a content element but rather a block that allows end-users to quickly add a new empty block and choose its column configuration.
## Enable / Disable
Columns tool is enabled by default but you can choose to disable it.
```javascript
unlayer.init({
tools: {
rows: {
enabled: false,
},
},
});
```
---
## Divider
Divider is a built-in tool so users can add dividers to their designs. This tool is supported for both display modes: emails and web pages.
## Enable / Disable
Divider tool is enabled by default but you can choose to disable it.
```javascript
unlayer.init({
tools: {
divider: {
enabled: false,
},
},
});
```
---
## Default Values
Divider tool comes with the following default values. You can choose to change any of these.
| Property | Default Value |
| :--------------- | :------------------------------------------------------------------------------------- |
| width | `100%` |
| border | `{ borderTopWidth: '1px', borderTopStyle: 'solid', borderTopColor: '#BBBBBB', }` |
| textAlign | `center` |
| containerPadding | `10px` |
Here are a few examples on how to change these default values.
### Width
```javascript
unlayer.init({
tools: {
divider: {
properties: {
width: {
value: '100%',
},
},
},
},
});
```
---
### Border
```javascript
unlayer.init({
tools: {
divider: {
properties: {
border: {
value: {
borderTopWidth: '1px',
borderTopStyle: 'solid',
borderTopColor: '#BBBBBB',
},
},
},
},
},
});
```
---
### Alignment
```javascript
unlayer.init({
tools: {
divider: {
properties: {
textAlign: {
value: 'center',
},
},
},
},
});
```
---
### Container Padding
```javascript
unlayer.init({
tools: {
divider: {
properties: {
containerPadding: {
value: '10px',
},
},
},
},
});
```
---
## Form
Form is a built-in tool for our page builder. It lets users create and add forms to their landing pages. These could be used to capture leads, sign up, contact, and a variety of other use cases.
## Enable / Disable
Form tool is enabled by default but you can choose to disable it.
```javascript
unlayer.init({
tools: {
form: {
enabled: false,
},
},
});
```
---
## Usage Limit
You can put a limit to how many times Form tool can be used in a single design.
```javascript
unlayer.init({
tools: {
form: {
usageLimit: 1,
},
},
});
```
---
## Default Values
Form tool comes with the following default values. You can choose to change any of these.
| Property | Default Value |
| :------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| fields | `[ { "name": "email", "type": "email", "label": "Email", "placeholder_text": "Enter email here", "show_label": true, "required": true } ]` |
| formWidth | `100%` |
| fieldBorder | `{ borderTopWidth: '1px', borderTopStyle: 'solid', borderTopColor: '#CCC', borderLeftWidth: '1px', borderLeftStyle: 'solid', borderLeftColor: '#CCC', borderRightWidth: '1px', borderRightStyle: 'solid', borderRightColor: '#CCC', borderBottomWidth: '1px', borderBottomStyle: 'solid', borderBottomColor: '#CCC', }` |
| fieldBorderRadius | `0px` |
| fieldPadding | `10px` |
| fieldBackgroundColor | `#FFFFFF` |
| fieldColor | `#000000` |
| fieldFontSize | `12px` |
| formAlign | `center` |
| fieldDistance | `10px` |
| placeholderAlign | `left` |
| labelFontSize | `14px` |
| labelColor | `#444` |
| labelAlign | `left` |
| labelPadding | `0px 0px 3px` |
| buttonText | `Submit` |
| buttonColors | `{ color: '#FFF', backgroundColor: '#3AAEE0', hoverColor: '#FFF', hoverBackgroundColor: '#3AAEE0' }` |
| buttonAlign | `center` |
| buttonWidth | `50%` |
| buttonFontSize | `14px` |
| buttonBorder | `{}` |
| buttonPadding | `10px` |
| buttonMargin | `5px 0px 0px` |
Here are a few examples on how to change these default values.
### Fields
When someone adds a form to their design, it only has the Email field added by default. You can change that and add more fields.
```javascript
unlayer.init({
tools: {
form: {
properties: {
fields: {
value: [
{
name: 'first_name',
type: 'text',
label: 'First Name',
placeholder_text: 'Enter first name here',
show_label: true,
required: true,
},
{
name: 'last_name',
type: 'text',
label: 'Last Name',
placeholder_text: 'Enter last name here',
show_label: true,
required: false,
},
{
name: 'email',
type: 'email',
label: 'Email',
placeholder_text: 'Enter email here',
show_label: true,
required: true,
},
],
},
},
},
},
});
```
---
### Form Width
```javascript
unlayer.init({
tools: {
form: {
properties: {
formWidth: {
value: '100%',
},
},
},
},
});
```
---
### Field Border
```javascript
unlayer.init({
tools: {
form: {
properties: {
fieldBorder: {
value: {
borderTopWidth: '1px',
borderTopStyle: 'solid',
borderTopColor: '#CCC',
borderLeftWidth: '1px',
borderLeftStyle: 'solid',
borderLeftColor: '#CCC',
borderRightWidth: '1px',
borderRightStyle: 'solid',
borderRightColor: '#CCC',
borderBottomWidth: '1px',
borderBottomStyle: 'solid',
borderBottomColor: '#CCC',
},
},
},
},
},
});
```
---
### Field Border Radius
```javascript
unlayer.init({
tools: {
form: {
properties: {
fieldBorderRadius: {
value: '0px',
},
},
},
},
});
```
---
### Field Padding
```javascript
unlayer.init({
tools: {
form: {
properties: {
fieldPadding: {
value: '10px',
},
},
},
},
});
```
---
## Preset Fields
When a user tries to add a new field, there are some preset fields available in the dropdown. You can change those preset fields if you like.
```javascript
unlayer.init({
tools: {
form: {
properties: {
fields: {
editor: {
data: {
defaultFields: [
{ name: 'birthday', label: 'Birthday', type: 'date' },
{ name: 'company', label: 'Company', type: 'text' },
{ name: 'email', label: 'Email', type: 'email' },
{ name: 'first_name', label: 'First Name', type: 'text' },
{ name: 'last_name', label: 'Last Name', type: 'text' },
{ name: 'phone_number', label: 'Phone Number', type: 'text' },
{ name: 'website', label: 'Website', type: 'text' },
{ name: 'zip_code', label: 'Zip Code', type: 'text' },
],
},
},
},
},
},
},
});
```
---
## New Custom Fields
By default, users can add a custom field if they want. You can disable this behavior.
```javascript
unlayer.init({
tools: {
form: {
properties: {
fields: {
editor: {
data: {
allowAddNewField: true,
},
},
},
},
},
},
});
```
---
## Submit Actions
You can control where you want the form to submit, or you can let the end-users add a custom URL.
## Pre-Defined Actions
You can add pre-defined actions for the form submission end-point. If there are multiple actions, the users will see a dropdown to pick one. Otherwise, it will just default to the one you provide.
Each action needs to have the following attributes.
| Attribute | Description |
| :--------- | :------------------------------------------------------------------------------------------------------------------- |
| **label** | This is the label that the users will see in the dropdown if there are multiple actions. |
| **method** | This is the HTTP method for your end-point. You can add `GET` or `POST`. |
| **url** | This is the URL where the form will submit. |
| **target** | This is target window where the form will submit. If you want the form to submit in a new tab, you can add `_blank`. |
```javascript
unlayer.init({
tools: {
form: {
properties: {
action: {
editor: {
data: {
actions: [
{
label: 'Marketing',
method: 'POST',
url: 'http://whatever.com/marketing-form-submission',
},
{
label: 'Sales',
method: 'POST',
target: '_blank',
url: 'http://whatever.com/sales-form-submission',
},
],
},
},
},
},
},
},
});
```
## Custom URL
You can let the end-user add a custom URL for the submit action. To enable this, you can set `allowCustomUrl` to true.

```javascript
unlayer.init({
tools: {
form: {
properties: {
action: {
editor: {
data: {
allowCustomUrl: true,
},
},
},
},
},
},
});
```
---
## Heading
Heading is a built-in tool so users can add headings to their designs. This tool is supported for both display modes: emails and web pages.
:::warning
The text editor for headings has been updated. Existing headings in saved designs will continue using the legacy editor, while new headings will use the updated editor.
:::
## Enable / Disable
Heading tool is enabled by default but you can choose to disable it.
```javascript
unlayer.init({
tools: {
heading: {
enabled: false,
},
},
});
```
---
## Default Values
Heading tool comes with the following default values. You can choose to change any of these.
| Property | Default Value |
| :--------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| textJson | `{"root":{"children":[{"children":[{"detail":0,"format":0,"mode":"normal","style":"","text":"Heading","type":"extended-text","version":1}],"format":"","indent":0,"type":"extended-paragraph","version":1,"textFormat":0,"isInlineTool":true}],"format":"","indent":0,"type":"root","version":1}}` |
| headingType | `h1` |
| fontFamily | `{ label: 'Arial', value: 'arial,helvetica,sans-serif'}` |
| textAlign | `left` |
| color | `#000000` |
| lineHeight | `140%` |
| containerPadding | `10px` |
Here are a few examples on how to change these default values.
### Text
```javascript
unlayer.init({
tools: {
heading: {
properties: {
textJson: {
value:
'{"root":{"children":[{"children":[{"detail":0,"format":0,"mode":"normal","style":"","text":"This is a different heading","type":"extended-text","version":1}],"format":"","indent":0,"type":"extended-paragraph","version":1,"textFormat":0,"isInlineTool":true}],"format":"","indent":0,"type":"root","version":1}}',
},
},
},
},
});
```
---
### Alignment
```javascript
unlayer.init({
tools: {
heading: {
properties: {
textAlign: {
value: 'right',
},
},
},
},
});
```
---
### Color
```javascript
unlayer.init({
tools: {
heading: {
properties: {
color: {
value: '#000000',
},
},
},
},
});
```
---
### Line Height
```javascript
unlayer.init({
tools: {
heading: {
properties: {
lineHeight: {
value: '140%',
},
},
},
},
});
```
---
### Container Padding
```javascript
unlayer.init({
tools: {
heading: {
properties: {
containerPadding: {
value: '10px',
},
},
},
},
});
```
---
## HTML
HTML is a built-in tool so users can add custom HTML to their designs. This tool is supported for both display modes: emails and web pages.
## Enable / Disable
HTML tool is enabled by default but you can choose to disable it.
```javascript
unlayer.init({
tools: {
html: {
enabled: false,
},
},
});
```
---
## CodeMirror Options
[CodeMirror](https://codemirror.net/) is the code editor component used for the HTML editor. It has a variety of configuration options that you can override.
In this example code, we will disable the line wrapping in the HTML editor.
```javascript
unlayer.init({
tools: {
html: {
properties: {
html: {
editor: {
widgetParams: {
codeMirrorOptions: {
lineWrapping: false,
},
},
},
},
},
},
},
});
```
---
## Default Values
HTML tool comes with the following default values. You can choose to change any of these.
| Property | Default Value |
| :--------------- | :------------------------------- |
| html | `Hello, world!` |
| containerPadding | `10px` |
Here are a few examples on how to change these default values.
### HTML
```javascript
unlayer.init({
tools: {
html: {
properties: {
html: {
value: 'Hello, world!',
},
},
},
},
});
```
---
### Container Padding
```javascript
unlayer.init({
tools: {
html: {
properties: {
containerPadding: {
value: '10px',
},
},
},
},
});
```
---
## HTML Sanitization
Setting `safeHtml: true` will remove invalid HTML structures to prevent potential security issues and ensure valid HTML output.
### Table Sanitization
For example, if you input an invalid table structure like:
```html
Invalid table
```
It will be removed because it's missing the required `` element. A valid table structure should be:
```html
Valid table
```
If you need to disable this sanitization, you can set `safeHtml: false` in your initialization options.
---
## Image
Image is a built-in tool so users can add images to their designs. This tool is supported for both display modes: emails and web pages.
## Enable / Disable
Image tool is enabled by default but you can choose to disable it.
```javascript
unlayer.init({
tools: {
image: {
enabled: false,
},
},
});
```
---
## Default Values
Image tool comes with the following default values. You can choose to change any of these.
| Property | Default Value |
| :--------------- | :----------------------------------------------------------------------------------------- |
| src | `{ url: 'https://via.placeholder.com/500x100?text=IMAGE', width: 500, height: 100 }` |
| textAlign | `center` |
| altText | `Image` |
| containerPadding | `center` |
Here are a few examples on how to change these default values.
### Source
```javascript
unlayer.init({
tools: {
image: {
properties: {
src: {
value: {
url: 'https://via.placeholder.com/500x100?text=IMAGE',
width: 500,
height: 100,
},
},
},
},
},
});
```
---
### Alignment
```javascript
unlayer.init({
tools: {
image: {
properties: {
textAlign: {
value: 'center',
},
},
},
},
});
```
---
### Alternate Text
```javascript
unlayer.init({
tools: {
image: {
properties: {
altText: {
value: 'Image',
},
},
},
},
});
```
---
### Container Padding
```javascript
unlayer.init({
tools: {
image: {
properties: {
containerPadding: {
value: '10px',
},
},
},
},
});
```
---
## Placeholder
You can set a placeholder image for the image tool. This image will be displayed when the image URL is empty.
```javascript
unlayer.init({
image: {
properties: {
src: {
editor: {
widgetParams: {
placeholderUrl: 'IMAGE_PLACEHOLDER_URL',
},
},
},
},
},
});
```
---
## Menu
Menu is a built-in tool used to create navigation menus. It is supported in both display modes: email and web pages.
## Enable / Disable
Menu tool is enabled by default but you can choose to disable it.
```javascript
unlayer.init({
tools: {
menu: {
enabled: false,
},
},
});
```
---
## Default Values
Menu tool comes with the following default values. You can choose to change any of these.
| Property | Default Value |
| :--------- | :------------------------------------------------------------ |
| menu | `{ items: [] }` |
| fontFamily | `{ label: 'Arial', value: 'arial,helvetica,sans-serif' }` |
| fontSize | `14px` |
| textColor | `#444444` |
| linkColor | `#0068A5` |
| align | `center` |
| layout | `horizontal` |
| separator | ` ` |
| padding | `5px 15px` |
Here are a few examples on how to change these default values.
### Menu Items
You can set the menu tool to come with default menu items and their URLs pre-filled.
```javascript
unlayer.init({
tools: {
menu: {
properties: {
menu: {
value: {
items: [
{
key: `${Date.now() + Math.floor(Math.random() * 100)}`, // unique key
text: 'Home Page',
link: {
name: 'web',
values: {
href: 'https://mysite.com',
target: '_self',
},
},
},
{
key: `${Date.now() + Math.floor(Math.random() * 100)}`, // unique key
text: 'About Us',
link: {
name: 'web',
values: {
href: 'https://mysite.com/about-us',
target: '_self',
},
},
},
],
},
},
},
},
},
});
```
---
### Layout
By default, the layout is set to horizontal but you can change it to vertical.
```javascript
unlayer.init({
tools: {
menu: {
properties: {
layout: {
value: 'vertical',
},
},
},
},
});
```
---
### Separator
You can add a separator between menu items by default.
```javascript
unlayer.init({
tools: {
menu: {
properties: {
separator: {
value: '|',
},
},
},
},
});
```
---
### Padding
```javascript
unlayer.init({
tools: {
menu: {
properties: {
padding: {
value: '10px',
},
},
},
},
});
```
---
## Built-In Tools
Our platform provides a variety of pre-configured, easy-to-use tools that empower your users to design and customize their content seamlessly. These built-in tools offer essential elements for creating emails, pages, and popups without the need for coding.
Each of the following tool is highly customizable, allowing you to adapt them to match your application’s design and user preferences.
---
## Paragraph
Paragraph is a built-in tool so users can add text to their designs. This tool is supported for all display modes.
## Enable / Disable
Paragraph tool is enabled by default but you can choose to disable it.
```javascript
unlayer.init({
tools: {
paragraph: {
enabled: false,
},
},
});
```
---
## Default Values
Paragraph tool comes with the following default values. You can choose to change any of these.
| Property | Default Value |
| :--------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| textJson | `{"root":{"children":[{"children":[{"detail":0,"format":0,"mode":"normal","text":"This is a new Paragraph block. Change the text.","type":"extended-text","version":1}],"format":"","indent":0,"type":"paragraph","version":1,"textFormat":0}],"format":"","indent":0,"type":"root","version":1}}` |
| textAlign | `left` |
| fontSize | `14px` |
| color | `#000000` |
| lineHeight | `140%` |
| containerPadding | `10px` |
| fontFamily | `Arial, Helvetica, sans-serif` |
Here are a few examples on how to change these default values.
### Default Text
```javascript
unlayer.init({
tools: {
paragraph: {
properties: {
textJson: {
value:
'{"root":{"children":[{"children":[{"detail":0,"format":0,"mode":"normal","text":"My Paragraph","type":"extended-text","version":1}],"format":"","indent":0,"type":"paragraph","version":1,"textFormat":0}],"format":"","indent":0,"type":"root","version":1}}',
},
},
},
},
});
```
---
### Font Size
```javascript
unlayer.init({
tools: {
paragraph: {
properties: {
fontSize: {
editor: {
defaultValue: '16px',
},
},
},
},
},
});
```
---
### Alignment
```javascript
unlayer.init({
tools: {
paragraph: {
properties: {
textAlign: {
editor: {
defaultValue: 'right',
},
},
},
},
},
});
```
---
### Color
```javascript
unlayer.init({
tools: {
paragraph: {
properties: {
color: {
editor: {
defaultValue: '#ff0000',
},
},
},
},
},
});
```
---
### Line Height
```javascript
unlayer.init({
tools: {
paragraph: {
properties: {
lineHeight: {
editor: {
defaultValue: '140%',
},
},
},
},
},
});
```
---
### Container Padding
```javascript
unlayer.init({
tools: {
paragraph: {
properties: {
containerPadding: {
editor: {
defaultValue: '10px',
},
},
},
},
},
});
```
### Font Family
```javascript
unlayer.init({
tools: {
paragraph: {
properties: {
fontFamily: {
editor: {
defaultValue: {
value: "'Pacifico',cursive",
},
},
},
},
},
},
});
```
Please match exactly the value with one of those found in the [font family configuration](/builder/font-management/default-fonts).
---
## Migrating from Text Tool
The **Text** tool is deprecated in favor of **Paragraph**. Existing templates with Text blocks can still be loaded for backward compatibility, but the legacy Text tool is no longer actively maintained or receiving new bug fixes.
### Migrate Your Configuration to Paragraph
Update your configuration from `tools.text` to `tools.paragraph`. The text property also changes: Text uses `text` (an HTML string), while Paragraph uses `textJson` (a JSON string).
Use the [Default Text example](#default-text) above to configure Paragraph defaults. For before-and-after configuration examples, see the [Text-to-Paragraph migration guide](/builder/latest/migration/from-1-309-4-to-1-339-0).
### Migrate Existing Templates
Changing `tools.text` to `tools.paragraph` does not convert Text blocks in stored design JSON. Use the Cloud API's [Text-to-Paragraph conversion endpoint](/server/cloud-api/reference#tag/templates/operation/convertTextToParagraph) to convert existing designs.
The API returns a converted copy without creating or modifying a saved template. A Text block containing a table, image or horizontal rule can be split into Paragraph blocks plus Table, Image or Divider blocks. Review `data.warnings` and the converted design before saving it.
For the response fields and review steps, see [Migrate Existing Templates](/builder/latest/migration/from-1-309-4-to-1-339-0#migrate-existing-templates).
### Preserve Legacy Text Behavior
If you need to retain the deprecated Text tool's functionality, use one of the compatibility options below. Duplicating a Text block or locking your builder version preserves legacy behavior; neither option migrates your blocks or configuration to Paragraph or restores active maintenance of the legacy Text tool.
#### Duplicate an Existing Text Block
1. Find an existing template that uses the Text tool.
2. Duplicate the Text block.
3. The duplicated Text block retains its old functionality.
#### Lock Your Builder Version
Pin your builder to a stable version where the Text tool is still available. See the [version locking documentation](/builder/latest/version-management) for detailed instructions.
---
## Social Media
Social Media is a built-in tool that lets users add their social media icons to an email or web page.
## Enable / Disable
```javascript
unlayer.init({
tools: {
social: {
enabled: false,
},
},
});
```
---
## Default Values
Social Media tool comes with the following default values. You can choose to change any of these.
| Property | Default Value |
| :--------------- | :------------ |
| icons | `[]` |
| spacing | `5` |
| align | `center` |
| containerPadding | `10px` |
Here are a few examples on how to change these default values.
### Icons
You can set the social media tool to come with default social networks and their URLs pre-filled.
`iconType` is optional and defaults to `circle`. Set it explicitly to choose another style,
such as `squared`.
```javascript
unlayer.init({
tools: {
social: {
properties: {
icons: {
value: {
icons: [
{ name: 'Facebook', url: 'https://facebook.com/' },
{ name: 'X', url: 'https://x.com/' },
],
},
},
},
},
},
});
```
---
### Icon Spacing
```javascript
unlayer.init({
tools: {
social: {
properties: {
spacing: {
value: 5,
},
},
},
},
});
```
---
### Alignment
```javascript
unlayer.init({
tools: {
social: {
properties: {
align: {
value: 'center',
},
},
},
},
});
```
---
### Container Padding
```javascript
unlayer.init({
tools: {
social: {
properties: {
containerPadding: {
value: '10px',
},
},
},
},
});
```
---
## AI-generated designs
Social values in AI-generated designs and Simple JSON can omit `iconType`. Conversion keeps the
configured networks and uses `circle` for the missing style.
## Explicit image URLs
A Social icon can carry its own `imgUrl` in a design or default value. The image is preserved on the
canvas, in the settings preview, and in exported HTML. Changing the icon style keeps that image
unless a matching registered custom icon supplies the selected style.
`iconType` selects an image variant; it does not crop an explicit `imgUrl`. For a circular
custom icon, supply a PNG with a circular image and transparent corners, as in this example.
The shape is part of the image itself, so it does not depend on CSS `border-radius` support
in email clients. To support multiple shapes, register a separate image for each style
under [Custom Icons](#custom-icons).
```javascript
unlayer.init({
tools: {
social: {
properties: {
icons: {
value: {
icons: [
{
name: 'Flower Club',
url: 'https://example.com/',
imgUrl:
'https://docs.unlayer.com/img/custom-social-flower-circle.png',
},
],
},
},
},
},
},
});
```
## Custom Icons
Social media tool comes with a default set of social media networks. If you want to add a different social network, you can do that. Each custom icon must have an image url available for all icon types:
- circle
- circle-black
- circle-white
- rounded
- rounded-black
- squared
- squared-black
### Add New Icons
```javascript
unlayer.init({
tools: {
social: {
properties: {
icons: {
value: {
iconType: 'circle',
editor: {
data: {
customIcons: [
{
name: 'Twitch',
url: 'https://twitch.tv/',
icons: {
circle:
'https://cdn3.iconfinder.com/data/icons/popular-services-brands-vol-2/512/twitch-64.png',
'circle-black':
'https://cdn3.iconfinder.com/data/icons/popular-services-brands-vol-2/512/twitch-64.png',
'circle-white':
'https://cdn3.iconfinder.com/data/icons/popular-services-brands-vol-2/512/twitch-64.png',
rounded:
'https://cdn3.iconfinder.com/data/icons/popular-services-brands-vol-2/512/twitch-64.png',
'rounded-black':
'https://cdn3.iconfinder.com/data/icons/popular-services-brands-vol-2/512/twitch-64.png',
squared:
'https://cdn3.iconfinder.com/data/icons/popular-services-brands-vol-2/512/twitch-64.png',
'squared-black':
'https://cdn3.iconfinder.com/data/icons/popular-services-brands-vol-2/512/twitch-64.png',
},
},
],
},
},
},
},
},
},
},
});
```
### Turn Off Default
If you don't want the default icons to show and only show your custom ones, you can do that as well.
```javascript
unlayer.init({
tools: {
social: {
properties: {
icons: {
value: {
editor: {
data: {
showDefaultIcons: false,
customIcons: [],
},
},
},
},
},
},
},
});
```
---
## Table
Table is a built-in tool so users can add table to their designs. This tool is supported for all display modes.
## Enable / Disable
Table tool is enabled by default but you can choose to disable it.
```javascript
unlayer.init({
tools: {
table: {
enabled: false,
},
},
});
```
---
## Default Values
Table tool comes with the following default values. You can choose to change any of these.
| Property | Default Value |
| :------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| columns | `2` |
| rows | `2` |
| table | `{ headers: [{ cells: [{ text: 'Add header text' }, { text: '' }] }], rows: [{ cells: [{ text: 'Add text' }, { text: '' }] }, { cells: [{ text: '' }, { text: '' }] }] }` |
| border | `{ borderTopWidth: '1px', borderTopStyle: 'solid', borderTopColor: '#CCC', borderLeftWidth: '1px', borderLeftStyle: 'solid', borderLeftColor: '#CCC', borderRightWidth: '1px', borderRightStyle: 'solid', borderRightColor: '#CCC', borderBottomWidth: '1px', borderBottomStyle: 'solid', borderBottomColor: '#CCC' }` |
| stripedRows | `false` |
| stripedRowsBackgroundColor | `#CCC` |
| enableHeader | `true` |
| repeatHeaderOnEachPage | `true` |
| headerFontFamily | `inherit` |
| headerBackgroundColor | `#DDDDDD` |
| headerFontWeight | `700` |
| headerFontSize | `14px` |
| headerColor | `inherit` |
| headerTextAlign | `left` |
| headerPadding | `10px` |
| contentFontFamily | `inherit` |
| contentBackgroundColor | `#FFFFFF` |
| contentFontWeight | `inherit` |
| contentFontSize | `14px` |
| contentColor | `inherit` |
| contentTextAlign | `left` |
| contentLineHeight | `140%` |
| contentLetterSpacing | `inherit` |
| contentPadding | `10px` |
| enableFooter | `false` |
| repeatFooterOnEachPage | `true` |
| footerFontFamily | `inherit` |
| footerBackgroundColor | `#DDDDDD` |
| footerFontWeight | `700` |
| footerFontSize | `14px` |
| footerColor | `inherit` |
| footerTextAlign | `left` |
| footerPadding | `10px` |
Here are examples of how to customize the default values for the table tool:
### Table Values
```javascript
unlayer.init({
tools: {
table: {
properties: {
table: {
value: {
headers: [
{
cells: [{ text: 'Name' }, { text: 'Email' }],
},
],
rows: [
{
cells: [{ text: 'John Doe' }, { text: 'john@example.com' }],
},
{
cells: [{ text: 'Jane Smith' }, { text: 'jane@example.com' }],
},
],
},
},
},
},
},
});
```
### Columns and Rows
```javascript
unlayer.init({
tools: {
table: {
properties: {
columns: {
editor: {
defaultValue: 4,
},
},
rows: {
editor: {
defaultValue: 5,
},
},
},
},
},
});
```
---
### Columns and Rows Limits
You can configure the minimum and maximum allowed values for columns and rows using `widgetParams`. This will enforce limits both in the property editor and in the table controls.
```javascript
unlayer.init({
tools: {
table: {
properties: {
columns: {
editor: {
widgetParams: {
minValue: 1,
maxValue: 4,
},
},
},
rows: {
editor: {
widgetParams: {
minValue: 1,
maxValue: 5,
},
},
},
},
},
},
});
```
---
### Background Color
```javascript
unlayer.init({
tools: {
table: {
properties: {
backgroundColor: {
editor: {
defaultValue: '#FFFFFF',
},
},
},
},
},
});
```
---
### Header Settings
```javascript
unlayer.init({
tools: {
table: {
properties: {
enableHeader: {
editor: {
defaultValue: true,
},
},
headerFontSize: {
editor: {
defaultValue: '16px',
},
},
headerColor: {
editor: {
defaultValue: '#333333',
},
},
headerFontWeight: {
editor: {
defaultValue: 600,
},
},
headerTextAlign: {
editor: {
defaultValue: 'center',
},
},
headerFontFamily: {
editor: {
defaultValue: {
value: "'Pacifico',cursive", // Please match exactly the value with one of those found in the font family configuration
},
},
},
},
},
},
});
```
---
### Content Settings
```javascript
unlayer.init({
tools: {
table: {
properties: {
contentFontSize: {
editor: {
defaultValue: '16px',
},
},
contentColor: {
editor: {
defaultValue: '#444444',
},
},
contentLineHeight: {
editor: {
defaultValue: '150%',
},
},
contentLetterSpacing: {
editor: {
defaultValue: '1px',
},
},
contentFontWeight: {
editor: {
defaultValue: 400,
},
},
contentTextAlign: {
editor: {
defaultValue: 'center',
},
},
contentFontFamily: {
editor: {
defaultValue: {
value: "'Pacifico',cursive", // Please match exactly the value with one of those found in the font family configuration
},
},
},
},
},
},
});
```
---
### Footer Settings
```javascript
unlayer.init({
tools: {
table: {
properties: {
enableFooter: {
editor: {
defaultValue: true,
},
},
footerFontSize: {
editor: {
defaultValue: '16px',
},
},
footerColor: {
editor: {
defaultValue: '#333333',
},
},
footerFontWeight: {
editor: {
defaultValue: 600,
},
},
footerTextAlign: {
editor: {
defaultValue: 'center',
},
},
footerBackgroundColor: {
editor: {
defaultValue: '#EEEEEE',
},
},
footerPadding: {
editor: {
defaultValue: '15px',
},
},
footerFontFamily: {
editor: {
defaultValue: {
value: "'Pacifico',cursive", // Please match exactly the value with one of those found in the font family configuration
},
},
},
},
},
},
});
```
---
### Repeating Header and Footer Across Pages
When a table spans multiple pages in the [Document Builder](../../builders/document-builder/overview.md) (`displayMode: 'document'`), its header and footer rows can either repeat at the top and bottom of every page or render only once — at the start of the first page (header) and the end of the last page (footer).
This is controlled per-table by `repeatHeaderOnEachPage` and `repeatFooterOnEachPage`. Both default to `true`. They have no effect outside `displayMode: 'document'`, and they're hidden from the property panel in other display modes.
| Property | Default | Behavior when `true` | Behavior when `false` |
| :----------------------- | :------ | :-------------------------------------------------------------- | :------------------------------------------------------------------- |
| `repeatHeaderOnEachPage` | `true` | Header row repeats at the top of every page the table spans. | Header row renders once at the start of the table and never repeats. |
| `repeatFooterOnEachPage` | `true` | Footer row repeats at the bottom of every page the table spans. | Footer row renders once at the end of the table and never repeats. |
You can change the defaults the same way as the other header/footer properties:
```javascript
unlayer.init({
displayMode: 'document',
tools: {
table: {
properties: {
repeatHeaderOnEachPage: {
editor: {
defaultValue: false,
},
},
repeatFooterOnEachPage: {
editor: {
defaultValue: false,
},
},
},
},
},
});
```
The toggles are also surfaced in the table's property panel under **Header** and **Footer**, so end-users can flip the behavior per table without code.
---
### Striped Rows
```javascript
unlayer.init({
tools: {
table: {
properties: {
stripedRows: {
editor: {
defaultValue: true,
},
},
stripedRowsBackgroundColor: {
editor: {
defaultValue: '#F0F0F0',
},
},
},
},
},
});
```
---
### Border Settings
```javascript
unlayer.init({
tools: {
table: {
properties: {
border: {
editor: {
defaultValue: {
borderTopWidth: '2px',
borderTopStyle: 'solid',
borderTopColor: '#000000',
},
},
},
},
},
},
});
```
---
## Text
:::warning
Text tool was deprecated in favor of the [Paragraph tool](/builder/latest/tools/paragraph). Existing texts created with the Text tool will continue to work as expected.
:::
Text is a built-in tool so users can add text to their designs. This tool is supported for both display modes: emails and web pages.
## Enable / Disable
Text tool is enabled by default but you can choose to disable it.
```javascript
unlayer.init({
tools: {
text: {
enabled: false,
},
},
});
```
---
## Default Values
Text tool comes with the following default values. You can choose to change any of these.
| Property | Default Value |
| :--------------- | :----------------------------------------------------------------------------- |
| text | `This is a new Text block. Change the text.` |
| textAlign | `left` |
| fontSize | `16px` |
| color | `#000000` |
| lineHeight | `140%` |
| containerPadding | `10px` |
| fontFamily | `Arial, Helvetica, sans-serif` |
Here are a few examples on how to change these default values.
### Default Text
```javascript
unlayer.init({
tools: {
text: {
properties: {
text: {
value:
'This is a new Text block. Change the text.',
},
},
},
},
});
```
---
### Font Size
```javascript
unlayer.init({
tools: {
text: {
properties: {
fontSize: {
editor: {
defaultValue: '16px',
},
},
},
},
},
});
```
---
### Alignment
```javascript
unlayer.init({
tools: {
text: {
properties: {
textAlign: {
editor: {
defaultValue: 'right',
},
},
},
},
},
});
```
---
### Color
```javascript
unlayer.init({
tools: {
text: {
properties: {
color: {
editor: {
defaultValue: '#000000',
},
},
},
},
},
});
```
---
### Line Height
```javascript
unlayer.init({
tools: {
text: {
properties: {
lineHeight: {
editor: {
defaultValue: '140%',
},
},
},
},
},
});
```
---
### Container Padding
```javascript
unlayer.init({
tools: {
text: {
properties: {
containerPadding: {
editor: {
defaultValue: '10px',
},
},
},
},
},
});
```
### Font Family
```javascript
unlayer.init({
tools: {
text: {
properties: {
fontFamily: {
editor: {
defaultValue: {
value: "'Pacifico',cursive",
},
},
},
},
},
},
});
```
Please match exactly the value with one of those found in the font family configuration.
---
## Timer
Timer is a built-in tool used to create countdown timers. This tool create a countdown GIF image to run a realtime countdown. It is supported in both display modes: email and web pages.
## Enable / Disable
Timer tool is a premium tool. If you have it in your subscription, It's enabled by default but you can choose to disable it.
```javascript
unlayer.init({
tools: {
timer: {
enabled: false,
},
},
});
```
---
## Default Values
Timer tool comes with the following default values. You can choose to change any of these.
| Property | Default Value |
| --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| countdown | `{ countdownUrl: "https://cdn.tools.unlayer.com/countdown/countdown.gif", endTime: "", backgroundColor: "#FFFFFF", labelColor: "#A3A3A3", labelFontFamily: "Open Sans", labelFontSize: 16, digitColor: "#404040", digitFontFamily: "Open Sans", digitFontSize: 40, timezone: "America/Los_Angeles", locale: null, showLabels: true }` |
| width | `{ autoWidth: true, width: "100%" }` |
| textAlign | `center` |
| altText | `""` (empty: the end date is used, see [Alternate Text](#alternate-text)) |
| action | `{ name: "web", values: { href: "", target: "_blank" } }` |
Here are a few examples on how to change these default values.
### Countdown Properties
You can change any of the default countdown properties such as labels, language, fonts, timezone, etc.
Each property expects a specific type. Only `locale` accepts `null`; for every other property,
omit it to keep its default rather than passing `null` (an omitted property always falls back to its
built-in default).
| Property | Type | Notes |
| ----------------- | ---------------- | --------------------------------------------------- |
| `countdownUrl` | string | Placeholder GIF shown before the timer is rendered |
| `endTime` | string | ISO date-time, e.g. `2030-01-01T00:00:00` |
| `backgroundColor` | string | Hex or rgb(a) color |
| `labelColor` | string | Hex or rgb(a) color |
| `digitColor` | string | Hex or rgb(a) color |
| `labelFontFamily` | string | One of the supported fonts below (case-insensitive) |
| `digitFontFamily` | string | One of the supported fonts below (case-insensitive) |
| `labelFontSize` | number | |
| `digitFontSize` | number | |
| `timezone` | string | IANA timezone, e.g. `America/Los_Angeles` |
| `locale` | string \| `null` | `null` uses the editor's locale |
| `showLabels` | boolean | |
`labelFontFamily` and `digitFontFamily` accept one of the following names (matched
case-insensitively, so `arial` resolves to `Arial`): `Arial`, `Arial Black`, `Book Antiqua`,
`Comic Sans MS`, `Courier New`, `Georgia`, `Helvetica`, `Impact`, `Open Sans`, `Times New Roman`.
An unrecognized name falls back to `Open Sans`.
```javascript
unlayer.init({
tools: {
timer: {
properties: {
countdown: {
value: {
countdownUrl: `https://cdn.tools.unlayer.com/countdown/countdown.gif`,
endTime: '',
backgroundColor: '#000000',
labelColor: '#FFFFFF',
labelFontFamily: 'Open Sans',
labelFontSize: 28,
digitColor: '#FFFFFF',
digitFontFamily: 'Open Sans',
digitFontSize: 75,
timezone: 'America/Los_Angeles',
locale: null,
showLabels: false,
},
},
},
},
},
});
```
---
### Layout
By default, the layout is set to horizontal but you can change it to vertical.
```javascript
unlayer.init({
tools: {
timer: {
properties: {
layout: {
value: 'vertical',
},
},
},
},
});
```
---
### Width
By default, countdown GIF image is added with auto width turned on. You can change it.
```javascript
unlayer.init({
tools: {
timer: {
properties: {
width: {
value: {
autoWidth: false,
width: '50%',
},
},
},
},
},
});
```
---
### Alternate Text
The countdown is a GIF, so recipients whose email client blocks remote images see the alternate
text instead. When the alternate text is empty (or still the former default `Countdown`), the
exported image uses the countdown's end date in its configured timezone and language, for example
`Oct 7, 2026, 11:05 AM PDT`, so the deadline is still readable when the timer itself is not shown.
Set your own text to replace it.
```javascript
unlayer.init({
tools: {
timer: {
properties: {
altText: {
value: 'Countdown Timer',
},
},
},
},
});
```
The exported image also declares the countdown's size, so clients that support it keep the
design's layout while the GIF loads or when images are blocked.
---
## Video
Video is a built-in tool that lets users add **YouTube** or **Vimeo** videos to their emails or landing pages. This tool automatically generates thumbnails of videos for emails and ensures that it renders correctly on all platforms.
## Enable / Disable
```javascript
unlayer.init({
tools: {
video: {
enabled: false,
},
},
});
```
---
## CSS / JavaScript
Each tool has the ability to insert it's CSS or JavaScript in the `` part of HTML. This is useful if you don't want to use inline styles and want the CSS to be in the head instead.
You can target the specific instance of the tool by its HTML id using **values.\_meta.htmlID**.
```javascript
unlayer.registerTool({
name: 'my_tool',
label: 'My Tool',
icon: 'fa-smile',
supportedDisplayModes: ['web', 'email'],
options: {
colors: {
title: 'Colors',
position: 1,
options: {
textColor: {
label: 'Text Color',
defaultValue: '#FF0000',
widget: 'color_picker',
},
backgroundColor: {
label: 'Background Color',
defaultValue: '#FF0000',
widget: 'color_picker',
},
},
},
},
values: {},
renderer: {
Viewer: unlayer.createViewer({
render(values) {
return `I am a custom tool.`;
},
}),
exporters: {
web: function (values) {
return `I am a custom tool.`;
},
email: function (values) {
return `I am a custom tool.`;
},
},
head: {
css: function (values) {
return `#${values._meta.htmlID} div { background-color: ${values.backgroundColor}; color: ${values.textColor}; }`;
},
js: function (values) {
return `console.log("Tool JavaScript");`;
},
},
},
});
```
---
## Property States
When you register a tool, you can also provide a function to manage property states. This is especially useful if you want to hide or show property editors when value of another property changes.
```javascript
unlayer.registerTool({
...
propertyStates: (values) => {
if (values.textAlign === 'center') {
return {
textColor: {
enabled: false
}
};
}
}
);
```
In the example above, we are hiding the `textColor` color picker when value of `textAlign` is set to `center`.
---
## Transform Property Values
When you register a tool, you can also create a transformer for that tool. Transformer is a function that is called each time any of the properties is changed and gives you an opportunity to modify any or all of the values in the tool.
```javascript
unlayer.registerTool({
...
transformer: (values, source) => {
const { name, value, data } = source;
// Transform the values here
let newValues = {
...values
};
// Return updated values
return newValues;
}
});
```
The arguments passed to the transformer are these:
| Option | Description |
| :--------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **values** | Current property values for the tool |
| **source** | An object that contains information for the property that triggered this call:**name** of the property**value** of the property**data** is the optional metadata passed by the [updateValue](../create-custom-tool.md#javascript) function of the property editor |
---
## Built-In Property Editors
Following is a list of built-in property editors available and their value formats.
## Text Input

#### Widget
```
text
```
#### Default Value
```
String
```
---
## Rich Text Input V2
:::warning WARNING
`rich_text` was deprecated. Use `rich_text_v2` instead for new custom tools. It's a direct replacement with the same HTML string format.
:::

#### Widget
```
rich_text_v2
```
#### Default Value
```
String
```
---
## HTML Input

#### Widget
```
html
```
#### Default Value
```
String
```
---
## Color Picker

#### Widget
```
color_picker
```
#### Default Value
```
String
```
#### Valid Values
- HEX Format `#FFF000`
- RGB Format `rgba(0,0,0,0.5)`
---
## Text Alignment

#### Widget
```
alignment
```
#### Default Value
```
String
```
#### Valid Values
- `left`
- `center`
- `right`
---
## Font Family

#### Widget
```
font_family
```
#### Default Value
```
JSON
```
#### Valid Value
```json
{
"label": "Arial",
"value": "arial,helvetica,sans-serif"
}
```
---
## Border

#### Widget
```
border
```
#### Default Value
```
JSON
```
#### Valid Value
```json
{
"borderTopWidth": "0px",
"borderTopStyle": "solid",
"borderTopColor": "#CCC",
"borderLeftWidth": "0px",
"borderLeftStyle": "solid",
"borderLeftColor": "#CCC",
"borderRightWidth": "0px",
"borderRightStyle": "solid",
"borderRightColor": "#CCC",
"borderBottomWidth": "0px",
"borderBottomStyle": "solid",
"borderBottomColor": "#CCC"
}
```
---
## Counter

#### Widget
```
counter
```
#### Default Value
```
String
```
#### Example Values
`10` `25` `50` etc
---
## Image Uploader

#### Widget
```
image
```
#### Default Value
```
JSON
```
#### Valid Value
```json
{
"url": "http://via.placeholder.com/350x150"
}
```
---
## Toggle

#### Widget
```
toggle
```
#### Default Value
```
Boolean
```
#### Valid Values
- `true`
- `false`
---
## Link

#### Widget
```
link
```
#### Default Value
```
JSON
```
#### Valid Values
```json
{
"name": "web",
"values": {
"href": "http://google.com",
"target": "_blank"
}
}
```
#### Return Value
```json
{
"url": "http://google.com",
"target": "_blank"
}
```
---
## Dropdown

#### Widget
```
dropdown
```
### Dropdown Options
The dropdown editor needs options to be passed as data. Learn more at: [Passing Data to Property Editors](./create-custom-tool.md#dropdown-example)
---
## Date / Time

#### Widget
```
datetime
```
#### Default Value
```
String
```
#### Widget Params
```
hideTime (boolean)
hideCalendar (boolean)
format (string)
```
---
## Custom Editors
If you want to build a custom property editor for advanced use cases, you can do that with our [registerPropertyEditor API](./create-custom-tool.md#custom-property-editor).
---
## Create a Custom Tool
This tutorial will get you started with your first custom tool using our JavaScript API.
Before you proceed, please make sure you have read the overview and understand the following:
- [**Renderer**](./overview.md#renderer)
- [**Properties**](./overview.md#properties)
:::info Custom JavaScript
The following JavaScript has to be passed in the `customJS` parameter when initializing Unlayer. **registerTool**, **registerPropertyEditor**, **createViewer** and **createWidget** methods are only available there.
[Learn More](../../customization/appearance/custom-js-css.md#custom-javascript)
:::
## Register your Tool
The first step is to register your custom tool using the `registerTool` method.

```javascript
unlayer.registerTool({
name: 'my_tool',
label: 'My Tool',
icon: 'fa-smile',
supportedDisplayModes: ['web', 'email'],
options: {},
values: {},
renderer: {
Viewer: unlayer.createViewer({
render(values) {
return 'I am a custom tool.';
},
}),
exporters: {
web: function (values) {
return 'I am a custom tool.';
},
email: function (values) {
return 'I am a custom tool.';
},
},
head: {
css: function (values) {},
js: function (values) {},
},
},
validator(data) {
return [];
},
});
```
:::info Plan Limits
The number of custom tools you can register is governed by your plan's Custom Tools
limit. Calling `registerTool` beyond this limit will not make the extra tools
available — they are excluded from the tools panel and a warning is logged to the
browser console. If a design references an over-limit custom tool, the editor renders
a "Not available on your plan" placeholder in its place (with an upgrade link when
applicable) and exports nothing for it. Custom tools within your plan limit are
unaffected. To register more custom tools, upgrade your plan.
:::
It needs some configuration options which are explained below:
| Option | Description |
| :------------------------ | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **name** | Unique name for your tool |
| **label** | Label that users see in the tools panel |
| **icon** | Icon that users see in the tools panel. Use a [Font Awesome icon](https://fontawesome.com/icons?d=gallery) class name, an image URL (including SVG), or inline SVG markup. SVG image URLs do not require explicit `width` or `height` attributes. |
| **supportedDisplayModes** | Which display modes will this tool work in. Default value is `['email', 'web']` |
| **usageLimit** | Optional. You can set a limit to the number of times this tool can be used in a design |
| **options** | This is where we define tool properties and property editors |
| **values** | Initial values for our tool's properties |
| **renderer** | This is where we will add a `Viewer` , `exporters` and `head` |
| **supportedByAI** | Optional. Set to `false` to hide this tool from the AI Assistant |
| **validator** | You can add a validator function to check for issues in the values. For example, you can check values of properties to make sure everything looks correct. These errors/warnings would show up in the Audit tab. [Learn More](../../customization/content-settings/content-audit.md) |
:::info React: Recommended Usage
Unlayer exposes React 19 globally as `unlayer.React` and `unlayer.ReactDOM`. Reusing these globals avoids loading React twice and helps prevent version conflicts. Check our [React Example](https://examples.unlayer.com/custom_tools/react-custom-tool).
For synchronous rendering, create a root, wrap the render in `flushSync`, and read the HTML before unmounting:
```js
const el = document.createElement('div');
const root = unlayer.ReactDOM.createRoot(el);
unlayer.ReactDOM.flushSync(() => {
root.render(element);
});
const html = el.innerHTML;
root.unmount();
return html;
```
`unlayer.ReactDOM.render(element, container)` is still available as a deprecated compatibility shim for existing custom tools, but new code should target React 19+.
:::
---
## Add Tool Properties
Every tool needs certain properties to create content. Properties are variables that the user can modify, such as colors, font sizes, text alignment, images, and more.
Each property is assigned a _property editor_ which is a **UI control widget** used by the user to modify the property value. Check out the list of [built-in property editors](./built-in-property-editors.md).
## Color Picker Example
In this example, we will add 2 properties to our tool under a group called "**Colors**":
1. **Text Color** `textColor`
2. **Background Color** `backgroundColor`

Let's define the property group and both the properties inside it. This will be done in the `options` object. Each property group should have a unique key in options so we will call this group `colors`.
We will name the properties `textColor` and `backgroundColor` and use the [built-in](./built-in-property-editors.md#color-picker) `color_picker` editor widget for both of them. We will give each property a default value of `#FF0000`.
For the Renderer, we will use the `textColor` and `backgroundColor` in the HTML to apply those colors to our template. These properties will be available in the `values` object passed to the Viewer and the exporters.
```javascript
unlayer.registerTool({
name: 'my_tool',
label: 'My Tool',
icon: 'fa-smile',
supportedDisplayModes: ['web', 'email'],
options: {
colors: {
// Property Group
title: 'Colors', // Title for Property Group
position: 1, // Position of Property Group
collapsed: false, // Initial collapse state
options: {
textColor: {
// Property: textColor
label: 'Text Color', // Label for Property
defaultValue: '#FF0000',
widget: 'color_picker', // Property Editor Widget: color_picker
},
backgroundColor: {
// Property: backgroundColor
label: 'Background Color', // Label for Property
defaultValue: '#FF0000',
widget: 'color_picker', // Property Editor Widget: color_picker
},
},
},
},
values: {},
renderer: {
Viewer: unlayer.createViewer({
render(values) {
return `I am a custom tool.`;
},
}),
exporters: {
web: function (values) {
return `I am a custom tool.`;
},
email: function (values) {
return `I am a custom tool.`;
},
},
head: {
css: function (values) {},
js: function (values) {},
},
},
validator(data) {
const { defaultErrors, values } = data;
return [];
},
});
```
### Property Group
Property group is a collapsable panel that is used to organize properties into a group. This makes the experience of editing a template simpler and easier.
The `options` object defines all the property groups and properties available for your custom tool. Here's a breakdown of the available options:
| Option | Description |
| :------------ | :---------------------------------------------------------------- |
| **title** | Title for the property group shown in the panel |
| **position** | Position order of the property group (lower numbers appear first) |
| **collapsed** | This boolean controls the initial collapse state of the group |
| **options** | Contains all properties within this group |
---
## Custom Property Editor
In the example above, we used a built-in `color_picker` property editor. We have many [built-in property editors](./built-in-property-editors.md) available but many times you may want to use a custom property editor that is tightly integrated with your application.
Here's a small example where we add a custom color picker property editor. We'll call it `my_color_picker`. We will use the `registerPropertyEditor` method to register it.

```javascript
unlayer.registerPropertyEditor({
name: 'my_color_picker',
Widget: unlayer.createWidget({
// JSON Schema for Unlayer's AI Assistant support
schema: {
type: 'string',
description: 'Hex color value (e.g. #ff0000)',
},
render(value, updateValue, data) {
return `
Red
Green
Blue
`;
},
mount(node, value, updateValue, data) {
var input = node.getElementsByClassName('color-value')[0];
input.onchange = function (event) {
updateValue(event.target.value);
};
var redButton = node.getElementsByClassName('red')[0];
redButton.onclick = function () {
updateValue('#f00');
};
var greenButton = node.getElementsByClassName('green')[0];
greenButton.onclick = function () {
updateValue('#0f0');
};
var blueButton = node.getElementsByClassName('blue')[0];
blueButton.onclick = function () {
updateValue('#00f');
};
},
}),
});
```
Once our new property editor is registered, you can use it just like the built-in property editors when registering your tool. The configuration options are explained below:
| Option | Description |
| :--------- | :-------------------------------------------------------------------------------------------------------------------------------------------- |
| **name** | Unique slug for your property editor widget. You will have to provide this in `options` as a `widget` when registering your tool. |
| **Widget** | This is the UI widget. If you are using React, this would be a `Component`. If you are using vanilla JavaScript, you will use `createWidget`. |
## Widget
For each property editor, you have to pass a `Widget`. If you are using React, this would be a `Component`. If you are using vanilla JavaScript, you will use the `createWidget` function.
### **JavaScript**
The `unlayer.createWidget` function would be passed an object with the following attributes. You can check the [full example](https://examples.unlayer.com/custom_tools/simple-custom-tool#customtoolwithcustompropertyeditor).
| Attribute | Description |
| :--------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **render** | This is the HTML of your widget. It is passed the following arguments:**value** is the current value of this property**updateValue** is the function to update the value of this property. The first argument has to be the new value, and the second argument is optional data that can be used in the [transformer](./advanced-options/transform-property-values.md) to update values for other properties.**data** is the optional data passed by your application |
| **mount** | This gets called when your widget is mounted. You can attach events to the HTML elements here. It is passed the following arguments:**node** is the DOM ref to the HTML element that you created in the render method.**value** is the current value of this property**updateValue** is the function to update the value of this property. The first argument has to be the new value, and the second argument is optional data that can be used in the [transformer](./advanced-options/transform-property-values.md) to update values for other properties.**data** is the optional data passed by your application |
| **schema** | A [JSON Schema](https://json-schema.org/) object describing the value shape produced by this widget. Used by Unlayer's AI Assistant to understand what fields your custom property editor supports, so it can generate content for your custom tool. |
### **React**
If you are using React, you can create the same widget as a `Component`. You can check the full example [here](https://examples.unlayer.com/custom_tools/react-custom-tool).
```javascript
const MyColorPicker = (props) => {
const { label, labelId, value, updateValue, data } = props;
return (
{label}
updateValue(e.target.value)}
/>
updateValue('#f00')}>
Red
updateValue('#0f0')}>
Green
updateValue('#00f')}>
Blue
);
};
unlayer.registerPropertyEditor({
name: 'my_color_picker',
Widget: MyColorPicker,
});
```
`label` is the property's label and `labelId` the id of its text: render `label`, and reference `labelId` with `aria-labelledby` so screen readers announce the label with your control. Widgets made with `createWidget` get this automatically: the `node` passed to `mount` is a group named by the property label, which the builder keeps hidden. See [Accessibility](../../advanced-configuration/accessibility.md#custom-property-editors).
:::info React: Recommended Usage
Unlayer exposes React 19 globally as `unlayer.React` and `unlayer.ReactDOM`. Reusing these globals avoids loading React twice and helps prevent version conflicts. Check our [React Example](https://examples.unlayer.com/custom_tools/react-custom-tool).
For synchronous rendering, create a root, wrap the render in `flushSync`, and read the HTML before unmounting:
```js
const el = document.createElement('div');
const root = unlayer.ReactDOM.createRoot(el);
unlayer.ReactDOM.flushSync(() => {
root.render(element);
});
const html = el.innerHTML;
root.unmount();
return html;
```
`unlayer.ReactDOM.render(element, container)` is still available as a deprecated compatibility shim for existing custom tools, but new code should target React 19+.
:::
---
## Pass Data to Custom Tools
In some cases, your custom tool will need data from your application instance. You can pass that data when the Unlayer editor is initialized. Inside the `tools` object, you can add the data that your tool needs.
In this example, we will pass user's information. This data will be available in the `values` parameter to your tool's renderer and exporters. If your tool's name is `my_tool`, you will add an object called `custom#my_tool` and pass the `data` object in it. Replace `NAME` with the name of your tool.
You can see a full running example here: [Live Demo](https://examples.unlayer.com/custom_tools/custom-tool-data)
```javascript
unlayer.init({
...
tools: {
'custom#NAME': {
data: {
name: 'John Doe',
age: '27',
photo: 'http://via.placeholder.com/350x150'
}
}
}
});
```
---
## Pass Data to Property Editors
Some property editors need data from your application programmatically. You can pass this data during the initialization.
Replace `NAME` with your tool's `name` and `PROPERTY-NAME` with the property's `name`. For example, if your tool's name is `my_color_picker` and property name is `colorOptions`, you will use `custom#my_color_picker` as the key and `colorOptions` as the property name.
You can see a full running example here: [Live Demo](https://examples.unlayer.com/custom_tools/custom-tool-data)
```javascript
unlayer.init({
...
tools: {
'custom#NAME': {
properties: {
PROPERTY-NAME: {
editor: {
data: {
"hello": "world"
}
}
}
}
}
}
});
```
### **Dropdown Example**
Let's say your custom tool has a property that needs to use our built-in dropdown property editor. You can use the following example to pass options to the dropdown property editor.
In this example, our tool's name is `contact_form` and our property's name is `department` which is using a dropdown editor. We want the user to pick Sales, Customer Support, HR or Other from the dropdown.
You can see a full running example here: [Live Demo](https://examples.unlayer.com/custom_tools/custom-tool-data)
```javascript
unlayer.init({
...
tools: {
'custom#contact_form': {
properties: {
department: {
editor: {
data: {
options: [
{label: "Custom Support", value: "Customer Support"},
{label: "Sales", value: "Sales"},
{label: "HR", value: "HR"},
{label: "Other", value: "Other"}
]
}
}
}
}
}
}
});
```
---
## Full Example
We have a full example of custom tools and custom property editors with the JavaScript API in our playgrounds. [Check it out here](https://examples.unlayer.com/custom_tools/simple-custom-tool).
---
## Custom Tools
## What is a Custom Tool?
Custom tools are user-defined elements that extend the default functionality of the visual builder, allowing developers to create unique design components tailored to their specific needs. Unlike built-in tools, custom tools offer complete flexibility in terms of appearance, behavior, and interactivity. Developers can define how these tools behave, including custom properties, actions, and styling options.
Custom tools integrate seamlessly into the editor’s interface, enabling users to drag, drop, and configure them just like built-in tools. This allows for advanced customization, supporting a wide range of use cases from specialized content elements to custom workflows. We know that every application is different and needs different tools to reach its full potential.

Every custom tool needs to have the following attributes to get running.
| Attribute | Description |
| :-------------------------- | :------------------------------------------------------------------ |
| **Name** | A unique identifier string for your tool |
| **Label** | A display label for your tool that the users will see |
| **Icon** | An icon for your tool from a choice of 700+ icons or a custom image |
| **Supported Display Modes** | Display mode this tool will work in (**email**, **web** or both) |
| **Usage Limit** | Number of times a tool can be used in a single design |
| **Renderer** | Renderer contains the content that the tool will create and export |
| **Properties** | A set of variables that your tool will need to create content |
---
## **Renderer**
Renderer is where you define the content that your tool will create. This is done using a HTML template. Each renderer consists of a Viewer, Exporters and Head. In most cases, Viewer and Exporters contain the same HTML template but there are cases when these could be different.
### Viewer
Viewer is the tool's template which will be visible to the user when they use your tool within the Unlayer editor.
### Exporters
Exporters define the tool's HTML template which will be passed to your application when you call [exportHtml](../../get-started/export/export-html.md). Depending on your supported display modes, each tool can have these 2 exporters:
- Email
- Web
This reflects what the output should be for each of the 2 display modes. HTML markup for email can be very different from a web page so this is where you can have the same tool working nicely for both display modes.
### Head
Head is where you define any CSS or JavaScript that the tool will need to function. As the name says, these assets will be added to the `` part of HTML. [Learn more](./advanced-options/css-javascript.md)
---
## Properties
Every tool needs certain properties to create content. Properties are variables that the user can modify, such as colors, font sizes, text alignment, images, and more.
### Property Group
Property group is a collapsable panel that is used to organize properties into a group. This makes the experience of editing a template simpler and easier.

### Property Editor
Each property is assigned a property editor which is a **UI control widget** used by the user to modify the property value. For example: color picker, slider, toggle, etc. We have many [built-in property editors](./built-in-property-editors.md) available, and you can also create a [custom property editor](./create-custom-tool.md#custom-property-editor).

---
## Tools
Tools are the core building blocks within the drag-and-drop builder that allow users to create and customize content. Each tool represents an individual design element, such as text, buttons, images, or headings, that can be easily added to an email, page, or popup. Tools provide essential functionality and design capabilities, enabling users to visually construct their content without writing code.
These tools are pre-configured with default settings but offer a range of customization options. Users can modify their appearance, behavior, and interactions to suit specific design requirements and business needs. Additionally, developers can extend these tools by creating [custom tools](./custom-tools/overview.md), giving even more flexibility to tailor the design experience.
## Enable / Disable Tools
You can choose which tools to enable or disable for the Unlayer editor instance.
Here's some examples...
### Disable Image Tool
```javascript
unlayer.init({
tools: {
image: {
enabled: false,
},
},
});
```
---
## Reposition Tools
You can reposition tools to appear before or after other tools.
```javascript
unlayer.init({
tools: {
image: {
position: 1,
},
},
});
```
---
## Usage Limit
You can specify a limit to how many times a tool can be used in a single design. For example, if you want the form to be used only once in a design, you can do this:
```javascript
unlayer.init({
tools: {
form: {
usageLimit: 1,
},
},
});
```
---
## Change Icon
You can change the icon of any tool. For example, if you want to change the icon of image tool, you can do this:
```javascript
unlayer.init({
tools: {
image: {
icon: '[IMAGE URL HERE]',
},
},
});
```
`icon` accepts an image URL, inline SVG markup, or a [Font Awesome](https://fontawesome.com/icons) icon name:
```javascript
unlayer.init({
tools: {
image: {
icon: 'fa-camera',
},
},
});
```
For built-in tools, the icon you set applies to every theme, classic themes included.
### Different Icons Per Theme
Classic themes ship their own set of default tool icons, kept from before the modern themes were introduced. If you want a different icon in classic themes specifically, set `classicIcon` alongside `icon`:
```javascript
unlayer.init({
appearance: {
theme: 'classic_light',
},
tools: {
image: {
icon: 'fa-camera',
classicIcon: 'fa-image',
},
},
});
```
`classicIcon` is optional and takes the same values as `icon`. It is only used by classic themes — `classic_light`, `classic_dark`, and any custom theme that extends one of them. Modern themes always use `icon`.
`classicIcon` also works on [custom tools](./custom-tools/overview.md), where you set it in the `unlayer.registerTool({ … })` call. Note that a `classicIcon` you register this way is yours, so it keeps applying in classic themes even if you later override only `icon` through `unlayer.init`. To change a custom tool's classic icon, override `classicIcon` too.
---
## Built-In Tools
Our platform provides a variety of pre-configured, easy-to-use tools that empower your users to design and customize their content seamlessly. These built-in tools offer essential elements for creating emails, pages, and popups without the need for coding. Each tool is highly customizable, allowing you to adapt them to match your application’s design and user preferences. [Learn More](./built-in-tools/overview.md)
---
## Custom Tools
A custom tool can help you add more content elements to the editor. [Learn more](./custom-tools/overview.md) on how to build a custom tool.

---
## Custom JS / CSS
The builder runs inside an iframe, which allows developers to customize its appearance and behavior using custom JavaScript and CSS. You can pass both custom JS and CSS during the builder's initialization. This feature is particularly useful for adjusting the builder's look and feel or extending its functionality with custom tools and custom property editors.
---
## Custom CSS
Custom CSS allows you to make design tweaks to the builder. It's useful for branding, adjusting layouts, and styling the builder interface to fit your application's design language.
:::info String or Array
`customCSS` accepts a string or an array of strings
:::
To add custom CSS to the builder, pass a CSS string or URL to the customCSS option when initializing the builder.
```javascript
unlayer.init({
customCSS: 'https://example.com/custom-styles.css',
});
```
Or, you can pass the CSS source code like this:
```javascript
unlayer.init({
customCSS: [
"
body {
background-color: yellow;
}
"
]
});
```
### Use Cases for Custom CSS
- **Branding**: Customize colors, fonts, and layouts to match your application.
- **Appearance Tweaks**: Adjust margins, paddings, and sizes to fit your design.
- **Custom Tool Styling**: Style custom tools or custom property editors for consistency with your app's UI.
---
## Custom JavaScript
Custom JavaScript allows developers to extend the functionality of the builder by creating custom tools, custom property editors, or handling additional events inside the iframe. Unlayer's SDK supports advanced methods like `unlayer.registerTool()` and `unlayer.registerPropertyEditor()` to enable these custom features. These methods are only available inside the iframe.
:::info String or Array
`customJS` accepts a string or an array of strings
:::
You can pass custom JavaScript to the builder using the `customJS` property during initialization. The custom JavaScript will run inside the iframe, allowing you to register new tools, modify existing ones, or add new property editors.
```javascript
unlayer.init({
customJS: '//cdn.muicss.com/mui-0.9.28/js/mui.min.js',
});
```
Or, you can pass the JS source code like this:
```javascript
unlayer.init({
customJS: [
"
console.log('I am custom JS!');
"
]
});
```
### Key Methods for Custom JavaScript
- **unlayer.registerTool()**
This method is used to create custom tools that appear in the builder's toolbox. You can define the behavior, properties, and UI of the custom tool. [Learn More](../../tools/custom-tools/overview.md)
- **unlayer.registerPropertyEditor()**
This method allows you to create custom property editors for tools. Custom property editors allow users to input data and modify the behavior or content of a tool. [Learn More](../../tools/custom-tools/overview.md)
---
### Use Cases for Custom JavaScript
- **Custom Tools**: Build tools tailored to your end-users, such as special forms, custom buttons, or complex layout elements.
- **Property Editors**: Add custom input fields or property editors to allow users to customize the behavior and appearance of the custom tools.
- **Event Handling**: Handle custom events or extend the functionality of existing tools by reacting to actions taken by the end-users.
---
## Examples
You can see a few examples of Custom JS and Custom CSS in the [Examples & Playground](https://examples.unlayer.com).
---
## Layout
The layout options allow developers to configure the layout of the builder's tool panels, ensuring that the user interface can be customized to fit the needs and preferences of your end-users.
These options give you control over where the tool panel is positioned and whether it can be collapsed, providing flexibility in how the builder interface is structured.
## Tools Position
By default, the tool panel is positioned on the right side of the builder. However, you can change the position of the panel to better fit your layout needs.
### Setting Panel Position
You can control the position of the tool panel using the dock option. The tool panel can be docked either on the right or the left side of the builder interface.
#### Docking Options
- **right** (default)
- **left**
Example of docking the panel on the right (default):
```javascript
unlayer.init({
appearance: {
panels: {
tools: {
dock: 'right',
},
},
},
});
```
To dock the panel on the left:
```javascript
unlayer.init({
appearance: {
panels: {
tools: {
dock: 'left',
},
},
},
});
```
## Collapsible Panel
This feature allows you to enable or disable the ability to collapse the tool panel. By default, the tool panel is collapsible, meaning users can hide or show the panel as needed to create more space while designing.
### Enable or Disable Collapsing
You can control whether the tool panel is collapsible using the collapsible option. When set to`false`, the tool panel will remain fixed and cannot be collapsed.
Example of disabling collapsibility:
```javascript
unlayer.init({
appearance: {
panels: {
tools: {
collapsible: false,
},
},
},
});
```
---
## Best Practices
- **User Flexibility**: Consider keeping the collapsible feature enabled (collapsible: true) to allow users to create more space while designing, especially on smaller screens.
- **Docking Position**: Position the tool panel on the side that best fits your application's layout and design. The default right-side docking works well for most users, but left-docking may be preferable depending on the design flow or user preferences.
- **Responsive Design**: When positioning the panel or making it collapsible, ensure that the layout works well across different devices.
By customizing the layout options, developers can create a more user-friendly and adaptable interface for the builder, providing flexibility in how the tool panel is displayed and used.
---
## Loading Spinner
This feature allows you to replace the default loading spinner in the builder with a custom one, either using an animated image or an HTML/CSS-based loader. This gives you flexibility to match the builder’s loading animation with your application’s branding or user interface design.
### Animated Image
You can replace the default loader with a custom animated image (such as a GIF or PNG). This is useful if you have a branded or pre-designed loading spinner image.
```javascript
unlayer.init({
appearance: {
loader: {
url: 'https://example.com/loader.gif', // URL of the custom loading spinner image
},
},
});
```
In this example, the loading spinner will display the image from the provided URL whenever the builder is loading.
---
### CSS Loader
If you prefer to create a fully customized loader using HTML and CSS, you can provide the structure and styling for the loader directly in the configuration. This approach gives you full control over the design and animations of the loading spinner.
```javascript
unlayer.init({
appearance: {
loader: {
html: '', // HTML structure for the loader
css: '.custom-spinner { color: red; }', // CSS styling for the loader
},
},
});
```
In this example, the custom loader will display a red spinner as defined by the HTML and CSS. You can create complex loaders using animations or any design that fits your needs.
---
## Best Practices
- **Branding**: Use a custom loader that aligns with your brand’s identity. Whether using an animated image or custom HTML/CSS, ensure that the design is consistent with your application’s overall look and feel.
- **Performance**: When using an animated image, ensure that the file size is optimized to avoid slow loading times. For HTML/CSS loaders, avoid overly complex animations that could impact performance.
- **Testing Across Devices**: If you are using a CSS loader, test the design across different devices and screen sizes to ensure it behaves and renders correctly, especially on mobile and tablets.
---
## Appearance
This section allows developers to configure how the builder itself looks and feels. This section focuses on the visual presentation and layout of the builder interface, providing customization options to match your brand or enhance the user experience.
In this section, you can:
- **Themes & Layouts**: Choose themes and layouts for the builder interface, allowing you to adjust its overall appearance to suit your application’s design style.
- **Custom CSS/JS**: Add custom styles or scripts to further tailor the builder’s appearance, ensuring it aligns with your brand’s look and feel.
- **Design Tweaks**: Make small adjustments to the builder’s UI elements, enhancing the user interface to provide a smoother editing experience.
By configuring the builder’s appearance, you can provide a visually cohesive and user-friendly environment for your end-users, ensuring that the design and layout of the builder are consistent with your platform’s branding and usability standards.
---
## Themes
This feature allows you to customize the overall look and feel of the drag-and-drop builder interface. We offer four out-of-the-box themes that can be easily applied to the builder, giving you the flexibility to choose between light and dark modes as well as different design styles. You can also pass a custom theme object to override the editor colors with your own.
## Available Themes
### **Modern Light** – _Default_
#### `modern_light`
A more contemporary design with light tones, providing a fresh and minimalist feel while maintaining clarity and usability. This is the default theme.
### **Modern Dark** {#dark-mode}
#### `modern_dark`
A darker, modern interface that combines a sleek design with a minimalistic feel, ideal for users who prefer dark mode with a modern touch.
### **Classic Light**
#### `classic_light`
A clean, traditional interface with a light background, designed for clarity and simplicity.
### **Classic Dark**
#### `classic_dark`
A darker version of the classic theme, ideal for users who prefer a low-light interface or want a more modern, sleek look.
---
## Setting a Theme
You can configure the theme for the builder during initialization using the `unlayer.init()` method. By default, the builder is set to the Classic (Light) theme, but you can easily switch to any of the available themes.
Example of setting a theme:
```javascript
unlayer.init({
appearance: {
theme: 'modern_light',
},
});
```
Or you can change the theme on the fly like this:
```javascript
unlayer.setTheme('modern_dark');
```
#### Built-in Theme Options
- modern_light (default)
- modern_dark
- classic_light
- classic_dark
---
## Custom Themes
Instead of passing a string with the theme name, you can pass an object overriding the editor colors. Here's how you create a custom Modern Dark Purple theme:
```js
unlayer.init({
appearance: {
theme: {
name: 'custom_modern_dark_purple',
extends: 'modern_dark',
isClassic: false,
isDark: true,
mapping: {
borderRadius: {
none: '0',
min: '2px',
mid: '8px',
max: '12px',
full: '50%',
},
colors: {
accent_01: '#9632a0',
accent_02: '#ae70b4',
accent_03: '#bf87c4',
accent_04: '#d9b4dc',
accent_05: '#eed5f0',
primary_01: '#ffffff',
primary_02: '#f2ebf4',
primary_03: '#e8dded',
primary_04: '#d2c2d6',
primary_05: '#9c95a6',
primary_06: '#906994',
primary_07: '#5d425c',
primary_08: '#4f344d',
primary_09: '#3c263d',
primary_10: '#4e2e51',
primary_11: '#441e42',
},
},
},
},
});
```
Or you can change the theme on the fly like this:
```js
unlayer.setTheme(myCustomThemeObject);
```
### Custom JS / CSS
If the out-of-the-box themes don't fully meet your needs, or you want to customize some very specific UI element, you can use the [Custom JS / CSS](./custom-js-css.md) options. This gives you further control to tweak the existing themes or create a completely new look that fits your brand.
---
## Best Practices
- **Consistency with Your Brand**: Choose the theme that best aligns with your platform's overall design and user experience. You can also apply custom branding elements via CSS to make the builder interface feel more integrated with your application.
- **Light vs. Dark Mode**: Offering both light and dark themes provides users with a more personalized experience. You can also allow users to switch between themes based on their preferences, enhancing accessibility and comfort, especially in low-light environments.
By utilizing this feature, you can create a visually appealing and cohesive environment for your users, ensuring that the builder interface matches your application's aesthetic while providing a comfortable and flexible design experience.
---
## Body Values
You can programmatically set values for the **Body** panel options.
```javascript
unlayer.setBodyValues({
backgroundColor: '#e7e7e7',
contentWidth: '500px', // or percent "50%"
fontFamily: {
label: 'Helvetica',
value: "'Helvetica Neue', Helvetica, Arial, sans-serif",
},
preheaderText: 'Hello World',
});
```
# Default Body Values
You can set default values for the **Body** panel options.
### Text Color
```javascript
unlayer.init({
tools: {
bodies: {
properties: {
textColor: {
editor: {
defaultValue: '#ff0000',
},
},
},
},
},
});
```
---
### Background Color
```javascript
unlayer.init({
tools: {
bodies: {
properties: {
backgroundColor: {
editor: {
defaultValue: '#ff0000',
},
},
},
},
},
});
```
---
### Font Family
```javascript
unlayer.init({
tools: {
bodies: {
properties: {
fontFamily: {
editor: {
defaultValue: {
value: "'Open Sans',sans-serif",
},
},
},
},
},
},
});
```
---
### Content Alignment
```javascript
unlayer.init({
tools: {
bodies: {
properties: {
contentAlign: {
editor: {
defaultValue: 'center',
},
},
},
},
},
});
```
---
### Font Weight
```javascript
unlayer.init({
tools: {
bodies: {
properties: {
fontWeight: {
editor: {
defaultValue: 700,
},
},
},
},
},
});
```
---
## Disable Columns
This feature allows developers to configure the builder to remove the ability to create or edit multi-column blocks. When columns are disabled, blocks will be restricted to a single column, hiding the Columns tool and any multi-column layout options from the editing panel and the Blocks tab. This ensures that all created content will follow a single-column structure, which can be useful for simplifying designs or following specific layout constraints.
## How It Works
When the columns feature is disabled, the following changes occur:
- The **Columns** tool is removed from the builder's toolbar.
- The ability to add multi-column blocks is disabled.
- Only single-column blocks will be available in the Blocks tab.
## Enabling the Feature
To disable columns, you need to configure the builder by passing the `columns: false` option within the editor configuration. This can be done when initializing the builder.
Example: Disabling Columns
```javascript
cy.loadEditor({
editor: {
columns: false,
},
});
```
In this configuration:
- `columns: false` disables the columns feature, ensuring that only single-column blocks are allowed in the editor.
## Use Case
This feature is useful for applications or use cases where multi-column layouts are not desired or needed. For instance:
- **Mobile-First Designs**: If your design is primarily targeting mobile devices, single-column layouts are typically preferred for readability and simplicity.
- **Simplified User Experience**: Removing the complexity of multi-column blocks can simplify the builder experience for less experienced end-users.
- **Strict Design Guidelines**: If your application enforces strict design guidelines that mandate single-column layouts, this option will ensure that no multi-column blocks are created.
---
## Columns(Columns)
Columns are a fundamental part of the builder's layout system. They allow end-users to organize content in flexible, responsive grids, making it easy to design structured layouts for emails, web pages, or popups. Columns divide the available space in a block into separate sections, where different content elements like text, images, or buttons can be placed.

## How Columns Work
The builder operates on a 12-column grid system. This means that the width of the entire row is divided into 12 equal parts, and you can allocate any number of these parts to a column. The sum of all column widths within a block must always equal 12, ensuring the content fits perfectly into the layout.
## Example Layouts
Here are some examples of how columns can be used in the builder:
- **Single Column Layout**: Takes up the full width (12/12 columns).
- **Two Column Layout**: You can divide the row into two equal parts, each column taking up 6 parts of the grid (6/12 + 6/12).
- **Three Column Layout**: Three columns can be defined with equal or unequal widths, as long as the total is 12 (e.g., 4/12 + 4/12 + 4/12 or 3/12 + 3/12 + 6/12).
## Flexibility in Design
Columns provide immense flexibility in how content is displayed. You can:
- **Organize content** into distinct sections side-by-side (like text next to an image).
- **Create complex layouts** with varying column sizes to suit your design needs.
- **Ensure responsiveness** by stacking columns on smaller screens, such as mobile devices, where the content is automatically adjusted to fit the screen width.
## Managing Columns in the Builder
In the builder, end-users can easily manage columns. They can:
- **Add or remove columns** to structure their layout.
- **Resize columns** by adjusting the width of each section using the drag handles.
- **Reorder content** within columns by dragging and dropping elements between them.
### Predefined Columns
The predefined columns feature allows developers to add default blocks with specific column configurations to the builder. [Learn More](./predefined-columns.md)
### Disable Columns
This feature allows developers to configure the builder to remove the ability to create or edit multi-column blocks. [Learn More](./disable-columns.md)
### Locking columns
When on Editor Mode, you can mark individual columns as "Locked" or "Non Deletable" to prevent your users from removing them from the template or editing their content. [Learn More](../templates/permissions)
---
## Predefined Columns
The predefined columns feature allows developers to add default blocks with specific column configurations to the builder. This feature uses the `registerColumns` function to create blocks with fixed column sizes. Each block can contain up to 12 columns, and the sum of the column sizes must always equal 12.
This feature provides flexibility to design pre-configured blocks that can speed up the design process for end-users and ensure layouts follow certain guidelines.
We have a few pre-built blocks available with different column sizes. You can add your own blocks with custom column sizes.

## How It Works
The `registerColumns` function accepts an array of numbers as a parameter. The array defines the column sizes for a block. Each number represents the width of a column, and the sum of these numbers must always equal 12, as the builder's grid system is based on 12 columns.
## Basic Usage
To create a custom block with predefined columns, call the `unlayer.registerColumns()` function and pass an array that defines the column widths.
### Example: 4 Columns
In this example, we will create a block with 4 columns:
- The first and last columns will each take 2 parts of the grid (smaller).
- The two middle columns will each take 4 parts of the grid (bigger).
```javascript
unlayer.registerColumns([2, 4, 4, 2]);
```
This results in a block with the following layout:

### Example: 3 Columns
In this example, we will create a block with 3 columns:
- The first two columns will each take 3 parts of the grid.
- The last column will take 6 parts of the grid.
```javascript
unlayer.registerColumns([3, 3, 6]);
```
This results in a block with the following layout:

---
## Guidelines for Using registerColumns
- **Grid System**: The builder's grid system is based on 12 columns. This means that the sum of the numbers in the array passed to registerColumns must always equal 12.
- **Column Flexibility**: You can define columns of varying sizes, but they must fit within the 12-column grid.
- **Customization**: Developers can use this feature to provide end-users with pre-configured layouts that suit specific use cases or design guidelines.
---
## Practical Use Cases
Here are some scenarios where pre-defined columns in blocks can be useful:
- **Standardized Layouts**: Ensure that end-users follow predefined layout structures for brand consistency.
- **Design Templates**: Speed up the design process by providing commonly used column configurations as ready-to-use blocks.
- **Responsive Design**: Define column sizes that adapt well to different screen sizes, especially when targeting mobile or tablet devices.
---
## Content Audit
The Audit tab flags common issues so you can address them before finishing your email or page design. It currently looks for accessibility checks so you can identify and fix common issues during the design process. It addresses:
- Missing alternate text for images
- Missing links in buttons or menus
- Missing image URLs
As an added bonus, by using the Audit tab and learning from the issues it flags, you can become more practiced and aware of these considerations so they’re part of your design and development workflow instead of an afterthought.
---
## Enable / Disable
You can enable or disable this feature.
```javascript
unlayer.init({
features: {
audit: true,
},
});
```
---
## Custom Validators
If you want to run the content for other types of issues, you can create custom validators.
:::info Availability
Custom validators require a plan that includes the Custom Audit Validators feature. See [pricing](https://unlayer.com/pricing).
Without it, validators set with `unlayer.setValidator`, `unlayer.setToolValidator`, the `validator` option of `unlayer.init`, or a tool override's `validator` are skipped, and only the built-in audits run. The editor logs one console warning when it skips a validator. A custom tool's own validator, passed to `unlayer.registerTool`, is part of the custom tool and keeps running.
:::
### Global Validator
A global validator can be used to identify general design issues. For example, if you want to run and analyze the content for potential spamminess.
```javascript
unlayer.setValidator(function (data) {
const { html, design, defaultErrors } = data;
return [
{
id: 'DESIGN_CUSTOM_ERROR',
icon: 'fa-smile',
severity: 'WARNING',
title: 'This is a custom error',
description:
'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce pretium non lectus venenatis lacinia. Fusce vitae venenatis nibh. Sed laoreet ornare lorem, a convallis nibh suscipit eu. Ut dictum commodo velit vitae interdum.',
},
].concat(defaultErrors);
});
```
Each error needs to have the following parameters.
| Name | Description |
| :-------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **id** | A unique ID for the error type |
| **icon** | Icon that users see in the errors tab. The value can be class name of any [fontawesome icon](https://fontawesome.com/icons), or a URL for your icon's image |
| **severity** | `ERROR` or `WARNING` |
| **title** | Title of the error message |
| **description** | Description of the error message |
---
### Tool Validator
Similar to the global validator, you can also create custom validators for different tools. This can be done for built-in tools, as well as custom tools, using 'custom#tool_name' as the first argument. These validators can check and validate different values of the tools' properties.
Here's an example of attaching a validator to the `button` tool.
```javascript
unlayer.setToolValidator('button', function (data) {
const { defaultErrors, values } = data;
return [
{
id: 'CUSTOM_ERROR',
icon: 'fa-smile',
severity: 'WARNING',
title: 'This is a custom button error',
description: `Lorem ipsum dolor sit amet ${values?.text}.`,
},
].concat(defaultErrors);
});
```
### Translations (i18n) for Validators
The title and description for each error can include translated text to keep it i18n compliant. You can read more about our [localization](../../advanced-configuration/localization.md).
```javascript
unlayer.init({
translations: {
en: {
custom_translation_title: 'This is a custom title',
custom_translation_desc: 'This is a custom description.',
},
},
});
unlayer.setToolValidator('button', function (data) {
return [
{
id: 'CUSTOM_ERROR',
icon: 'fa-smile',
severity: 'WARNING',
title: 'custom_translation_title',
description: 'custom_translation_desc',
},
];
});
```
---
## Check Status
You can check if there are any active errors or warnings in the design by using the following method.
```javascript
unlayer.audit(function (data) {
console.log(data);
// {
// status: "PASS",
// errors: [],
// }
// {
// status: "FAIL",
// errors: [{...}],
// }
});
```
---
## Spam Example
Here's an async example where you can use an external API to check your content for spam.
```javascript
unlayer.setValidator(async (data) => {
const { html, design, defaultErrors } = data;
const errors = [];
// Check HTML for spamminess using a third-party API
const isSpammy = await isHtmlSpammy(html);
if (isSpammy) {
errors.push({
id: 'SPAM_ERROR',
icon: 'fa-image',
severity: 'WARNING',
title: 'Content is Spammy',
description: 'The content seems to be spammy. Fix your content.',
});
}
return errors.concat(defaultErrors);
});
```
---
## Headers and Footers
Unlayer provides built-in Header and Footer Support, allowing designs to be divided into clearly defined sections: Header, Content and Footer. This helps end-users structure their designs more logically, simplifies template creation, and ensures better consistency across designs.
When enabled, the editor visually highlights the Header and Footer areas inside the canvas with distinct indicators, making it easy for users to understand which part of the content they are working on.
## Key Benefits
- **Clear Visual Separation**: Dedicated header and footer areas are displayed at the top and bottom of the design canvas.
- **Improved Design Consistency**: Helps enforce structural best practices across all designs.
- **Simplifies Template Creation**: End-users can easily place branding, navigation, and legal information in appropriate sections.
- **Stored in Design JSON**: The header/footer structure is fully preserved in the design data model.
## Enabling Headers and Footers
You can enable this feature by passing a feature flag during initialization:
```javascript
unlayer.init({
features: {
headersAndFooters: true,
},
});
```
Once enabled:
- The editor will display Header and Footer sections with visible labels.
- Users can independently add content inside each section using the existing tools.
- Content added inside the Header or Footer remains logically grouped in the design JSON.
## Design Behavior
- **Header**: Shown at the top of the canvas, ideal for logos, navigation, or branding elements.
- **Content**: All content between header and footer remains fully editable.
- **Footer**: Shown at the bottom, ideal for legal disclaimers, contact details, unsubscribe links, etc.
## Notes
- This feature only modifies the editor interface and design structure; exported outputs remain as standard HTML or PDF content.
- In Document Builder, headers and footers repeat on every page and use the printable dimensions of the selected page size and orientation, matching the canvas.
- Repeated Document Builder headers and footers require a plan that includes both Header and Footer Support and repeated headers and footers in documents. This requirement doesn't change header and footer behavior in email or web mode.
- When disabled, the editor operates as a single continuous body without any section divisions.
---
## Min / Max Rows
You can set a limit of minimum and maximum rows that can be added in the editor. This is particularly useful in some cases where you want to restrict the number of rows.
```javascript
unlayer.init({
editor: {
minRows: 1,
maxRows: 2,
},
});
```
---
## Content Settings
This section allows you to configure essential aspects of the content structure and layout within the designs. These settings give developers control over the default styles and behaviors of content, ensuring a consistent experience for end-users.
Through this section, you can:
- **Set Default Body Values**: Define the default background color, font family, content width, and preheader text to ensure brand consistency across all templates.
- **Page Anchors**: Enable users to define sections of a page and create internal links, making it easy to link buttons or text to specific areas of the design.
- **Custom Column Sizes and Row Limits**: Configure default column sizes and set minimum or maximum rows allowed in your designs.
By configuring these settings, developers can ensure that the content structure is well-organized, flexible, and tailored to the specific needs of their users, while maintaining consistency across different templates.
The following editor options are available:
---
## Page Anchors
:::warning
Page anchors are not available when AMP is enabled.
:::
This is a great feature for linking within a page. It lets users define sections of a page and then link buttons or links to those sections.

You can enable this using the following code.
```javascript
unlayer.init({
features: {
pageAnchors: true,
},
});
```
---
## Page Title
You can pass a custom title to the `unlayer.exportHtml()` method to set the title of the exported HTML during the export process.
```javascript
unlayer.exportHtml(console.log, { title: 'Exported HTML Title' });
```
---
## Preheader Text
If you are using the **email builder**, end-users can set a preheader. A preheader is the short summary text that follows the subject line when viewing an email from the inbox.
By default, preheader text is turned on. If you want to disable it, you can turn it off.
```javascript
unlayer.init({
features: {
preheaderText: false,
},
});
```
---
## Auto Select On Drop
When a user drags and drops a tool in their design, the default behavior is not to automatically select the tool and show its properties in the editor panel. If you turn this option to `true`, it will automatically select the tool when it's dropped.
```javascript
unlayer.init({
editor: {
autoSelectOnDrop: true,
},
});
```
---
## Blank Design
The editor loads with a blank design by default. You can use this function to reset the design to blank state and let the user can start from scratch.
You can also specify a background color for the body here.
```javascript
unlayer.loadBlank({
backgroundColor: '#e7e7e7',
});
```
---
## Confirm On Delete
When a user deletes any content in their design, the default behavior is not to show a confirmation message. If you have the [Undo / Redo](./undo-redo.md) feature turned off, then you may want to enable this feature.

You can enable this feature by passing the following parameter to your initialization code.
```javascript
unlayer.init({
editor: {
confirmOnDelete: true,
},
});
```
---
## Editor Behavior
This section allows you to configure how the editor operates and responds to user interactions. These settings give developers control over the editor's functionality, ensuring a smooth, intuitive user experience while working with the drag-and-drop interface.
By fine-tuning these behavior settings, you can optimize how the editor functions for your end-users, ensuring it behaves consistently with their expectations and workflows.
The following editor options are available:
---
## Preview Designs
This feature allows end-users to toggle between viewing their design in mobile, tablet or desktop mode, ensuring responsiveness and compatibility across different devices. It also allows end-users to view their emails in different email clients to ensure email client compatibility. This feature can be controlled programmatically, hidden, or customized to show dynamic content through custom HTML.
## Enable or Disable
By default, the preview icon is visible in the actions bar, but you can choose to hide it using the `unlayer.init()` configuration.
Example:
```javascript
unlayer.init({
features: {
preview: false, // Disable mobile/desktop preview icons
},
});
```
Setting `preview: false` will hide the preview toggle icons in the editor’s actions bar.
---
## Programmatically Controlling Preview Mode
You can also show or hide the preview mode programmatically, allowing developers to control when the preview is shown and which device mode (mobile or desktop) is active.
### Show Desktop Preview
```javascript
unlayer.showPreview('desktop');
```
This method open the preview in desktop mode, showing how the design will look on a desktop screen.
### Show Mobile Preview
```javascript
unlayer.showPreview('mobile');
```
This method open the preview in mobile mode, showing how the design will look on a mobile device.
### Hide Preview
```javascript
unlayer.hidePreview();
```
This method hides the preview mode, returning the user to the normal editing interface.
---
## Custom Device Resolutions
You can customize the available device resolutions options in the preview mode by defining custom resolutions with specific dimensions. This allows you to test your designs at exact viewport sizes that match your target devices or breakpoints.
### Basic Device Resolutions Example
```javascript
unlayer.init({
features: {
preview: {
enabled: true,
deviceResolutions: {
showDefaultResolutions: true, // Show built-in device options
customResolutions: {
desktop: [
{ value: 1000, name: 'Medium Desktop' },
{ value: 1440, name: 'Large Desktop' },
],
tablet: [
{ value: 500, name: 'Small Tablet' },
{ value: 768, name: 'iPad Portrait' },
],
mobile: [
{ value: 300, name: 'Small Mobile' },
{ value: 375, name: 'iPhone X' },
],
},
},
},
},
});
```
Custom device resolutions can be organized into three categories:
| Category | Description |
| :---------- | :---------------------------------------------- |
| **desktop** | Large screen devices (typically > 768px) |
| **tablet** | Medium screen devices (typically 768px - 480px) |
| **mobile** | Small screen devices (typically < 480px) |
Each custom device resolution object supports the following properties:
| Option | Description |
| :-------- | :-------------------------------------------- |
| **value** | The viewport width in pixels (number) |
| **name** | The display text shown in the device dropdown |
### Hide Default Resolutions
If you want to show only your custom device resolutions and hide the default ones:
```javascript
unlayer.init({
features: {
preview: {
enabled: true,
deviceResolutions: {
showDefaultResolutions: false, // Hide built-in device options
customResolutions: {
desktop: [
{ value: 1920, name: 'Full HD Desktop' },
{
value: 1366,
name: 'Standard Desktop',
},
],
tablet: [
{ value: 1024, name: 'iPad Pro 11"' },
{ value: 912, name: 'Surface Pro' },
],
mobile: [
{ value: 390, name: 'iPhone 14' },
{ value: 360, name: 'Samsung Galaxy S23' },
],
},
},
},
},
});
```
---
## Customizing Preview with Custom HTML
In cases where you want to control what is displayed in preview mode, you can use custom HTML. This is especially useful if you’re using a templating library to render dynamic content in the preview mode.
To achieve this, you can register a callback function using the `unlayer.registerCallback()` method and pass your custom HTML to the preview mode.
```javascript
unlayer.registerCallback('previewHtml', function (params, done) {
// You can manipulate the params.html here or replace it with custom HTML
done({
html: params.html, // you can pass your custom html here
});
});
```
This allows you to fully control what the preview mode renders, whether it’s static content or dynamic content parsed through a templating engine.
---
## Best Practices
- **Device Compatibility**: It’s recommended to keep the preview functionality enabled so users can switch between mobile and desktop views to ensure their design is responsive.
- **Custom Previews for Dynamic Content**: When rendering dynamic or personalized content, use the custom HTML feature to show how the final design will look in preview mode. This ensures the template renders accurately with real data.
By leveraging the preview feature, developers can provide end-users with a powerful tool to ensure that their designs are responsive across all devices, while maintaining the flexibility to customize and control how previews are displayed programmatically.
---
## Responsive Controls
In modern web design, managing responsiveness is crucial, especially when dealing with content layouts that need to adapt across different devices. Unlayer builder provides a few important features to help developers and end-users manage responsiveness in their designs:
- **Do Not Stack on Mobile**: By default, columns in a block are set to stack on mobile devices for a better user experience. End-users have the option to change this setting for each block.
- **Reverse Stacking on Mobile**: When columns stack, this option places the last column first. Select a row in mobile view to turn it on. It is off by default, and **Do Not Stack on Mobile** takes precedence.
- **Hide on Mobile**: Allows specific content to be hidden on mobile devices, improving control over mobile layouts.
By default, these options come with preset values, but developers can customize the default settings to suit the needs of their applications.
Email exports use separate desktop and mobile layouts for rows with reverse stacking enabled. This allows the mobile layout to work in email apps that strip media queries. Desktop clients that strip the layout styles and do not use classic Outlook's rendering engine may also show the stacked layout. Enabling the option increases the size of the exported email and can cause long messages to be clipped. Custom body, row, and column exporters keep their own layout. Preview the finished email in the clients your audience uses.
If your email provider processes template code on send, both copies can run that code. Test rows that assign variables, increment counters, or generate unique values before enabling reverse stacking.
In email clients that support jump links, links to content inside a reversed row may land at the start of that row. Give destinations distinct names when linking into reversed rows. Some rows with IDs or named anchors that depend on send-time template code use the standard stacking order.
---
# Customizing Mobile Controls
You can change the default behavior for **Do Not Stack on Mobile** and **Hide on Mobile** by configuring the `unlayer.init()` method. This is done through the `_override` option in the editor configuration, which allows you to set default values for mobile settings.
## Example: Changing Default Value for "Do Not Stack on Mobile"
The "Do Not Stack on Mobile" property is only available for blocks (rows).
```javascript
unlayer.init({
tools: {
rows: {
properties: {
noStackMobile: {
editor: {
_override: {
mobile: {
defaultValue: true, // Default value for 'Do Not Stack on Mobile'
},
},
},
},
},
},
},
});
```
### Example Explained
- **tools**: This top-level object represents all the available tools in the editor (e.g., rows, images, text, etc).
- **rows**: Refers to the row tool, which is commonly used to manage the layout structure in the design.
- **properties**: This object contains the various properties that can be modified for the row tool.
- **noStackMobile**: This property refers to the "Do Not Stack on Mobile" feature. When enabled, columns in rows won't stack vertically on smaller screens like mobile devices.
- **\_override**: This setting allows you to change the default behavior of the property for a non-desktop device.
- **mobile.defaultValue**: Defines the default value for the "Do Not Stack on Mobile" option. Setting it to true ensures that blocks do not stack by default on mobile devices.
## Example: Changing Default Value for "Hide on Mobile"
In this example, we will change the default value for "Hide on Mobile" for **Button** tool. This means that buttons will be hidden on mobile devices by default. This is for demonstration only and not a good idea in practice.
```javascript
unlayer.init({
tools: {
button: {
properties: {
hideMobile: {
editor: {
_override: {
mobile: {
defaultValue: true,
},
},
},
},
},
},
},
});
```
:::info Note
The end-user still has the option to toggle this off in the builder
:::
---
## Use Cases
**Custom Mobile Layouts**: Applications with unique mobile design requirements can modify the default values for mobile responsiveness to ensure that content behaves as expected without requiring the end-user to manually change the settings.
**Consistent Branding**: Developers can enforce consistent branding guidelines by adjusting the default behavior for mobile stacking and visibility to match their brand's responsive design standards.
---
## Notes
- Setting a default value through the \__override_ property will ensure that newly created content in the builder start with the specified behavior, but end-users can still manually change the option if needed.
- This feature gives developers more control over the initial design behavior on mobile devices, making it easier to maintain responsive designs across different applications.
---
## Undo / Redo
This feature allows end-users to easily revert or reapply changes made in the builder, providing flexibility and control over their design process. This functionality ensures that end-users can experiment with content creation without the fear of making permanent mistakes.
## Enable / Disable
You can enable or disable the Undo/Redo feature by configuring it within the `unlayer.init()` method. By default, this feature is enabled, but you can disable it if needed. If you choose to disable it, you may want to turn on [delete confirmation](./confirm-on-delete.md) setting.
Example:
```javascript
unlayer.init({
features: {
undoRedo: false,
},
});
```
Setting `undoRedo` to false disables the undo/redo functionality in the builder. If you want to re-enable it, set `undoRedo: true` or omit this property entirely, as it’s enabled by default.
## Additional configuration
You can control whether the editor should select the element related to the undo/redo action, and whether the text input should be focused or not, with the following options:
```javascript
unlayer.init({
features: {
undoRedo: {
enabled: true,
autoSelect: true,
autoFocus: true,
},
},
});
```
## Undo/Redo API Methods
You can also control this feature through several API methods that allow for precise management of user actions.
### Undo Last Action
The `unlayer.undo()` method reverts the last action taken in the editor.
Example:
```javascript
unlayer.undo();
```
This method undoes the last change made by the user.
### Redo Last Action
The `unlayer.redo()` method reapplies the most recently undone action.
Example:
```javascript
unlayer.redo();
```
This method redoes the last undone action, allowing users to move forward through their action history.
### Check if Undo is Available
The `unlayer.canUndo()` method checks if there are any actions in the queue that can be undone.
```javascript
if (unlayer.canUndo()) {
console.log('There are actions to undo.');
}
```
This method returns a boolean (true or false), indicating whether any actions are available to undo.
### Check if Redo is Available
The `unlayer.canRedo()` method checks if there are any actions in the queue that can be redone.
```javascript
if (unlayer.canRedo()) {
console.log('There are actions to redo.');
}
```
This method returns a boolean (true or false), indicating whether any actions are available to redo.
---
## Best Practices
- **Undo/Redo User Experience**: It’s recommended to keep the Undo/Redo feature enabled to allow users more flexibility in editing and modifying their designs without fear of mistakes. If you choose to disable the undo/redo feature, it is highly recommended to turn on the [Confirm On Delete](./confirm-on-delete.md) feature.
- **Custom UI**: If you are adding the Undo/Redo buttons in your UI, use `unlayer.canUndo()` and `unlayer.canRedo()` methods to determine when to enable or disable the undo/redo buttons in your UI, providing a smooth user experience.
By utilizing the Undo/Redo feature, developers can provide their end-users with the ability to easily correct mistakes or backtrack on their designs, enhancing both usability and confidence in the builder's capabilities.
---
## Accessibility
This feature enables developers to configure and manage accessibility options in the builder. With this API, you can name the builder's iframe for screen readers and specify a custom title for the exported HTML.
## Editor Configuration
```javascript
unlayer.init({
editor: {
title: 'Editor Iframe Title',
},
});
```
In this example, screen readers announce the builder's iframe as "**Editor Iframe Title**".
If you don't set `editor.title`, the iframe is named after the display mode, for example "Email editor" or "Web page editor", so screen reader users always know what the frame contains. The name is the iframe's `aria-label`, not its `title`, so no tooltip appears when the pointer rests on the builder. The builder also sets its document language from the [locale](./localization.md).
## Keyboard Navigation
The builder can be used without a mouse. Tab moves between the action bar, the tools panel, the design canvas and the properties panel, and the arrow keys move within each of them. Actions such as inserting, deleting, duplicating, undoing and switching devices are announced to screen readers.
### Tools Panel
| Key | Action |
| :---------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Up / Down, Home / End | Move between the panel's tabs (Content, Blocks, Body, and others). |
| Enter or Space on a tab | Open the tab. |
| Enter on a tool, block, row or image tile | Insert it after the layer you are on in the canvas, or at the end of the design. "Add Content" in an empty column targets that column. When an image is being chosen for an Image block, Enter or Space picks it instead. |
| Space on a tile | Start a keyboard drag: the arrow keys move it, Tab and Shift+Tab jump to the next or previous place it can be dropped, Space drops it and Escape cancels. |
### Design Canvas
The canvas is a tree of layers: rows (including the header and footer), their columns, and the content inside each column. Tab and Shift+Tab move through the layers in that order: a row, then each of its columns followed by the content in it, then the next row. Moving to a layer does not select it.
| Key | Action |
| :------------------------------ | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Up / Down | Move to the previous or next layer. |
| Right / Left | Move into a row's columns or a column's content, or back out to its parent. |
| Home / End | Move to the first or last layer. |
| Enter or Space | Select the layer and open its properties. On a column, select its row with that column's settings open. |
| Enter or F2 on a selected layer | Edit its text. A table starts in its first cell. |
| Escape | Deselect the layer. |
| Tab / Shift+Tab | Move to the next or previous layer. From a selected layer, Tab first reaches its actions, such as Move, Duplicate and Delete. |
| Enter or Space on a Move handle | Pick the selected layer up: the arrow keys move it, Tab and Shift+Tab jump to the next or previous place it can be dropped, Space or Enter drops it and Escape cancels. |
Links, buttons and form fields inside the design are left out of the Tab order while you are in the editor. The exported HTML is unchanged.
### Editing Text
| Key | Action |
| :-------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Tab / Shift+Tab | Indent and outdent the text, or nest a list item. In a table, move to the next or previous cell. In headings and buttons from older designs, they do nothing. |
| Alt+F10 | Move to the text formatting toolbar. Escape returns to the text. |
| Escape or F2 | Stop editing and return to the layer. From there, Tab and Shift+Tab move through the design as usual. |
Screen readers announce these keys when the text receives focus. In the properties panel, the HTML editor and rich text fields also keep Tab for indenting: press Escape (or F2), then Tab or Shift+Tab, to move on to the next field.
### Properties Panel
| Key | Action |
| :----------- | :------------------------------------------------------------------------------------- |
| Left / Right | Move between device tabs (Desktop, Tablet, Mobile) and column tabs. Enter opens a tab. |
| Escape | Close the panel and deselect the layer. Inside a nested panel, close just that panel. |
Reorderable lists, such as social icons, menu items and form fields, have a "Move" handle for keyboard dragging (Enter or Space picks the item up) and Move up / Move down buttons.
### Image Editor
| Key | Action |
| :--------- | :---------------------------------------------------------------------- |
| ] / [ | Select the next or previous object on the image (text, shape, sticker). |
| Arrow keys | Move the selected object by 1 px, or by 10 px with Shift. |
| Delete | Remove the selected object. |
| Enter | Edit the selected text. |
| Escape | Deselect the object. In a menu or color picker, close just that menu. |
The Crop panel has Left, Top, Width and Height fields, and each object has Position fields, as alternatives to dragging on the image.
### AI Assistant Images
| Key | Action |
| :------------------------------ | :---------------------------------------------------------------- |
| Arrow keys on an attached image | Move it earlier or later among the images attached to the prompt. |
| Enter on an attached image | Add it to the design, after the layer you are on in the canvas. |
| + / - / 0 in an image preview | Zoom in, zoom out, or reset the zoom. |
| Arrow keys in a zoomed preview | Move around the image. |
| Escape in an image preview | Close the preview. |
Screen readers announce when an image is added to the design or the prompt, replaced, or the change undone.
## Custom Property Editors
Connect your widget's controls to the property's label so screen readers announce them together:
- **React widgets** receive a `label` prop, the property's label to show, and a `labelId` prop, the id of its text. Render `label`, then reference `labelId` with `aria-labelledby={labelId}` on the control, or on a `role="group"` wrapper when the widget has several controls.
- **`createWidget` widgets**: the builder doesn't show the label, so draw your own in `render` if you want one visible. The `node` passed to `mount` is already a group named by the property label. To name a single control after it, copy the reference:
```javascript
mount(node, value, updateValue) {
var input = node.querySelector('input');
input.setAttribute('aria-labelledby', node.getAttribute('aria-labelledby'));
}
```
Give icon-only buttons an `aria-label`. See [Create a Custom Tool](../tools/custom-tools/create-custom-tool.md#custom-property-editor) for the full widget API.
## HTML Title Tag for Exported HTML
You can set the HTML `` tag for exported HTML in three ways, with the following priority order:
### 1. Export Options (Highest Priority)
You can pass a title when calling `exportHtml`:
```javascript
unlayer.exportHtml(
function (data) {
var html = data.html;
},
{
title: 'My Custom Page Title',
},
);
```
### 2. Design Body Properties (Medium Priority)
Users can set the HTML `` tag directly in the editor UI through the **Body** panel under the **Accessibility** section. This allows non-technical users to configure the title without code changes.
### 3. Editor Configuration (Lowest Priority)
If no title is specified in the export options or the body properties, the title from the editor configuration will be used:
```javascript
unlayer.init({
editor: {
title: 'Default Page Title',
},
});
```
This fallback ensures that there's always a `` tag value available for the exported HTML.
---
## Color Management
This feature allows developers to configure and control the color options available in the builder, ensuring brand consistency and flexibility for end-users. By using this API, you can now define custom color groups, set default color groups, and disable existing color options to suit your specific needs. This flexibility ensures that end-users have access to the right color schemes for their design needs, including support for custom color groups like dark mode.
## Key Features
- **Custom Color Groups**: Create and define custom color categories beyond the default “Common Colors” and “Brand Colors.”
- **Default Color Group**: Set a default color group in the color picker dropdown for ease of use.
- **Disabling Color Groups**: Disable specific built-in color groups, such as “Template Colors,” if they are not needed.
You can change the default color presets for the color picker.
```javascript
unlayer.init({
features: {
colorPicker: {
presets: [
'#D9E3F0',
'#F47373',
'#697689',
'#37D67A',
'#2CCCE4',
'#555555',
'#DCE775',
],
},
},
});
```
---
## Custom Color Groups
You can define any custom color group, giving you the flexibility to add categories that suit your application.
```javascript
unlayer.init({
features: {
colorPicker: {
colors: [
{
id: 'dark_colors',
label: 'Dark Mode',
colors: ['#000', '#333', '#666'],
},
],
},
},
});
```
In this example, a custom color group labeled “**Dark Mode**” with specific colors is added to the color picker.
---
## Setting Default Color Group
You can now specify which color group should be set as the default in the color picker dropdown by using the `default: true` flag.
```javascript
unlayer.init({
features: {
colorPicker: {
colors: [
{
id: 'brand_colors',
colors: ['pink'],
default: true,
},
],
},
},
});
```
Here, the “**Brand Colors**" group is set as the default color group.
---
## Disable Existing Color Groups
You can also disable any of the existing color groups, such as “**Template Colors**”, by passing an empty array for the group’s colors.
```javascript
unlayer.init({
features: {
colorPicker: {
colors: [
{
id: 'template_colors',
colors: [], // Disables the Template Colors group
},
],
},
},
});
```
This example disables the “**Template Colors**” group by setting its colors array to empty.
---
## Overriding Existing Color Groups
To override default color groups like “Common Colors” or “Brand Colors”, use the following structure:
```javascript
unlayer.init({
features: {
colorPicker: {
colors: [
{
id: 'common_colors', // Override Common Colors
colors: ['blue'],
},
{
id: 'brand_colors', // Override Brand Colors
colors: ['pink'],
default: true,
},
],
},
},
});
```
Here, the “Common Colors” group is overridden with a single color (“blue”), and the “Brand Colors” group is overridden with “pink” and set as the default.
---
## Updating Color Picker Configuration on the Fly
In addition to setting the configuration during initialization, you can update the color picker settings dynamically using the `unlayer.setColorPickerConfig()` method.
```javascript
unlayer.setColorPickerConfig({
colors: [
{
id: 'light_colors',
label: 'Light Mode',
colors: ['#FFF', '#EEE', '#CCC'],
},
],
});
```
This allows you to modify the color picker configuration after initialization, providing flexibility to change settings based on user interactions or preferences.
---
## FAQ
**Can I completely remove the default color groups?**
Yes, you can disable any default color group (e.g., “Template Colors”) by passing an empty array for that group’s colors.
**How do I add multiple custom color groups?**
You can define multiple custom color groups by adding multiple objects within the colors array, each with a unique id and label.
**Can I dynamically update the color picker settings?**
Yes, you can use `unlayer.setColorPickerConfig()` to update the color picker settings at any point after initialization.
---
By using the color management API, developers can fully customize the color options available in the builder, ensuring flexibility and branding control for their end-users.
---
## Device Management
The editor supports content creation for multiple devices such as `Mobile` and `Desktop` out of the box. However, in some cases, you may want to restrict the editor to a mobile-only or desktop-only mode or keep mobile mode as the default mode.
## Supported Devices
By default, the editor supports `desktop` and `mobile` devices. You can choose to disable one by removing it.
```javascript
unlayer.init({
devices: ['desktop', 'mobile'],
});
```
---
## Default Device
When the editor is initialized, it opens in the default device mode that is selected here. You can choose to change the default mode to mobile mode if required.
```javascript
unlayer.init({
defaultDevice: 'desktop',
});
```
---
## Mobile-Only Mode
If you want to run the editor in mobile-only mode, you can use the following code.
```javascript
unlayer.init({
defaultDevice: 'mobile',
devices: ['mobile'],
});
```
---
## Domain Management
### Whitelisting Domains for Production Use
When testing Unlayer locally, the domain `localhost` is automatically whitelisted. This allows you to access the full set of plan features and ensures that the Unlayer watermark is removed during development.
However, in a **production (or live) environment**, you must explicitly add your domain to the Unlayer Console for the builder to function correctly and reflect your subscription plan.
### How to Whitelist Your Domain
1. Open the page where the Unlayer builder is embedded.
2. Right-click anywhere on the page and select **Inspect**.
3. Navigate to the **Network** tab and refresh the page.
4. Look for a network request named **`session`** and open its **Payload**.
5. Locate the **`domain`** property in the payload data.
6. Copy the domain value.
7. Go to your [Unlayer Console](https://console.unlayer.com/) and navigate to:
**Developer** → **Builder** → **Settings** → **Allowed Domains**
8. Paste the domain into the **Allowed Domains** field and save.
9. Refresh the page where you are loading the builder. You should now see the correct plan features, and the Unlayer watermark will be removed.
---
## Design Tags
Design Tags are customizable placeholders that allow you to personalize email or page templates dynamically during the editing process. Unlike [Merge Tags](./merge-tags.md), which replace content when an email is sent, design tags only appear within the builder when the template is being edited by users.
For example, you can use design tags to display a personalized message like “Welcome to **My Business**,” where **My Business** dynamically changes based on the business name of the user editing the template.
:::info Exported Design
The final design that is exported does **not** have the variables but the replacement that the end-user sees.
:::
---
## Key Features
- **Customization in the Builder**: Design tags allow for personalized content in the template when it’s being edited in the builder.
- **HTML-Safe Tags**: Use HTML-safe tags to prevent breaking the layout or introducing errors in the template.
- **Flexible Delimiters**: You can customize the tag delimiters to suit your specific syntax requirements.
---
## How Design Tags Work
Design tags are defined using **double square brackets** `[[ var ]]`. These tags are replaced with dynamic content while the template is being edited in the builder. For example, the tag `[[ business_name ]]` could be replaced with the value “Tesla Inc” while editing.
To ensure tags are **HTML-safe** (i.e., to escape special characters or preserve formatting), you can use an additional curly bracket: `[[{ var }]]`. This is especially important when passing URLs for **images** or **links**, ensuring they are safely inserted into the HTML.
---
## Initializing the Builder with Design Tags
You can pass design tags as part of the `unlayer.init()` function when initializing the builder. Design tags are defined as key-value pairs, where the key represents the variable in the template, and the value is the dynamic content that will be displayed in place of the tag.
**Example: Passing Design Tags During Initialization**
```javascript
unlayer.init({
designTags: {
business_name: 'Tesla Inc',
current_user_name: 'Elon Musk',
business_logo_url: 'https://example.com/logo.png',
unsubscribe_link: 'https://example.com/unsubscribe',
},
});
```
In this example:
- The design tag `[[ business_name ]]` will be replaced with “Tesla Inc.”
- The design tag `[[ current_user_name ]]` will be replaced with “Elon Musk.”
- The design tag `[[{ business_logo_url }]]` will be replaced with the URL for the business logo.
- The design tag `[[{ unsubscribe_link }]]` will be replaced with the unsubscribe link URL.
## Updating Design Tags Dynamically
You can also update design tags dynamically at any point after the builder has been initialized by using the `unlayer.setDesignTags()` method. This is useful when you want to update tags based on user actions or changes in real-time.
**Example: Updating Design Tags Dynamically**
```javascript
unlayer.setDesignTags({
business_name: 'SpaceX',
current_user_name: 'John Doe',
});
```
In this example:
- The design tag `[[ business_name ]]` is updated to “SpaceX.”
- The design tag `[[ current_user_name ]]` is updated to “John Doe.”
---
If your template contains the following:
```
Welcome to [[business_name]].
Yours Truly,
[[current_user_name]]
```
When editing the template in the builder, it will display:
```
Welcome to Tesla inc.
Yours Truly,
Elon Musk
```
---
## HTML-Safe Design Tags
To make the content **HTML-safe** and avoid issues with rendering dynamic content in the editor, you can use triple curly brackets in the tag: `[[{ var }]]`. You must do this if you are passing **URLs** for **images** or **links**.
**Example: HTML-Safe Design Tags**
```text
[[{ business_logo }]]
```
In this case, the value for `[[{ business_name }]]` will be displayed as “Tesla Inc,” and any special characters in the value will be safely rendered in the HTML.
---
## Customizing Delimiters
If the default delimiter `[[ ]]` conflicts with your template or is not suitable for your syntax, you can customize the delimiters used for design tags.
```javascript
unlayer.init({
designTagsConfig: {
delimiter: ['((', '))'], // Change delimiters to (( ))
},
designTags: {
business_name: 'Tesla Inc',
current_user_name: 'Elon Musk',
},
});
```
In this example:
- The delimiter has been changed from `[[ ]]` to `(( ))`.
- Now, the design tag `<< business_name >>` will be replaced with “Tesla Inc.”
This is useful when \[[ ]] conflicts with other syntax or templates being used in your application.
---
## Key Differences Between Design Tags and Merge Tags
It’s important to note the difference between design tags and merge tags:
- **Design Tags**: These are placeholders that dynamically change during the editing process in the builder. They are visible only to the person editing the template in the builder.
- **Merge Tags**: These are placeholders that are replaced with actual content (e.g., user-specific data) when an email is sent to a recipient.
While design tags help personalize the template for the editor, merge tags allow for dynamic content when sending emails to end recipients.
---
## Common Use Cases for Design Tags
Some typical use cases for design tags in templates include:
- **Personalized Business Name**: Show the business name of the user editing the template (e.g., `[[ business_name ]]`).
- **Personalized Business Logo**: Display a dynamic URL for the business logo using an HTML-safe tag (e.g., `[[{ business_logo_url }]]`).
- **Custom Footer Text**: Display a footer text specific to the user or business editing the template.
- **Custom Unsubscribe Link**: Use an HTML-safe tag to generate personalized unsubscribe links for the email template (e.g., `[[{ unsubscribe_link }]]`).
These use cases help personalize the editing experience and ensure that the correct dynamic content is visible while users edit their templates in the builder.
---
## Display Conditions
The Display Conditions feature allows your end-users to show or hide specific content in an email based on customizable conditions. This is useful for creating personalized email campaigns that adapt to recipients’ behaviors or attributes, such as gender, purchase history, location, or preferences.
End-users can choose display conditions for different blocks when designing their emails, ensuring that recipients see tailored content based on predefined rules.

Your users will have the ability to pick a condition and apply it to a row so they can show different content based on who the audience is.
---
## Enable Feature
The `unlayer.setDisplayConditions` API lets you define display conditions that users can apply to email blocks. Each condition specifies content visibility based on a particular rule, such as a user’s last order catalog or any custom attribute you define.
**Example: Setting Display Conditions**
```javascript
unlayer.setDisplayConditions([
{
type: 'Last Order Catalog',
label: 'Women',
description: 'Only people who ordered from Women catalog',
before: "{% if lastOrder.catalog == 'Women' %}",
after: '{% endif %}',
},
{
type: 'Last Order Catalog',
label: 'Men',
description: 'Only people who ordered from Men catalog',
before: "{% if lastOrder.catalog == 'Men' %}",
after: '{% endif %}',
},
{
type: 'Last Order Catalog',
label: 'Children',
description: 'Only people who ordered from Children catalog',
before: "{% if lastOrder.catalog == 'Children' %}",
after: '{% endif %}',
},
]);
```
This example creates three conditions based on the recipient’s last order catalog. End-users can apply these conditions to different email blocks, so that each block will only be displayed to recipients who meet the selected condition.
Your end-users will see these options in a modal.

---
### Attributes for Display Conditions
Each display condition must have the following attributes. You can also send any custom attributes to identify the condition.
| Attribute | Description |
| :-------------- | :------------------------------------------------------------------------------------------------------------------------------ |
| **type** | A category to group multiple conditions into folders. End-users will select the condition type first. |
| **label** | The name of the condition that the user will see. |
| **description** | A description of the condition that will help users understand when it applies. |
| **before** | The opening syntax for the condition (e.g., an opening tag or logic statement). This will be added **before** the selected row. |
| **after** | The closing syntax for the condition (e.g., a closing tag or logic statement). This will be added **after** the selected row |
### Example: Attribute Breakdown
```json
{
"type": "Last Order Catalog",
"label": "Women",
"description": "Only people who ordered from the Women catalog",
"before": "{% if lastOrder.catalog == 'Women' %}",
"after": "{% endif %}"
}
```
- **type**: Groups this condition under “Last Order Catalog.
- **label**: Displays the name “Women” in the UI.
- **description**: Provides a helpful description for end-users: “Only people who ordered from the Women catalog.”
- **before/after**: Defines the template syntax for wrapping content, where the content is only shown if the recipient’s last order catalog is “Women.”
---
## Custom UI for Display Conditions
You can extend this feature by creating a custom UI that allows your end-users to build their own conditions using an interface that you control. For example, you could display a custom modal where users select or build conditions before applying them to their email content.
```javascript
unlayer.registerCallback('displayCondition', function (data, done) {
// `data` contains the current display condition and a context object with the related element id
// Open your custom UI for building display conditions
// This could be a modal or any interface you control
// Once the user has built or selected a condition, call the `done` callback
// with the new condition.
done({
type: 'Last Order Catalog',
label: 'Women',
description: 'Only people who ordered from the Women catalog',
before: "{% if lastOrder.catalog == 'Women' %}",
after: '{% endif %}',
});
});
```
In this example:
- **data**: This parameter contains the current display condition that the user is working with and a context object with the related element id.
- **Custom UI**: You can open your own modal or custom interface for the user to build or select a display condition.
- **done()**: After the user has selected or created a display condition, call the done function with the new condition. This condition will then be applied to the selected email block.
### Example Workflow for Custom UI Implementation
1. **Open Custom Modal**: When the user selects to add or edit a display condition, open a custom modal or interface where they can select or create a new condition.
2. **Define the Condition**: In your custom UI, let the user define the display condition by selecting attributes like type, label, description, and conditions for showing the block.
3. **Pass the Condition Back to the Builder**: Once the user finalizes the condition, pass it back to the builder by calling the `done()` callback with the appropriate `type`, `label`, `description`, `before`, and `after` values.
4. **Save and Apply the Condition**: The condition is now applied to the block, ensuring that the content is shown only when the recipient meets the specified criteria.
---
## Use Cases for Display Conditions
1. **Personalized Email Campaigns**: Create targeted emails where different content is displayed based on recipient behavior, such as their gender, last purchase, location, or preferences.
2. **Dynamic Content**: Use display conditions to dynamically alter content within a single email template, reducing the need to create separate emails for different audience segments.
3. **Advanced Segmentation**: Set up advanced segmentation by defining custom conditions that control when specific blocks of content are shown to recipients.
---
## Dynamic Images
Dynamic images give each recipient their own unique image using any subscriber data you have in your email service provider. These images change depending on one or more [merge tags](./merge-tags.md) that are passed to the system that delivers them.
Some examples where dynamic images can be used are:
- Personalized Cards
- Countdown Timers
- Live Ads
- Flight Tracker
- Live Charts
- Product Recommendations
- etc
Let's check out an example of personalized birthday cards.
---
## Personalized Birthday Cards
You can send a birthday card to thousands of email subscribers, each personalized with the subscriber's first name. It's simple to do with dynamic images. There are services that can generate personalized images "on the fly", like [Nifty Images](https://niftyimages.com?utm_source=unlayer).

Here is a personalized image created on Nifty Images to wish a happy birthday to all the subscribers. The editor preview of the image uses a sample name `Katie`, but the URL uses a merge tag `{{first_name}}`. Merge tags act as variables in the URL. When rendering your email, landing page, or popup, the real name will replace the merge tag.
The final image can have different dimensions from the sample shown in the editor. Email exports keep the height of merge-tag images fluid so the delivered image retains its natural proportions across email clients, including Outlook Classic.
If you carefully look at the image URL in the editor, it is:
`https://img1.niftyimages.com/e75h/npar/8y-i?name={{first_name}}`
It is replaced with **Katie** in the editor because we have provided that as a `sample` value for the merge tag `{{first_name}}`. [Learn more here](./merge-tags.md#previewing-merge-tags).

---
## Merge Tags
Merge Tags allow end-users to dynamically insert personalized content into their emails. These placeholders are replaced with real values when the email is sent, making it easy to create highly personalized and dynamic emails. Merge tags can be inserted into a block of text by clicking the "Merge Tags" button in the text editor toolbar.
If no merge tags are provided during initialization, the "Merge Tags" button will not appear.
## How Merge Tags Work
Merge tags are placeholders that are replaced by real data at the time of sending the email. For example, the merge tag `{{first_name}}` might be replaced with "John" when an email is sent to a recipient.
Unlayer supports all templating engines, whether they use curly brackets `{{ ... }}`, square brackets `[ ... ]`, or any other syntax.

## Initializing Merge Tags
To pass merge tags to the builder, use the `mergeTags` configuration during initialization. Each merge tag requires a name (what the user sees), a value (the actual merge tag in the templating engine), and a sample value for preview purposes.
**Example: Passing Merge Tags**
```javascript
unlayer.init({
mergeTags: {
first_name: {
name: 'First Name',
value: '{{first_name}}',
sample: 'John',
},
last_name: {
name: 'Last Name',
value: '{{last_name}}',
sample: 'Doe',
},
},
});
```
In this example:
- first_name will be displayed as "John" in preview mode.
- last_name will be displayed as "Doe" in preview mode.
---
## Grouping Merge Tags into Sub-Menus
You can group related merge tags into sub-menus for better organization. This is useful for scenarios like grouping address fields under a "Shipping Address" menu.
**Example: Grouping Merge Tags**
```javascript
unlayer.init({
mergeTags: {
shipping_address: {
name: 'Shipping Address',
mergeTags: {
street_1: {
name: 'Street 1',
value: '{{shipping_address.address_1}}',
},
street_2: {
name: 'Street 2',
value: '{{shipping_address.address_2}}',
},
city: {
name: 'City',
value: '{{shipping_address.city}}',
},
state: {
name: 'State',
value: '{{shipping_address.state}}',
},
zip: {
name: 'Zip',
value: '{{shipping_address.zip}}',
},
},
},
},
});
```
In this example, the user will see a "Shipping Address" sub-menu with Street 1, Street 2, City, State, and Zip options.
---
## Updating Merge Tags Dynamically
You can dynamically update merge tags after the builder has been initialized using the `unlayer.setMergeTags()` method.
**Example: Dynamically Updating Merge Tags**
```javascript
unlayer.setMergeTags({
first_name: {
name: 'First Name',
value: '{{first_name}}',
sample: 'John',
},
last_name: {
name: 'Last Name',
value: '{{last_name}}',
sample: 'Doe',
},
});
```
---
## Smart Merge Tags

Smart merge tags improve the user experience by:
- **Highlighting** merge tags within text fields.
- Showing **human-readable names** (e.g., "Customer Name" instead of `{{ customer.name }}`).
- Allowing users to select, replace, and style merge tags easily.
Smart Merge Tags are enabled by default, but you can disable them:
```javascript
unlayer.init({
features: {
smartMergeTags: false,
},
});
```
---
## Conditions and Looping
> Run this example in our [Examples](https://examples.unlayer.com/dynamic_content/merge-tag-loops/) page
Merge tags can be used to create dynamic content with conditions and loops. This allows for advanced personalization, such as displaying product lists or conditional content based on user behavior.
For example, if you want your users to create an order confirmation email template and show all products in that order, you would pass the "Products" merge tags along with some `rules`. The `before` and `after` of the selected rule will be added before and after the block in the exported HTML.
This `before` and `after` can be used to create loops or if-then-else conditions. The syntax will depend on which templating engine the host application uses. In this example, we are using Mustache templating engine.
If you want to add conditions to display content to different segments of audience, check [Display Conditions](./display-conditions.md).
**Example: Adding Loops with Merge Tags**
```javascript
unlayer.init({
mergeTags: {
products: {
name: 'Products',
rules: {
repeat: {
name: 'Repeat for Each Product',
before: '{{#products}}',
after: '{{/products}}',
},
},
mergeTags: {
name: {
name: 'Product Name',
value: '{{name}}',
},
image: {
name: 'Product Image',
value: '{{image}}',
},
},
},
},
});
```
In this example:
- The "Products" merge tag group includes a rule for repeating content for each product.
- The `before` and `after` values define the loop in Mustache syntax.
When the loop is processed, each product will be displayed using the name and image merge tags inside the loop.
Specifying the `rules` will add an additional icon to the blocks in the editor. This icon will be used to select the merge tag group and rules.

Once you click that icon, it will let users pick a merge tag group and a merge rule, and will show the available merge tags after selection. You can then use those tags any where inside that block.

---
## Previewing Merge Tags
Sample values for merge tags can be provided using the `sample` attribute. These values are shown in preview mode to help users visualize what the final email will look like.
**Example: Sample Merge Tag Values**
```javascript
unlayer.init({
mergeTags: {
first_name: {
name: 'First Name',
value: '{{first_name}}',
sample: 'John',
},
last_name: {
name: 'Last Name',
value: '{{last_name}}',
sample: 'Doe',
},
},
});
```
In preview mode, `{{first_name}}` will be replaced with "John," and `{{last_name}}` will be replaced with "Doe."
---
## Autocomplete Menu Trigger
By default, the merge tag autocomplete menu is triggered by the first character of your merge tags. For example, if your merge tags look like `{{ first_name }}`, the trigger will automatically be **`{`**.
If you want to change the trigger character, you can do that like this.
```javascript
unlayer.init({
mergeTagsConfig: {
autocompleteTriggerChar: '@',
},
});
```
To disable the autocomplete feature, you can pass `null`.
```javascript
unlayer.init({
mergeTagsConfig: {
autocompleteTriggerChar: null,
},
});
```
---
## Sorting Merge Tags
By default, merge tags are sorted alphabetically in the menu. You can disable sorting.
```javascript
unlayer.init({
mergeTagsConfig: {
sort: false,
},
});
```
---
## Exporting HTML with Real Values
:::info When are Merge Tags replaced?
Replacing merge tags with actual values is done at the time of sending the email by the host application. Usually, the HTML should be parsed by your templating engine (Mustache, Nunjucks, etc) and the tags are replaced with real values.
:::
In case you want to replace merge tags with real values at the time of exporting HTML, you can use the following examples.
### Values
Replace `{{ first_name }}` with `John` and `{{ last_name }}` with `Doe`.
```javascript
unlayer.exportHtml(
function (data) {
var json = data.design;
var html = data.html;
},
{
mergeTags: {
first_name: 'John',
last_name: 'Doe',
},
},
);
```
### Conditions
The following example can be used to show or hide a block based on a `true | false` condition.
```javascript
unlayer.exportHtml(
function (data) {
var json = data.design;
var html = data.html;
},
{
mergeTags: {
products: {
empty: true,
},
},
},
);
```
### Loops
The following example can be used to provide data to a loop.
```javascript
unlayer.exportHtml(
function (data) {
var json = data.design;
var html = data.html;
},
{
mergeTags: {
products: {
repeat: [{ name: 'Item 01' }, { name: 'Item 02' }],
},
},
},
);
```
---
## Custom UI
You can extend this feature and allow users of the editor to build or choose merge tags using a UI that you control. For example, you can open a custom modal and show any interface to pick or build merge tags or rules.
### Merge Tags
You can use this callback function to show custom UI to pick merge tags.
**Example: Custom Merge Tag Picker UI**
```javascript
unlayer.registerCallback('mergeTag', function (data, done) {
// data - contains current mergeTagGroup, current mergeTagRule, list of mergeTags and a context object with the related element id
// done - callback function
// Open custom UI for merge tags here
// Once your user is done choosing a merge tag, call the "done"
// callback function with the new merge tag.
done({
name: 'First Name',
value: '{{first_name}}',
});
// Alternatively, you can use this api to pass a prefix and a suffix
// This is useful if your custom UI allows adding multiple merge tags, for example,
// so you could set a separator between each addition
done({
mergeTag: {
name: 'First Name',
value: '{{first_name}}',
},
prefix: '',
suffix: ' ',
});
});
```
### Merge Tag Groups
You can use this callback function to show custom UI to pick [merge tag groups and rules](#merge-tag-groups).
```javascript
unlayer.registerCallback('mergeTagRule', function (data, done) {
// data - contains current mergeTagGroup, current mergeTagRule, list of mergeTags and a context object with the related element id
// done - callback function
// Open custom UI for merge tag groups here
// Once your user is done choosing a merge tag group and rules,
// call the "done" callback function with the new merge tag group.
// Reset the merge tag group and rules
// done({
// mergeTagGroup: null,
// mergeTagRule: null,
// });
done({
mergeTagGroup: 'products',
mergeTagRule: 'repeat',
});
});
```
---
## End-User Identification
Identifying end-users allows developers to associate actions performed in the builder with specific end-users in the host application. This is essential for personalizing the experience, tracking saved blocks, and managing uploads that belong to individual end-users.
## Why Identify End-Users?
Identifying end-users allows the builder to:
- **Save and load personalized content**: Each end-user can have their own set of saved blocks, or file uploads.
- **Provide a seamless experience**: Ensure that the right content is available to the right end-user.
- **Improve tracking**: Keep track of who created, edited, or saved specific files for audit or reporting purposes.
---
## Setting Up End-User Identification
Pass the current end-user's details through the `user` property when initializing the builder.
Use an opaque `user.id` from your application that stays the same across sessions.
Although `name` and `email` are optional for general identification, we recommend sending both
when available. The name is displayed next to comments in [Team Collaboration](../collaboration/setup.md),
helping teammates recognize who is participating, and the email address enables Send Test Email.
```javascript
unlayer.init({
user: {
id: 'user-42',
name: 'Jane Doe',
email: 'jane.doe@example.com',
},
});
```
If your integration does not send profile details, a stable `user.id` is the minimum identity
needed for features such as saved blocks, uploads, and AI usage attribution:
```javascript
unlayer.init({
user: {
id: 'user-42',
},
});
```
These examples show only the identity fields. If your project uses identity verification or
requires end-user feature policies, also pass the appropriate `signature` or `featurePolicyToken`.
See [Security Settings](./security-settings.md).
**Send Test Email requires a valid `user.email`.** The test email is sent to that address.
If you use this feature, include the email address and follow the other
[Test Email requirements](../builders/email-builder/test-email.md).
Omitting profile fields does not clear values you previously sent for the same end-user.
See [Custom Properties](#custom-properties) for how stored values are merged and cleared.
### User Object Properties
- **id** (required): This is the unique identifier for the end-user within your host application. It could be a number or a string.
- **name** (optional, recommended): The name of the end-user. Displayed next to comments in [Team Collaboration](../collaboration/setup.md) so teammates can identify the author.
- **email** (optional, recommended): The email address of the end-user. Required for [Send Test Email](../builders/email-builder/test-email.md).
- **avatar** (optional): URL of the end-user's profile image.
### Custom Properties
Any other property you put on `user` is stored with the end-user and returned to the editor with
the session, so you can keep your own identifiers next to the profile:
```javascript
unlayer.init({
user: {
id: 1,
name: 'John Doe',
tenantId: 'acme-eu',
plan: 'pro',
},
});
```
What you send is merged into what is already stored for that end-user. This applies to `name`,
`email`, and `avatar` as well as to your own properties: a property you stop sending keeps its last
value rather than being cleared. To clear a stored value, send the property as `null`. Unlayer does
not interpret your own properties.
`id`, `signature`, and `featurePolicyToken` are credential fields, so a custom property cannot
replace them. Unlayer also reserves the following names for authentication and session data:
- `projectId`, `customId`, `consoleAttestation`, and `entitlements`
- `featurePolicy`, `policyExp`, `featurePolicyVerified`, and `legacySignatureVerified`
- `consoleSession`, `_consoleSession`, `_consoleSessionId`, `_consoleSessionProof`, and
`_consoleUserId`
- `consoleContextVerified`, `consoleSessionExp`, `consoleSessionId`, `consoleUserId`, and
`consoleSessionProof`
A non-null `featurePolicyToken` and any supplied `consoleAttestation` are verified even when Identity
Verification is off: a value Unlayer cannot verify, including an empty string, fails authentication,
and the editor loads without a session. A `featurePolicyToken` set to `null` is treated as missing and
uses the normal legacy-signature or unsigned flow; projects that require end-user feature policies
still reject it. Any other reserved name is dropped rather than rejected. Either way, prefer names
specific to your application — `tenantId` or `acmePlan` rather than generic ones.
### Restricting What an End-User Can Do
If different end-users of the same project should have different features — say full template generation on your paid tier only — pass a signed `featurePolicyToken` instead of a plain `signature`. It covers the same user id and additionally carries the features that end-user is permitted to use. See [Restricting Features Per End-User](./security-settings.md#restricting-features-per-end-user).
---
### Why the id is Required
The `id` is the key property that helps the builder associate the user’s actions and saved content with their account. Without it, the builder won’t know which content belongs to which user, making it impossible to offer certain features.
The AI Assistant depends on it most directly. Without an `id`, the assistant
doesn't appear in the editor, because AI usage is tracked per end user so you
can see who consumes your credits. Recent editor versions log a console
warning when the id is the only thing missing. See [AI Assistant setup](/ai/assistant/setup).
On AI Assistant plans, AI image edits in the image editor still work without an `id`, and so do
Smart Buttons and Smart Headings when the plan includes them. That's deprecated: a future version
will hide them too, and the editor warns in the console until then.
---
## Use Cases for End-User Identification
- **Saved Blocks**: When users save blocks, they are saved under a unique id, making them available only to that specific end-user. The id helps ensure only the right person has access to their saved content. [Learn More](../blocks/user-saved-blocks.md)
- **File Manager**: When users upload images or files, they are saved under a unique id, making them available only to that specific end-user. These files are visible to the end-user in uploads tab. [Learn More](../files-storage/file-manager.md)
- **AI Assistant**: The AI Assistant requires an identified end-user. Without an id, the assistant is hidden in the editor and AI requests are rejected. [Learn More](/ai/assistant/setup)
- **End-User AI Credits**: Use the same end-user id to attribute AI usage in your backend, then show that user's allowance and purchase flow in the builder. See [End-User AI Credits & Upsell](/ai/credit-upsell).
---
## Best Practices
- **Unique and Consistent IDs**: Ensure that the id you pass is always unique and consistent for each user across different sessions.
- **Recommended Profile Fields**: Send `name` and `email` when available, even though they are optional for general identification. Names help teammates recognize comment authors in Team Collaboration; a valid email address is required for Send Test Email.
- **Security**: Make sure you review the [Security Settings](./security-settings.md) to setup identity verification. Identity verification prevents third parties from impersonating your logged-in users.
- **Per-End-User Permissions**: `unlayer.init` feature flags configure the editor for everyone who loads it. To grant or withhold a feature for one specific end-user, use a [signed feature policy](./security-settings.md#restricting-features-per-end-user).
---
## Events & Callbacks
## Editor Ready
This event is called when the editor is ready for use. It waits for custom js, css and fonts to be fully loaded.
```javascript
unlayer.addEventListener('editor:ready', function () {
console.log('editor:ready');
});
```
---
## Design Loaded
This event is called when your design is loaded in the editor.
```javascript
unlayer.addEventListener('design:loaded', function (data) {
// Design is loaded
var json = data.design; // design json
});
```
---
## Design Updated
This event is called when the design changes in the editor. This can be used to set up [auto saving](../get-started/load-and-save-designs.md#auto-saving-a-design).
```javascript
unlayer.addEventListener('design:updated', function (data) {
// Design is updated by the user
var type = data.type; // body, row, content
var item = data.item;
var changes = data.changes;
console.log('design:updated', type, item, changes);
});
```
This event is also triggered while text is being edited in the text editor. You can customize the text editor's settings to optimize performance. [Learn More](text-management/trigger-change-event.md)
---
## Image Uploaded
This event is called when an image is uploaded by the user.
```javascript
unlayer.addEventListener('image:uploaded', function (data) {
var image = data.image;
var url = image.url;
var width = image.width;
var height = image.height;
});
```
---
## Text Editor Ready
This event fires whenever the inline rich text editor becomes ready, which
happens every time a text block enters edit mode. It is not a one-time
initialization event, so do not use it to run setup that should happen once.
```javascript
unlayer.addEventListener('text-editor:ready', function () {
// the inline text editor is ready for this editing session
});
```
---
## Inbox Preview Viewed
This event fires after a completed Inbox Preview screenshot becomes visible to
the user. It includes whether the editor selected the screenshot automatically
or the user opened it from the gallery or navigation controls.
```javascript
unlayer.addEventListener('inbox-previews:viewed', function (data) {
var runId = data.runId;
var endUserId = data.endUserId;
var clientId = data.clientId;
var viewSource = data.viewSource;
var autoSelected = data.autoSelected;
});
```
Use the `runId` and `clientId` pair to count unique viewed screenshots. See
[Inbox Previews](/builder/latest/email-builder/inbox-previews#track-which-results-users-view)
for the complete payload and reporting guidance.
---
## Fetch Image Callback
Register `fetchImage` to load images through your own backend, for example from hosts without CORS headers. The builder calls it when it needs an image's data, such as to draw it in a [document PDF](../builders/document-builder/pdf-rendering.md#images). The callback receives the image's URL and calls `done` with the image as a `Blob`, or with an `error`, including when your backend answers with an error status: a page of error text isn't an image.
```javascript
unlayer.registerCallback('fetchImage', function (data, done) {
fetch('/my-image-proxy?url=' + encodeURIComponent(data.url))
.then((response) => {
if (!response.ok)
throw new Error('Image request failed: ' + response.status);
return response.blob();
})
.then((blob) => done({ blob }))
.catch((error) => done({ error }));
});
```
---
## Credit Purchase Callback
Register `credits:purchase` to open your application's checkout from the builder
and return the updated end-user allowance when the purchase completes. See
[End-User AI Credits & Upsell](/ai/credit-upsell#keep-the-purchase-inside-the-builder)
for the callback contract and `setCredits` updates. Your backend remains
responsible for payment, the allowance ledger, and enforcement.
---
## Custom Fonts
You can add and manage custom fonts to provide a more personalized design experience for your end-users. These fonts will be available for selection in the editor, allowing users to create content that adheres to their branding.
## Usage
You can pass custom fonts configuration during initialization like this:
```javascript
unlayer.init({
fonts: {
showDefaultFonts: true,
customFonts: [
{
label: 'Comic Sans',
value: "'Comic Sans MS', cursive, sans-serif",
},
{
label: 'Lobster Two',
value: "'Lobster Two',cursive",
url: 'https://fonts.googleapis.com/css?family=Lobster+Two:400,700',
weights: [
{ label: 'Regular', value: 400 },
{ label: 'Bold', value: 700 },
],
},
],
},
});
```
In this example default fonts are loaded, and two new fonts are added: a web safe font (Comic Sans) and a Google hosted web font (Lobster Two).
## Parameters
| Parameter | Description | Default |
| :-------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------ |
| **showDefaultsFonts** | This boolean parameter indicates whether default fonts are loaded in the list or not. If it's set to `false`, only your custom fonts will be loaded. If it's set to `true`, your custom fonts will be loaded along with the default fonts. | `true` |
| **customFonts** | This is an array of objects which contains your custom fonts. These custom fonts could be web safe fonts or hosted web fonts (google, etc). | `[]` |
Each element in **customFonts** can have the following properties:
| Parameter | Description | Example |
| :--------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------ |
| **label** | This is the name of the font that will be shown to the end-users in the dropdown. | `Lobster` |
| **value** | This is the CSS font stack that will be emitted in the HTML. You should provide at least one fallback font to ensure the text is not displayed in an unwanted font family. Make sure you use single quote marks with the font names instead of double quotation marks to maintain a correct syntax. | `'Lobster', cursive` |
| **url**_(optional)_ | This parameter is used only when we work with web fonts. It's important that the URL points to a CSS file with the @font-face properties, and not directly to the font files. Also, CSS must be hosted on HTTPS. | `https://fonts.googleapis.com/css?family=Lobster` |
| **weights**_(optional)_ | This is an array of supported weights for each font. | `[{ label: 'Regular', value: 400 }, { label: 'Bold', value: 700 }]` |
---
## Example
Here's another example where it only shows your custom fonts and not the default fonts. It's a mix of web safe system fonts and Google fonts.

```javascript
unlayer.init({
fonts: {
showDefaultFonts: false,
customFonts: [
{
label: 'Anton',
value: "'Anton', sans-serif",
url: 'https://fonts.googleapis.com/css?family=Anton',
},
{
label: 'Georgia',
value: "Georgia, Times, 'Times New Roman', serif",
},
{
label: 'Helvetica',
value: "'Helvetica Neue', Helvetica, Arial, sans-serif",
},
{
label: 'Lucida',
value: "'Lucida Grande', 'Lucida Sans', Geneva, Verdana, sans-serif",
},
{
label: 'Lato',
value: "'Lato', Tahoma, Verdana, sans-serif",
url: 'https://fonts.googleapis.com/css?family=Lato',
},
],
},
});
```
---
### Grouped Fonts
You can organize fonts into groups using the `fonts` configuration option. Each group has a `label` and an `options` array containing the individual font definitions.
```javascript
unlayer.init({
fonts: {
showDefaultFonts: false,
customFonts: [
{
label: 'Arial',
value: 'arial,helvetica,sans-serif',
},
{
label: 'Brand Fonts',
options: [
{
label: 'Brand Primary',
value: "'Brand Primary', sans-serif",
url: 'https://fonts.googleapis.com/css2?family=Roboto&display=swap',
},
{
label: 'Brand Secondary',
value: "'Brand Secondary', serif",
url: 'https://fonts.googleapis.com/css2?family=Lora&display=swap',
},
],
},
{
label: 'Google Fonts',
options: [
{
label: 'Open Sans',
value: "'Open Sans', sans-serif",
url: 'https://fonts.googleapis.com/css2?family=Open+Sans&display=swap',
},
],
},
],
},
});
```
---
## Default Fonts
This is the complete list of the default fonts in the Unlayer editor and its configuration, including the URL for Google web fonts:
```json
[
{
"label": "Andale Mono",
"value": "andale mono,times"
},
{
"label": "Arial",
"value": "arial,helvetica,sans-serif"
},
{
"label": "Arial Black",
"value": "arial black,avant garde,arial"
},
{
"label": "Book Antiqua",
"value": "book antiqua,palatino"
},
{
"label": "Comic Sans MS",
"value": "comic sans ms,sans-serif"
},
{
"label": "Courier New",
"value": "courier new,courier"
},
{
"label": "Georgia",
"value": "georgia,palatino"
},
{
"label": "Helvetica",
"value": "helvetica,sans-serif"
},
{
"label": "Impact",
"value": "impact,chicago"
},
{
"label": "Symbol",
"value": "symbol"
},
{
"label": "Tahoma",
"value": "tahoma,arial,helvetica,sans-serif"
},
{
"label": "Terminal",
"value": "terminal,monaco"
},
{
"label": "Times New Roman",
"value": "times new roman,times"
},
{
"label": "Trebuchet MS",
"value": "trebuchet ms,geneva"
},
{
"label": "Verdana",
"value": "verdana,geneva"
},
{
"label": "Lobster Two",
"value": "'Lobster Two',cursive",
"url": "https://fonts.googleapis.com/css?family=Lobster+Two:400,700"
},
{
"label": "Playfair Display",
"value": "'Playfair Display',serif",
"url": "https://fonts.googleapis.com/css?family=Playfair+Display:400,700"
},
{
"label": "Rubik",
"value": "'Rubik',sans-serif",
"url": "https://fonts.googleapis.com/css?family=Rubik:400,700"
},
{
"label": "Source Sans Pro",
"value": "'Source Sans Pro',sans-serif",
"url": "https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,700"
},
{
"label": "Open Sans",
"value": "'Open Sans',sans-serif",
"url": "https://fonts.googleapis.com/css?family=Open+Sans:400,700"
},
{
"label": "Crimson Text",
"value": "'Crimson Text',serif",
"url": "https://fonts.googleapis.com/css?family=Crimson+Text:400,700"
},
{
"label": "Montserrat",
"value": "'Montserrat',sans-serif",
"url": "https://fonts.googleapis.com/css?family=Montserrat:400,700"
},
{
"label": "Old Standard TT",
"value": "'Old Standard TT',serif",
"url": "https://fonts.googleapis.com/css?family=Old+Standard+TT:400,700"
},
{
"label": "Lato",
"value": "'Lato',sans-serif",
"url": "https://fonts.googleapis.com/css?family=Lato:400,700"
},
{
"label": "Raleway",
"value": "'Raleway',sans-serif",
"url": "https://fonts.googleapis.com/css?family=Raleway:400,700"
},
{
"label": "Cabin",
"value": "'Cabin',sans-serif",
"url": "https://fonts.googleapis.com/css?family=Cabin:400,700"
},
{
"label": "Pacifico",
"value": "'Pacifico',cursive",
"url": "https://fonts.googleapis.com/css?family=Pacifico"
}
]
```
---
## Font Sizes
To ensure that your templates have a consistent look and feel, you can define preset font sizes for text elements. This allows users to quickly apply standard sizes without manually adjusting them every time.
```javascript
unlayer.init({
features: {
textEditor: {
fontSizes: ['18px', '20px', '30px'],
},
},
});
```
---
## Font Management
Font management feature allows you to control the fonts available within the builder, ensuring consistency across your designs. Whether you’re using standard web fonts or custom fonts, our platform provides flexible options to manage and apply fonts throughout your email, page, or popup templates.
## Key Features

---
## Best Practices
When embedding our builder into your application, it’s important to implement best practices for managing fonts to ensure optimal performance, flexibility, and user experience.
### Font Compatibility for Emails
- **Fallback Fonts**: Since many email clients do not support custom fonts, ensure your application allows users to define fallback fonts when using custom fonts in email templates. This ensures that emails render correctly in all clients, regardless of whether the custom font is supported.
Example of how to suggest fallback fonts to the builder:
```json
{
"label": "CustomFont",
"value": "'CustomFont', Arial, sans-serif"
}
```
- **Pre-defined Web-Safe Fonts**: Offer a set of standard web-safe fonts (e.g., Arial, Helvetica, Times New Roman) as defaults in the font dropdown. This gives end-users reliable, cross-client options without the risk of rendering issues.
- **Limit Custom Fonts for Email Content**: Educate end-users through documentation or guides that custom fonts should be used sparingly in email content, as many email clients don’t support them.
### Custom Fonts
When adding custom fonts, stick to commonly supported formats (.ttf, .woff, .woff2, .otf) or services like Google Fonts, Adobe Fonts, etc. You may also want to check size of font files to prevent performance issues caused by overly large font files.
### Font Size Presets
**Maintain Consistency with Font Sizes**: Predefine a range of font size presets that reflect commonly used sizes (e.g., 12px, 14px, 16px, etc.). This reduces the need for manual adjustments and maintains design consistency for the end-users.
---
## Link Types
Link types refer to the different formats or destinations that a link can point to within a design. Each link type defines a specific kind of action or behavior when a user clicks a button or a link. Our platform supports a variety of link types to accommodate different use cases, allowing you to create links that perform functions beyond just navigating to a web page.
Each link type can be configured with custom properties, such as tracking codes, link text, and link attributes, to match the specific functionality needed for your design. By defining different link types, you can create a more interactive and user-friendly experience for your audience.
## Available Link Types
- **Website Link (URL)**: Standard hyperlink that directs users to a webpage.
- **Email**: Opens the user's default email client to send an email to a specified address.
- **Phone Number**: Initiates a call when clicked on mobile devices, using the "tel:" protocol.
- **SMS**: Opens the default messaging app to send a pre-configured text message.
- **File Download**: Allows users to download a specified file when they click the link.

Each of these generate a URL with required input from the user. For example, `Open Website` asks the user for a URL and Target.

---
## Adding a New Link Type
You can add your own link types. Every link type has the ability to add a URL to **href** or a JavaScript function to the **onClick** method of the link or button HTML tag. This could be a simple static URL, or a URL generated with user input.
You have to define the following parameters for each link type.
### Parameters
| Name | Description |
| :--------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **name** | Unique name for the link type |
| **label** | Display label for the link type |
| **attrs** | An object where we define the link value. For URL based links, it will have **href** and **target**. For JavaScript links, this will have **onClick**. For File downloads, it will have a boolean **download**. |
| **fields** | This is where we will define the input fields that the user can fill to generate the URL. Check the [input field parameters](#input-field-parameters) below. |
### Input Field Parameters
If you need to get input from users to create the URL for your link, this is how you can define the fields.
| Name | Description |
| :------------------ | :----------------------------------------------------------------------------------------------- |
| **name** | Unique name for the input field |
| **label** | Display label for the input field |
| **defaultValue** | Default value for the input field |
| **inputType** | Input type for the field. This is the HTML input type. Examples: `text`, `email`, `number`, etc. |
| **placeholderText** | Placeholder text for the input field |
| **options** | Only required for dropdown. An array of objects containing all the option labels and values. |
| **sortOptions** | Boolean to sort the options by their labels in ascending order. |
---
## Examples
Here are a few examples that demonstrate different link types.
### Static Link
In this example, we will add a simple `https://google.com` static link as an available link type. If a user selects this action, the button will simply open Google in a new tab.

```javascript
unlayer.setLinkTypes([
{
name: 'static_google_link',
label: 'Go to Google',
attrs: {
href: 'https://google.com/',
target: '_blank',
},
},
]);
```
---
### Input Generated Link
In this example, we will ask the user to enter an **email** and choose a **country** to generate the link URL. The link would look like: `https://mycustomlink.com/?email=xyz@email.com&country=usa`
For this, we will have to define these 2 input fields.

```javascript
unlayer.setLinkTypes([
{
name: 'my_custom_link_type',
label: 'Custom',
attrs: {
href: 'https://mycustomlink.com/?email={{email}}&country={{country}}',
target: '_blank',
},
fields: [
{
name: 'email',
label: 'E-mail',
defaultValue: '',
inputType: 'email',
placeholderText: null,
options: [],
},
{
name: 'country',
label: 'Country',
defaultValue: 'usa',
inputType: null,
placeholderText: null,
options: [
{ value: 'usa', label: 'United States' },
{ value: 'other', label: 'Other' },
],
sortOptions: false,
},
],
},
]);
```
---
### Page Dropdown
Use a field's `options` to let users choose from your pages. Each option pairs a
display label with the value substituted into `href`. The dropdown scrolls when
the list exceeds the available space.
```javascript
const pageOptions = Array.from({ length: 6 }, (_, i) => ({
label: `Page ${i + 1}`,
value: `page_${i + 1}`,
}));
unlayer.setLinkTypes([
{
name: 'open_page',
label: 'Open Page',
attrs: { href: '{{page}}', target: '_self' },
fields: [
{
name: 'page',
label: 'Page',
defaultValue: 'page_1',
inputType: null,
placeholderText: 'Select a page',
options: pageOptions,
sortOptions: false,
},
],
},
]);
```
---
### JavaScript onClick Link
In this example, we will define a link type that uses JavaScript onClick instead of href. This is useful if you are using our landing page builder.

```javascript
unlayer.setLinkTypes([
{
name: 'my_custom_alert',
label: 'Show Alert',
attrs: {
onClick: 'alert("Hello World")',
},
},
]);
```
---
### File Download Link
```javascript
unlayer.setLinkTypes([
{
name: 'file_download',
label: 'File Download',
attrs: {
href: '{{file}}', // Link destination (file URL)
download: true, // Enables the download attribute
},
fields: [
{
name: 'file',
label: 'File',
defaultValue: undefined,
isMulti: false, // Single file selection
options: [
{
label: 'Open file management...',
value: '',
onClick(_option, _meta, done) {
// Simulate file manager popup to choose a file
const file = prompt('Enter the file name');
if (!file) return;
// Return the selected file to Unlayer
done({ label: 'Optional label here', value: `${file}.zip` });
},
highlight: true,
},
{
type: 'separator',
},
{
label: 'File 1',
value: 'https://website.com/file1.zip',
},
{
label: 'File 2',
value: 'https://website.com/file2.zip',
},
],
sortOptions: false,
},
],
},
]);
```
---
## Enable/Disable Defaults
You can enable or disable the default link types. `sms` link type is disabled by default because it's not supported by most email clients including Gmail, Yahoo and Outlook.
```javascript
unlayer.setLinkTypes([
{
name: 'phone',
enabled: true,
},
{
name: 'email',
enabled: true,
},
{
name: 'sms',
enabled: false,
},
]);
```
---
## Advanced
### Link Attributes
The editor has the ability to add or modify attributes in the link tag. These attributes can be set to support multiple values or a single value at a time. Chosen value(s) can be appended to an existing attribute or added as a new attribute.
#### Tags Example
A common example is appending multiple chosen tags to the `href` attribute in a link tag. In the following example, we will add support for multiple tags in the link editor and append it to the `href` attribute of the link tag.

You can use the following code sample to enable this feature.
```javascript
unlayer.setLinkTypesSharedConfig({
attrs: {
// 'data-tags': '{{tags}}',
'+href': '?tags={{tags}}', // append tags in the href attribute of link
},
fields: [
{
name: 'tags',
label: 'Tags',
defaultValue: [],
isClearable: true, // clear all tags
isCreatable: true, // allow creation of new tags
isMulti: true, // support multiple tags
limit: 2, // limit the number of items that can be selected when isMulti: true (optional)
limitMessage: 'You can only select up to 2 items', // custom message for when limit is reached (optional)
// optional - if creation is enabled
onCreateOption(inputValue, _meta, done) {
// Save or create inputValue in the database (if needed)
const newOption = {
label: inputValue,
value: inputValue,
};
done(newOption);
},
// existing tags
options: [
{
label: 'A',
value: 'a',
},
{
label: 'B',
value: 'b',
},
{
label: 'C',
value: 'c',
},
],
sortOptions: true,
},
],
});
```
---
## Link Management
The builder provides comprehensive tools for handling various types of links within your designs. Whether you’re creating links to websites, emails, phone numbers, or dynamic content, our platform allows for flexible link configuration to suit different use cases.
## Automatic links
:::info Version requirement
Automatic linking in Paragraph, Heading, and table text requires **Builder 1.526.0 or newer**.
:::
End users can create links in Paragraph, Heading, and table text without opening the link panel:
- **Typing:** A URL or email address becomes a link when the end user types a space or presses Enter after it.
- **Pasting:** URLs and email addresses in pasted plain or formatted text become links. Only addresses wholly within the pasted text are linked; text that was already in the design is left alone.
The following address forms are recognized:
| Text | Link destination |
| --------------------------------------------- | ------------------------- |
| `https://example.com` or `http://example.com` | The original URL |
| `ftp://example.com` | The original URL |
| `www.example.com` | `https://www.example.com` |
| `name@example.com` | `mailto:name@example.com` |
Surrounding punctuation is left outside the link. Closing brackets that belong to the URL are kept. Automatically created links open in a new tab by default.
### What stays unchanged
- Loading a saved design does not convert its existing plain-text addresses into links.
- Text inside an existing link is not linked again.
- The Button tool is excluded because a button is already a link.
- A URL that runs into a merge-tag token or continues across differently formatted text is not partially linked. Merge-tag placeholders that remain plain text within a URL, such as `https://example.com/?id={{user_id}}`, can remain part of the link.
### Undo automatic linking
Automatic links created after a space or paste have their own undo step. Undo removes the automatic link and keeps the URL text. If the end user continues typing immediately after the link is created, that typing can be included in the same undo step.
### Edit pasted links
Links pasted from documents or web pages retain their URL in the link panel, with either **Keep Formatting** or **Remove Formatting**. End users can open the panel to inspect or change the destination rather than re-entering it.
## Link configuration
Use the following pages to configure link types and predefined links:
By leveraging the link management options, you can create seamless, engaging, and dynamic experiences for your users, enhancing interactivity and enabling smooth navigation across different types of content.
---
## Special Links
Special links are predefined links that make it easier for the end-user to pick and set commonly used links for their buttons or links.
These could also be dynamic links that your system generates at the time the message is sent, typically because they include the message ID, the recipient's email, or some other variable. One of the most common one is the unsubscribe link.

Here's an example on how to define special links. It also allows nesting.
```javascript
unlayer.init({
specialLinks: [
{
name: 'Manage account',
href: 'https://[my-account]/',
target: '_self',
},
{
name: 'Frequently used',
specialLinks: [
{
name: 'Subscribe',
href: '[subscribe]',
target: '_blank',
},
{
name: 'Unsubscribe',
href: '[unsubscribe]',
target: '_blank',
},
],
},
],
});
```
---
## Localization
Set `locale` when initializing the editor to change the language of its user
interface. The default is `en-US`.
```javascript
unlayer.init({
locale: 'fr-FR',
});
```
The editor first looks for the full locale, then falls back to its base
language. For example, `fr-CA` can use Canadian French overrides and then
French defaults.
The translation reference on this page lists the languages and keys shipped
with the Editor version selected in the docs.
## Built-in Editor locales
The Editor ships with these locale codes: `ar`, `ca`, `cs`, `da`, `de`, `en`,
`en-CA`, `es`, `et`, `fa`, `fi`, `fr`, `fr-CA`, `hu`, `id`, `it`, `ja`,
`ko-KR`, `nl`, `no`, `pl`, `pt-BR`, `pt-PT`, `ru`, `sv`, `tr`, `uk`,
`vi-VN`, `zh-CN`, and `zh-TW`. The translation reference below remains the
source of truth for the selected docs version.
## Built-in Image Editor locales
The Image Editor ships with these locale codes: `de`, `en`, `es`, `fr`, `it`,
`ja`, `ko`, `nl`, `pt`, and `zh`. Select **Image Editor** in the translation
reference below to browse its keys.
## Override translations
Pass only the keys you want to change under the matching locale:
```javascript
unlayer.init({
locale: 'fr-FR',
translations: {
'fr-FR': {
'tools.tabs.content': 'Contenu',
'tools.tabs.row': 'Lignes',
},
},
});
```
The same `translations` object customizes Image Editor keys. Editor-specific
keys use the `image_editor.*` prefix; shared host-credit notices use
`labels.credits.*` keys.
If your project uses
[`@unlayer/types`](https://www.npmjs.com/package/@unlayer/types), translation
keys are typed as `UnlayerTranslationKey`, so your editor can autocomplete
them.
## Add a custom language
You can also supply every required key for a locale that is not built in:
```javascript
unlayer.init({
locale: 'xx',
translations: {
xx: {
'tools.tabs.content': 'Content',
'tools.tabs.row': 'Rows',
// ...
},
},
});
```
Use English in the translation reference below as the complete key list, then
provide values for your locale. Missing keys fall back to the editor's default
messages.
## Translation reference
Browse the exact translation keys shipped with the Editor version selected in
the docs menu. Choose a product and language, search by key or text, or copy the
full locale or filtered results as JSON.
The latest reference reads directly from the product translation files.
Released docs use an immutable snapshot from that Editor version, so their keys
do not change later. Copied JSON has the shape expected by the `translations`
option in `unlayer.init()`.
---
## Security Settings
Unlayer allows developers to enforce **Identity Verification** to enhance the security of the embedded builder. By verifying the identity of the users interacting with the builder, you can prevent unauthorized third parties from impersonating your logged-in users and misusing the builder. This feature is especially important for ensuring that only authenticated users have access to the builder.
We strongly recommend that you enforce identity verification to protect your application and users.
---
## Prerequisites
In order to enable enhanced security and identity verification, you must set up the following first:
- [End-User Identification](./end-user-identification.md)
## Setup Identity Verification
To set up identity verification, you’ll need to generate a secure [HMAC](https://en.wikipedia.org/wiki/Hash-based_message_authentication_code) (Hash-based Message Authentication Code) signature on your server for each logged-in user. This HMAC signature is then passed to Unlayer along with the user’s information when initializing the editor.
## Sending User Object with HMAC Signature
When initializing the Unlayer builder, you need to pass a user object that includes:
- A unique id for the logged-in user
- A securely generated signature (HMAC)
- Optional information such as name and email for the user
Here’s an example of how to initialize the builder with a `user` object:
```javascript
unlayer.init({
user: {
id: 1, // The user's unique ID
signature: 'XXX', // HMAC signature generated on the server
name: 'John Doe', // Optional user name
email: 'john.doe@acme.com', // Optional user email
},
});
```
---
## Generating the HMAC Signature
To ensure security, the HMAC signature must be generated **on your server** using a secret key. The secret key must never be exposed in client-side code or shared publicly. Here’s how to generate the signature using Node.js and the crypto module:
:::warning Project Secret
Your Project Secret is a sensitive piece of information that should never be exposed in your client-side code, repositories, or any place where it could be accessed by third parties. Always store it securely on your server and limit access to it.
:::
```javascript Node.js
const crypto = require('crypto');
const signature = crypto
.createHmac('sha256', '[PROJECT-SECRET]') // secret key (keep safe!)
.update('[USER-ID]')
.digest('hex');
```
```ruby Ruby on Rails
require 'openssl'
OpenSSL::HMAC.hexdigest(
'sha256', # hash function
'[PROJECT-SECRET]', # secret key (keep safe!)
'[USER-ID]' # user's id
)
```
```php PHP
hash_hmac(
'sha256', // hash function
$user->id, // user's id
'[PROJECT-SECRET]' // secret key (keep safe!)
);
```
```python Django (Python 3)
hmac.new(
b'[PROJECT-SECRET]', # secret key (keep safe!)
bytes(request.user.id, encoding='utf-8'), # user's id
digestmod=hashlib.sha256 # hash function
).hexdigest()
```
You can get your project secret from project settings in the Unlayer [console](https://console.unlayer.com).
### Explanation
- **[PROJECT-SECRET]**: This is your project-specific secret key. It must be kept secure and never exposed to the public or in your client-side code.
- **[USER-ID]**: This is the unique ID for the user (for example, id: 1 in the user object).
- The resulting HMAC signature is a cryptographic hash that verifies the identity of the user when passed to Unlayer during initialization.
---
## Why Use Identity Verification?
- **Prevent Impersonation**: Without identity verification, third parties could potentially impersonate your logged-in users and access or modify content in the editor. By requiring a valid HMAC signature, you ensure that only authorized users can interact with the Unlayer editor.
- **Enhanced Security**: This feature ensures that your users’ actions in the builder are authenticated and protected from potential tampering.
---
## Example Workflow
1. **User logs in** to your application.
2. **On the server**, you generate an HMAC signature using the user’s unique ID and your secret key.
3. **Initialize the Unlayer builder** with the user object containing the user’s ID and the generated HMAC signature.
4. Unlayer **verifies the signature** and ensures that the user accessing the editor is authenticated.
---
## Notes
- Do not commit your secret key to any public repositories or client-side code.
- Always generate the HMAC signature server-side to prevent exposure of your secret key.
- Identity verification only affects users interacting with the Unlayer builder within your application, ensuring they are properly authenticated.
---
## Restricting Features Per End-User
`unlayer.init({ features })` configures the editor for everyone who loads it. A signed feature
policy does something different: it sets what **one specific end-user** is permitted to do. You
sign it with your Project Secret, so the permission belongs to that end-user and travels with them.
:::info When you need this
Only when **different end-users of the same project should have different features** — for example
full template generation for your Pro tier but not your Free tier. To configure a feature for
everyone who loads the editor, use `unlayer.init({ features })`; to remove one from your workspace
altogether, ask your account manager.
:::
### Building the Token
The token uses the same Project Secret as identity verification, but derives a policy-only signing key from it with HKDF-SHA256. It has three parts joined by dots: the `v1` format version, a base64url-encoded payload, and the HMAC-SHA256 of the version and encoded payload, written as lowercase hexadecimal. The signature comparison is case-sensitive, so uppercase hex or a base64 digest fails verification.
```javascript Node.js
const { createHmac, hkdfSync } = require('node:crypto');
const projectSecret = '[PROJECT-SECRET]';
const version = 'v1';
const salt = 'unlayer:end-user-policy-token:v1:salt';
const info = 'unlayer:end-user-policy-token:v1:signing-key';
const claims = {
id: String(user.id), // must match the id you pass to unlayer.init
exp: Math.floor(Date.now() / 1000) + 60 * 60 * 8, // unix seconds
features: {
ai: {
fullTemplateGeneration: user.plan === 'pro',
},
},
};
const payload = Buffer.from(JSON.stringify(claims)).toString('base64url');
const policyKey = Buffer.from(
hkdfSync('sha256', projectSecret, salt, info, 32),
);
const signedPayload = `${version}.${payload}`;
const signature = createHmac('sha256', policyKey)
.update(signedPayload)
.digest('hex');
const token = `${signedPayload}.${signature}`;
```
```ruby Ruby on Rails
require 'base64'
require 'json'
require 'openssl'
claims = {
id: user.id.to_s,
exp: Time.now.to_i + 60 * 60 * 8,
features: { ai: { fullTemplateGeneration: user.plan == 'pro' } }
}
project_secret = '[PROJECT-SECRET]'
version = 'v1'
salt = 'unlayer:end-user-policy-token:v1:salt'
info = 'unlayer:end-user-policy-token:v1:signing-key'
payload = Base64.urlsafe_encode64(claims.to_json, padding: false)
# HKDF-SHA256 extract, then the single expand block needed for a 32-byte key.
prk = OpenSSL::HMAC.digest('SHA256', salt, project_secret)
policy_key = OpenSSL::HMAC.digest('SHA256', prk, info + "\x01")
signed_payload = "#{version}.#{payload}"
signature = OpenSSL::HMAC.hexdigest('sha256', policy_key, signed_payload)
token = "#{signed_payload}.#{signature}"
```
```php PHP
$claims = [
'id' => (string) $user->id,
'exp' => time() + 60 * 60 * 8,
// PHP encodes an empty array as a JSON array, which is rejected. Use
// new stdClass() for an empty `features` object or an empty nested group.
'features' => ['ai' => ['fullTemplateGeneration' => $user->plan === 'pro']],
];
$projectSecret = '[PROJECT-SECRET]';
$version = 'v1';
$salt = 'unlayer:end-user-policy-token:v1:salt';
$info = 'unlayer:end-user-policy-token:v1:signing-key';
$payload = rtrim(strtr(base64_encode(json_encode($claims)), '+/', '-_'), '=');
// HKDF-SHA256 extract, then the single expand block needed for a 32-byte key.
$prk = hash_hmac('sha256', $projectSecret, $salt, true);
$policyKey = hash_hmac('sha256', $info . "\x01", $prk, true);
$signedPayload = $version . '.' . $payload;
$signature = hash_hmac('sha256', $signedPayload, $policyKey);
$token = $signedPayload . '.' . $signature;
```
```python Django (Python 3)
claims = {
'id': str(user.id),
'exp': int(time.time()) + 60 * 60 * 8,
'features': {'ai': {'fullTemplateGeneration': user.plan == 'pro'}},
}
project_secret = b'[PROJECT-SECRET]'
version = 'v1'
salt = b'unlayer:end-user-policy-token:v1:salt'
info = b'unlayer:end-user-policy-token:v1:signing-key'
payload = base64.urlsafe_b64encode(
json.dumps(claims).encode()
).rstrip(b'=').decode()
# HKDF-SHA256 extract, then the single expand block needed for a 32-byte key.
prk = hmac.new(salt, project_secret, hashlib.sha256).digest()
policy_key = hmac.new(prk, info + b'\x01', hashlib.sha256).digest()
signed_payload = f'{version}.{payload}'
signature = hmac.new(policy_key, signed_payload.encode(), hashlib.sha256).hexdigest()
token = f'{signed_payload}.{signature}'
```
:::warning Derive the key and sign the versioned payload
Use the exact HKDF salt and info above, then compute the HMAC over `v1.`. Do not sign with the Project Secret directly or rebuild the JSON to sign — direct signing can confuse this credential with an identity signature, while re-encoding can change key order and number formatting between languages.
:::
### Passing the Token
Send the generated token to the browser and pass it in the `user` object. It replaces `signature`:
```javascript
unlayer.init({
projectId: 1234,
user: {
id: 1, // must match the id inside the token
name: 'John Doe',
email: 'john.doe@acme.com',
featurePolicyToken: '[GENERATED-TOKEN]',
},
});
```
The editor reflects the permissions in the token, and Unlayer honours them for that end-user.
Omitting `user.featurePolicyToken` or setting it to `null` means no policy token was supplied. This
supports integrations that serialize an unavailable token as `null`; the editor then uses the normal
legacy-signature or unsigned flow. An empty string is not missing: like any other malformed,
expired, wrongly signed, or mismatched non-null value, it fails authentication even when Identity
Verification is off. Projects that require end-user feature policies also reject `null`.
:::warning Keep your editor version current
A policy applies to a project whatever editor version it runs, but the editor's own handling of it
— hiding the features an end-user is not permitted to use, and recognising the most recently added
paths — needs a current build. If you [pin your editor version](/builder/version-management), move
to a current release before relying on a policy.
:::
### What `features` Accepts
The `features` object uses the boolean feature-flag portion of the shape you pass to `unlayer.init`, so you write a restriction once, in one vocabulary. It is required, although it may be an empty object when the token is being introduced before restrictions are assigned. It must encode as a JSON object: in PHP, `json_encode([])` produces `[]`, so pass `new stdClass()` instead.
Every leaf must be `true` or `false`; objects are containers for nested flags. Configuration values, arrays, `null`, duplicate or dotted keys, unsafe object keys, and nesting deeper than eight levels make authentication fail instead of being ignored. Include only feature flags in the signed object — do not copy configuration such as `ai.model` or `textEditor.customButtons` into it.
These paths are enforced by the server:
| Path | Effect when `false` |
| --------------------------- | ----------------------------------------------------------------------------------------------------------------- |
| `ai.assistant` | This end-user cannot use the builder's AI Assistant or the standalone Image Editor's AI Assistant. |
| `ai.fullTemplateGeneration` | This end-user cannot generate full templates, pages, or bodies. Row, content, and text edits still work. |
| `ai.magicImage` | This end-user cannot generate, edit, or read recent Magic Images, and cannot use the Image Editor's AI Assistant. |
| `ai.smartButtons` | This end-user cannot generate Smart Button suggestions. |
| `ai.smartHeadings` | This end-user cannot generate Smart Heading suggestions. |
| `ai.smartImageAltText` | This end-user cannot generate image alt text. |
| `ai.smartParagraph` | This end-user cannot generate Smart Paragraph suggestions. |
| `ai.smartText` | This end-user cannot generate Smart Text suggestions. |
| `inboxPreviews` | This end-user cannot generate inbox previews. |
| `sendTestEmail` | This end-user cannot send test emails. |
| `stockImages` | This end-user cannot search the stock image library. Their own uploads are unaffected. |
| `userUploads` | This end-user cannot upload images. Stock image search is unaffected. |
Any other flag you set to `false` is turned off by the editor for this end-user, on top of what `unlayer.init` configures; only the paths above are also enforced by Unlayer's servers. A `true` value never turns anything on — it only means the policy does not restrict that flag, and `unlayer.init` still decides. The editor applies a signed `false` after `unlayer.init`, so sign only flags where `false` means "off": for a flag where `false` is the looser setting, such as `stockImages.safeSearch`, a signed `false` overrides the `true` you pass to `unlayer.init`.
Each path stands on its own — apart from the two shorthands below, denying one never implies
another. In particular, `ai.smartText: false` leaves Smart Paragraph permitted.
Smart Text and Smart Paragraph run the same text generation, and the server checks whichever path
matches the surface a request names. Denying only one of them hides that surface in the editor, but
the end-user can still get the same generation through the other. To stop an end-user from
generating that text, deny both `ai.smartText` and `ai.smartParagraph`.
Two shorthands disable everything beneath them, matching how `unlayer.init` behaves:
```javascript
features: {
ai: false,
} // same as disabling every ai.* path
features: {
ai: {
enabled: false,
},
} // same
```
### Rules to Keep in Mind
- **A policy can only restrict.** It never grants a feature your plan does not include. If your subscription lacks the AI Assistant, setting `ai.assistant: true` changes nothing.
- **`unlayer.init` can restrict further, never less.** If the token allows a feature and `unlayer.init` disables it, it stays hidden.
- **The `id` in the token must match `user.id`.** A mismatch fails verification.
- **Generate the token on your server.** The Project Secret must never reach the browser.
### Choosing an Expiry
`exp` is required, in unix seconds. The editor session expires with it, so **set it to at least the length of a working session in your application** — typically several hours. A short expiry (minutes) will interrupt users mid-edit, because the editor has no way to fetch a fresh token on its own; the page must be reloaded with a newly generated one.
### Migrating From `signature`
By default, `featurePolicyToken` and `signature` are both accepted so you can roll the token out gradually without breaking anyone. This compatibility mode is for migration only: a retained signature has no expiry or feature restrictions and can be presented without the policy.
Finish the migration in this order:
1. Every end-user receives a `user.featurePolicyToken`.
2. Your app no longer sends `signature`. When a request carries both, the feature policy token is what authenticates — but a signature carries no policy, so while your app still issues one it can be presented on its own instead.
3. In **Security Settings**, enable **Require End-User Feature Policies**. Enabling it also enables Identity Verification. From that point on, authentication fails when `user.featurePolicyToken` is missing or when only a legacy signature is supplied.
Use a signed token with `features: {}` as the positive control before enabling the requirement. It proves every active integration can create and exchange policy-backed sessions without changing feature access. Once required mode is enabled, it is enforced by the editor bootstrap and by every editor API request, including requests made with sessions issued before the setting changed. Those sessions stop working on their next request, so an end-user who was still on a legacy signature must reload the editor with a `featurePolicyToken`.
Signatures do not expire. Required mode rejects them without requiring a secret rotation. If you also want to invalidate old signatures and policy tokens cryptographically, reset the Identity Verification Secret in the [console](https://console.unlayer.com). That invalidates all credentials signed with the old secret at once, so coordinate it with a deploy where every end-user already receives a new `featurePolicyToken`.
Rotating the secret prevents old signatures and policy tokens from creating new bootstrap credentials. A bootstrap credential that was already issued can still be exchanged for a session until its original expiry (at most seven days from authentication), and the resulting session remains usable until that same limit. Refreshing session data never extends the limit.
New sessions retain server-issued proof that their original identity credential was verified, so operations such as Send Test Email trust the session until it expires instead of rechecking a credential against the rotated secret. Sessions issued before that proof was recorded can still fail those operations; reload them with a newly signed credential after rotation. Plan the rotation window accordingly.
---
## Style Guide
This feature helps you create templates that follow a desired brand style. You can configure pre-defined styles for each tool, which can then be applied by your users using a dropdown.
When a tool has a Style Guide applied, its styles cannot be edited, ensuring it maintains the expected appearance.
## Setting up Style Guide
### Enable feature
```javascript
unlayer.init({
features: {
styleGuide: true,
},
});
```
### Defining the Style Guide styles
To define Style Guide styles, use the `unlayer.setStyleGuide({ ... })` method. See the examples below for API implementation details. All tool values are supported inside the `values` field.
#### Button example
##### Button - Default

##### Button - Primary Style

##### Button - Secondary Style

##### Code
```javascript
unlayer.setStyleGuide({
tools: {
button: {
styles: {
primary: {
label: 'Primary Button',
values: {
buttonColors: {
color: '#ffffff',
backgroundColor: '#000000',
hoverColor: '#ffffff',
hoverBackgroundColor: '#000000',
},
border: {
borderTopWidth: '1px',
borderTopStyle: 'solid',
borderTopColor: '#000000',
borderLeftWidth: '1px',
borderLeftStyle: 'solid',
borderLeftColor: '#000000',
borderRightWidth: '1px',
borderRightStyle: 'solid',
borderRightColor: '#000000',
borderBottomWidth: '1px',
borderBottomStyle: 'solid',
borderBottomColor: '#000000',
},
},
},
secondary: {
label: 'Secondary Button',
values: {
buttonColors: {
color: '#000000',
backgroundColor: '#ffffff',
hoverColor: '#000000',
hoverBackgroundColor: '#ffffff',
},
border: {
borderTopWidth: '1px',
borderTopStyle: 'solid',
borderTopColor: '#000000',
borderLeftWidth: '1px',
borderLeftStyle: 'solid',
borderLeftColor: '#000000',
borderRightWidth: '1px',
borderRightStyle: 'solid',
borderRightColor: '#000000',
borderBottomWidth: '1px',
borderBottomStyle: 'solid',
borderBottomColor: '#000000',
},
},
},
},
},
},
});
```
#### Default Styles
##### Initial Style Guide value
In this example, newly dropped buttons would have the `primary` Style Guide style by default:
```javascript
unlayer.init({
tools: {
button: {
properties: {
_styleGuide: {
value: 'primary',
},
},
},
},
});
```
##### Default style without any Style Guide value
In this example, newly dropped buttons without any Style Guide set would have this style by default:
```javascript
unlayer.init({
tools: {
button: {
properties: {
buttonColors: {
editor: {
defaultValue: {
backgroundColor: 'green',
// ...
},
},
},
},
},
},
});
```
#### Row example
##### Row - Default

##### Row - Blue Style

##### Row - Green Style

##### Code
```javascript
unlayer.setStyleGuide({
tools: {
rows: {
styles: {
blue: {
label: 'Blue Row',
values: {
backgroundColor: '#E5F2FF',
},
},
green: {
label: 'Green Row',
values: {
backgroundColor: '#E5FFEC',
},
},
},
},
},
});
```
#### Body example
```javascript
unlayer.setStyleGuide({
tools: {
bodies: {
styles: {
green: {
label: 'Green',
values: {
textColor: '#206154',
backgroundColor: '#BFEDD2',
linkStyle: {
body: true,
linkColor: '#169179',
linkHoverColor: '#169179',
linkHoverUnderline: true,
linkUnderline: true,
},
},
},
},
},
},
});
```
#### Custom Tool example
```javascript
unlayer.setStyleGuide({
tools: {
'custom#my_custom_tool': {
styles: {
green: {
label: 'Green',
values: {
color: '#206154',
},
},
},
},
},
});
```
---
## Tab Management
## What is a Tab?
The side panel in the editor consists of various tabs like Content, Blocks, Body, Images, Uploads, etc. Each tab provides access to unique functions of the editor.

---
## Enable / Disable Tabs
You can enable or disable any tab. For default tabs, the key is the tab name. For custom tabs, you have to prefix your tab name with `custom#`.
```javascript
unlayer.init({
tabs: {
content: {
enabled: true,
},
blocks: {
enabled: false,
},
'custom#my_tab': {
enabled: false,
},
},
});
```
---
## Default Active Tab
By default, the "Content" tab is active when editor loads. You can change it to be any other tab.
```javascript
unlayer.init({
tabs: {
blocks: {
active: true,
},
},
});
```
---
## Reposition Tabs
You can change the default positions of tabs.
```javascript
unlayer.init({
tabs: {
content: {
position: 1,
},
blocks: {
position: 2,
},
'custom#my_tab': {
position: 3,
},
},
});
```
---
## Change Icon
You can change the icon of any tab. Icon can be class name of any [fontawesome icon](https://fontawesome.com/icons?d=gallery), or a URL for your icon's image.
```javascript
unlayer.init({
tabs: {
content: {
icon: 'fa-user',
},
blocks: {
icon: 'https://my.cdn.com/blocks_icon.png',
},
},
});
```
---
## Create a Custom Tab
### Register your Tab
The first step is to register your custom tab using the `registerTab` method.

:::info Custom JavaScript
The following JavaScript has to be passed in the customJS parameter when initializing Unlayer. **registerTab**, and **createPanel** methods are only available there. [Learn more](../customization/appearance/custom-js-css.md).
:::
```javascript
unlayer.registerTab({
name: 'my_tab',
label: 'My Tab',
icon: 'fa-smile',
supportedDisplayModes: ['web', 'email'],
renderer: {
Panel: unlayer.createPanel({
render() {
return 'I am a custom tab.';
},
}),
},
});
```
It needs some configuration options which are explained below:
| Option | Description |
| :------------------------ | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **name** | Unique name for your tab |
| **label** | Label that users see in the side panel |
| **icon** | Icon that users see in the side panel. The value can be class name of any [fontawesome icon](https://fontawesome.com/icons?d=gallery), or a URL for your icon's image |
| **position** | Optionally, you can specify the position you want the tab to appear on |
| **supportedDisplayModes** | Which display modes will this tab work in. Default value is `['email', 'web']` |
---
### Example using React
Here's an example that uses a React component.
```javascript
const MyPanel = () => I am a custom tab.;
unlayer.registerTab({
name: 'my_tab',
label: 'My Tab',
icon: 'fa-smile',
supportedDisplayModes: ['web', 'email'],
renderer: {
Panel: MyPanel,
},
});
```
---
## Dev Tab
The Dev Tab is a special tab that appears in the editor's side panel when running in development environments. It provides developers with useful information about the editor configuration, authentication status, and version information.
### When Does the Dev Tab Appear?
The Dev Tab automatically appears in development environments and is hidden in production. This ensures that your end-users never see this developer-focused interface.
### Disable the Dev Tab
If you want to disable the Dev Tab during development, you can do so by setting the `devTab` feature to `false` in your editor configuration:
```javascript
unlayer.init({
features: {
devTab: false,
},
});
```
---
## Clean Paste
This feature allows you to control how content is pasted into the text editor from external sources, ensuring that unwanted formatting is either removed or retained based on your configuration. This is particularly useful for maintaining a consistent design and avoiding issues that can arise from copying content with conflicting styles.
## Configuration
By default, clean pasting is set to “**confirm**,” where the user is prompted to decide whether to keep all formatting or only basic formatting when pasting content. You can configure the behavior of clean pasting using the `unlayer.init()` method within the textEditor settings.
| Value | Description |
| :------------------------ | :-------------------------------------------------------------------------------------- |
| **true** | Clean pasting is turned on. No formatting will be added to the pasted content. |
| **false** | Clean pasting is turned off. All formatting from the pasted content will be preserved. |
| **basic** | Only basic formatting (such as bold, italic, and headings) and structure are preserved. |
| **confirm**(default) | Prompts the user to decide whether to keep all formatting or only basic formatting. |
---
### Enable Clean Paste
```javascript
unlayer.init({
features: {
textEditor: {
cleanPaste: true, // Clean pasting is always on, removing all formatting
},
},
});
```
When `cleanPaste: true`, all formatting is stripped when content is pasted, ensuring that only plain text is inserted.
### Disable Clean Paste
```javascript
unlayer.init({
features: {
textEditor: {
cleanPaste: false, // Disable clean pasting, keep all formatting
},
},
});
```
Setting `cleanPaste: false` preserves all formatting from the source when content is pasted into the text editor.
### Preserving Basic Formatting
```javascript
unlayer.init({
features: {
textEditor: {
cleanPaste: 'basic', // Keep structure and basic formatting only
},
},
});
```
When `cleanPaste: 'basic'`, the editor will keep only basic formatting, such as bold, italic, headings, and structure. More complex formatting (such as colors, font sizes, etc.) will be removed.
### Prompting the User (Default Behavior)
```javascript
unlayer.init({
features: {
textEditor: {
cleanPaste: 'confirm', // Prompt the user to decide whether to clean paste
},
},
});
```
By default, the editor will prompt users when they paste content, asking them whether they want to preserve all formatting or just the basic structure. This gives users more control over the pasted content.
---
## Best Practices
- **Consistent Design**: Enabling clean paste (true or basic) helps maintain a consistent design by preventing unwanted or conflicting styles from external sources from being pasted into the editor.
- **User Control**: The default confirm option is useful when you want to give users flexibility over how content is pasted, allowing them to choose whether to keep or remove formatting.
- **Prevent Styling Issues**: Use clean paste in situations where preserving external formatting could lead to styling issues, particularly when users copy content from word processors or websites with complex styles.
By leveraging this feature, developers can ensure that pasted content is clean and consistent with the intended design while offering flexibility in how formatting is handled.
---
## Custom Buttons
This feature allows developers to add custom buttons to the text editor, providing the ability to extend and enhance the editor’s functionality with advanced controls. Custom buttons can be used for a wide range of purposes, such as inserting predefined text, triggering custom actions, or integrating with third-party services.
## Adding Custom Buttons
You can add custom buttons to the text editor by configuring the `customButtons` array in the `unlayer.init()` method. Each button has several properties that define its name, label, icon, and actions.

```javascript
unlayer.init({
features: {
textEditor: {
customButtons: [
{
name: 'my_button', // Unique identifier for the button
text: 'My Button', // The label that will appear on the button
icon: 'bookmark', // Icon that will appear on the button (optional)
onSetup: () => {}, // Function executed when the button is set up
onAction: (data, callback) => {
console.log(data.text); // Log or manipulate text editor data
callback(data.text + ' Updated'); // Perform action and update the text
},
},
],
},
},
});
```
### Button Attributes
- **name**: A unique identifier for the button, used to reference it programmatically.
- **text**: The label of the button that will be displayed in the editor’s toolbar.
- **icon**: Icon can be a class name of any [FontAwesome icon](https://fontawesome.com/icons?d=gallery), a URL for your icon's image or a custom SVG code.
- **onSetup**: A function that runs when the button is set up in the editor. You can use this function to initialize or prepare the button for use.
- **onAction**: The main action handler that runs when the user clicks the button. It receives two arguments:
- **data**: The current data in the text editor (e.g., text, formatting).
- **callback**: A function used to perform the desired action and update the editor with new content or behavior.
### Custom SVG Icons
You can also use custom SVG code as the icon. Here’s an example:
```javascript
unlayer.init({
features: {
textEditor: {
customButtons: [
{
name: 'my_button',
text: 'My Button',
icon: ' ', // Insert your custom SVG here
},
],
},
},
});
```
---
## Best Practices
- **Clear Naming and Icons**: Choose meaningful names and icons for your custom buttons to make it clear to end-users what the button does.
- **Action Feedback**: Provide immediate visual feedback when users click a custom button. For example, you can update the text in the editor or show a notification indicating that the action was successful.
- **Limit Complexity**: While custom buttons can be powerful, keep their functionality focused and straightforward to ensure a smooth user experience.
By using this feature, developers can build custom, advanced controls directly into the text editor, allowing for powerful text manipulation and interaction capabilities that go beyond standard editor features.
---
## Emojis
This feature allows users to insert emojis directly into their content using the text editor, adding a fun and expressive element to emails, pages, and other designs. Emojis can enhance communication by conveying emotion or emphasis in a simple, visual way.
## Enable or Disable
By default, the emoji feature is enabled, but you can choose to disable or enable it using the `unlayer.init()` method within the textEditor configuration.
```javascript
unlayer.init({
features: {
textEditor: {
emojis: true, // Enable emoji support in the text editor
},
},
});
```
Setting `emojis: true` allows users to access the emoji picker within the text editor and insert emojis into their content.
---
## Best Practices
- **Context-Appropriate Use**: Emojis can add a fun and engaging element to content, but it’s important to consider the context and audience.
- **Cross-Platform Compatibility**: While emojis are widely supported across devices and platforms, some email clients or devices may not render all emojis correctly.
---
## Inline Font Controls
This feature allows users to change the font family, font size, and text alignment directly within the text editor via inline controls. While these controls provide a quick way to format text, they are not recommended due to the availability of more robust font controls in the right panel, which offers better responsiveness across devices.
By default, inline font controls are disabled. You can enable or disable this feature using the `unlayer.init()` method within the textEditor configuration.
## Enable Inline Font Controls
```javascript
unlayer.init({
features: {
textEditor: {
inlineFontControls: true, // Enable inline font controls in the text editor
},
},
});
```
Setting `inlineFontControls: true` will allow users to adjust font family, size, and alignment directly within the text editor, using inline options.
## Disable Inline Font Controls (Recommended)
```javascript
unlayer.init({
features: {
textEditor: {
inlineFontControls: false, // Disable inline font controls (default behavior)
},
},
});
```
Setting `inlineFontControls: false` disables the inline font controls, encouraging users to manage font settings from the right panel, which provides more comprehensive and device-friendly options.
---
## Best Practices
- **Right Panel Usage**: We recommend keeping inline font controls disabled. The right panel offers a more consistent and responsive way to manage text formatting, including font family, font size, and alignment. This approach ensures that text renders properly across different devices and screen sizes.
- **Consistency Across Devices**: By using the right panel for font controls, you ensure that font settings are applied more uniformly, especially when switching between mobile and desktop views. This makes your design more responsive and adaptable.
- **Avoiding Clutter**: Disabling inline font controls reduces potential clutter in the editor, keeping the design cleaner and encouraging users to focus on using the more powerful formatting options available in the right panel.
---
## When to Enable
While it is generally recommended to use the right panel for font settings, you may consider enabling inline font controls if:
- Users need quick access to font adjustments directly within the editor.
- You’re working in specific cases where users prefer inline formatting over panel-based controls.
By managing this feature, you can decide how users interact with text formatting within the editor. Keeping this feature disabled ensures a more consistent design experience, with better responsiveness across devices, while enabling it can provide quicker access for users who need direct text formatting control.
---
## Text Management
This section allows developers to configure the text editor features available within the builder. These settings enable fine-grained control over text editing functionalities, such as spell checking, tables, font controls, and more, allowing you to customize the text editing experience for your end-users.
This section covers:
By configuring these options, developers can tailor the text editing experience to meet the needs of their users, ensuring both flexibility and control over content creation within the builder.
---
## Spell Checker
This feature provides automatic spelling checks within the text editor, ensuring that end-users can easily identify and correct spelling errors as they create content. This functionality enhances the overall quality of the text, reducing errors and improving readability.
## Enable or Disable
The spell checker is on by default in the Paragraph, Heading and Button tools and in table cells. It uses the browser's own spell check, so misspelled words are underlined while a block is being edited, in the languages the user's browser checks.
To turn it off, set `spellChecker` to `false` in the `textEditor` configuration:
```javascript
unlayer.init({
features: {
textEditor: {
spellChecker: false, // Turn off the spell checker
},
},
});
```
Setting `spellChecker: false` also turns it off in the legacy Text tool.
---
## Best Practices
- **Content Quality**: It’s recommended to keep the spell checker enabled to ensure higher content quality and reduce the chance of typographical errors in emails, pages, or popups.
- **User Experience**: For applications where language precision is important, the spell checker can help users improve their content without needing external tools.
---
## Tables
This feature allows users to create and edit tables directly within the text editor, making it easier to organize and display structured data. This functionality is especially useful for creating layouts, comparison charts, or any content that requires tabular representation.
:::warning
Tables within the text editor are only supported in the deprecated [Text](/builder/latest/tools/text) tool. The [Paragraph](/builder/latest/tools/paragraph#migrating-from-text-tool) tool does not support tables in the text editor. For current table functionality, use the dedicated [Table](/builder/latest/tools/table) tool available on non-legacy plans.
:::
## Enable or Disable
The tables feature is disabled by default. You can enable or disable the ability to insert tables using the `unlayer.init()` method under the textEditor configuration.
```javascript
unlayer.init({
features: {
textEditor: {
tables: true, // Enable tables in the text editor
},
},
});
```
Setting `tables: true` enables the table creation and editing tools in the text editor. Users will be able to insert tables, modify the number of rows and columns, and adjust table formatting.
---
## Best Practices
- **Structured Data**: For content requiring organized information, like pricing grids or data comparisons, enabling tables can significantly improve the readability and layout.
- **Responsive Design**: When using tables, especially in emails, it’s important to ensure that they are designed to be responsive. Emails are often viewed on mobile devices, and large or complex tables may not display well on smaller screens.
- **Email Client Compatibility**: Tables in emails can behave differently across various email clients (such as Gmail, Outlook, etc.). Be mindful of compatibility issues by testing the email templates on different clients. Some email clients, particularly older ones, may not fully support modern table styling or responsive layouts.
- **Overcomplicated Layouts**: When end-users design emails, they can create overly complex tables with too many rows, columns, or nested tables, and this can lead to poor rendering in certain email clients.
---
## Text Direction
This feature enables text direction controls within the text editor, allowing users to switch between left-to-right (LTR) and right-to-left (RTL) text directions.
## Enable or Disable
By default, the text direction feature is disabled. You can enable or disable the text direction controls using the `unlayer.init()` method within the textEditor configuration.
```javascript
unlayer.init({
features: {
textEditor: {
textDirection: true, // Enable text direction controls
},
},
});
```
---
## Trigger Change Event
This feature gives developers more control over how the text editor triggers changes during editing. You can configure the text editor to trigger change events more effectively during text editing and control how frequently those events are fired using a debounce mechanism.
Here’s the API configuration for the new options:
```javascript
unlayer.init({
features: {
textEditor: {
triggerChangeWhileEditing: true, // default: true
debounce: 300, // default: 300 (ms)
},
},
});
```
---
## API Options
- **triggerChangeWhileEditing** (default: true)
- **Description**: This option controls whether the text editor should trigger the `design:updated`event while the end-user is actively editing text. By default, this is set to true, meaning that the event will be fired in real-time as text is being updated.
- **Use Case**: If you’re building an application where real-time updates or auto-saving features are critical, you should keep this option enabled to ensure that changes are consistently saved.
- **debounce** (default: 300ms)
- **Description**: This option allows you to control the debounce time for triggering the `design:updated` event. Debouncing ensures that the event isn’t triggered excessively during rapid typing or frequent text changes. By default, the debounce time is set to 300 milliseconds.
- **Use Case**: You can adjust the debounce value based on the performance needs of your application. A higher value will reduce the frequency of change events (better for performance), while a lower value will make the change detection more responsive (better for real-time feedback).
---
## Example Use Case
If you want to ensure that every change in the text editor is registered and saved without delay, you can configure the text editor to trigger updates with minimal debouncing:
```javascript
unlayer.init({
features: {
textEditor: {
triggerChangeWhileEditing: true,
debounce: 100, // Trigger changes every 100ms during editing
},
},
});
```
In this example:
- `triggerChangeWhileEditing: true` ensures that changes are consistently tracked.
- `debounce: 100` makes the event more responsive, ideal for scenarios where real-time feedback or frequent auto-saving is required.
---
## Notes
- **Performance Considerations**: Lower debounce values can lead to frequent event triggering, which may have performance implications for very large designs or complex layouts. Adjust the debounce time based on the complexity of your design and the performance requirements of your host application.
- **Default Behavior**: By default, both options are set to ensure real-time event handling with reasonable performance, but you can customize these values to fit the needs of your users and application.
---
## Legacy Templates
:::warning
Loading HTML content that includes full document structure (like \ or \ tags) is no longer supported since version **1.249.0**. To continue using this feature, please [lock your editor version](/builder/version-management) to **1.227.0 or lower**.
:::
This feature allows you to seamlessly integrate and manage your existing library of HTML templates within our platform. This version of the editor offers a classic WYSIWYG experience, designed specifically for users who have a collection of legacy HTML templates. By using the builder in classic mode, you can maintain consistency and continue using your old HTML content while still taking advantage of the powerful features our platform provides.
## Key Features
- **Classic WYSIWYG Editor**: A familiar and simple editing environment for users who prefer a basic HTML editor, without the need for advanced drag-and-drop functionality.
- **HTML Compatibility**: Easily import and edit legacy HTML templates, ensuring backward compatibility with your existing content.
- **Unified Experience**: Use the same platform for both new and legacy templates, allowing for a streamlined workflow and consistent template management.
---
In classic mode, there is no JSON and templates are loaded and exported using HTML only.
## Load Design
You can load the legacy design like this.
```javascript
unlayer.loadDesign({
html: 'This is a legacy HTML template.',
classic: true,
});
```
---
## Export Design
The export function will return HTML.
```javascript
unlayer.exportHtml(function (data) {
var html = data.html; // final html
// Do something with the html
});
```
---
## Update Event
```javascript
unlayer.addEventListener('design:updated', function (data) {
var type = data.type; // html:updated
console.log('design:updated', type);
});
```
---
## Full Example
We have a full example of legacy template. [Check it out](https://examples.unlayer.com/web/legacy-template)
---
## Multi-Language Templates
Multi-Language lets a single template hold content in multiple languages. Users switch languages in the editor and translate text, images, and other elements without duplicating the template.
:::info Editor Localization
Multi-Language controls the languages of your **template content**. To translate the editor interface itself (panels, buttons, tool names), see [Localization](../advanced-configuration/localization.md).
:::
## Plan limits
Each plan includes a number of languages per editor instance, meaning the list you configure with `features.multiLanguage.languages` or `setLanguages`. The default language counts toward the limit:
| Plan | Languages per editor |
| :--------- | :------------------- |
| Free | Not available |
| Launch | Not available |
| Scale | 2 |
| Optimize | 5 |
| Enterprise | Unlimited |
The limit is enforced by Unlayer's servers from your project's plan, so the value you pass to `unlayer.init` cannot raise it. When you configure more languages than the plan includes:
- The default language is always kept, then the remaining slots go to the other languages in the order you configured them.
- Languages beyond the limit stay visible in the language selector but are greyed out, with a tooltip naming the limit. They cannot be selected in the editor, through `setCurrentLanguage`, or as the `language` of a client-side export.
- Content already stored for those languages is **preserved** in the design JSON — nothing is deleted — so it becomes editable again if the plan is upgraded.
- The editor's export methods (`exportHtml`, `exportImage`, `exportPdf`, `exportZip`) fall back to the current language when asked for one beyond the limit, and log a console warning. A direct Cloud API export of such a language is rejected with a `403` error that names the limit.
## Enable
Disabled by default. Enable it with `features.multiLanguage` — pass `true`, or an object with `enabled: true` plus the available languages (the object form does **not** enable the feature on its own):
```javascript
unlayer.init({
features: {
multiLanguage: {
enabled: true,
languages: [
{ label: 'English', value: 'en_US', default: true },
{ label: 'Spanish', value: 'es_ES' },
{ label: 'Arabic', value: 'ar_AE', rtl: true },
],
},
},
});
```
Each language object supports:
| Property | Type | Required | Description |
| :-------- | :-------- | :------- | :--------------------------------------------------------------------------------- |
| `value` | `string` | Yes | Unique identifier for the language, e.g. `en_US`, `pt_BR` |
| `label` | `string` | No | Display name shown in the language selector. Can be omitted if using translations. |
| `default` | `boolean` | No | Marks the default language. Set it on exactly one language. |
| `rtl` | `boolean` | No | Applies `direction: rtl` to content when this language is selected. |
:::warning Set a default
If no language has `default: true`, the first language in the array is only the _initially selected_ one — no language becomes the default. Edits in every language are then stored as per-language overrides, so untranslated content falls back to each tool's built-in default value instead of the first language's content.
:::
## Switching languages
When enabled, a language selector appears in three places: the editor toolbar, the Body settings tab, and the preview modal header. Switching re-renders the canvas with that language's content:
You can also drive it programmatically after init:
```javascript
// Replace the available languages
unlayer.setLanguages([
{ label: 'English', value: 'en_US', default: true },
{ label: 'Portuguese', value: 'pt_BR' },
]);
// Switch the active language
unlayer.setCurrentLanguage('pt_BR');
```
## Translating language labels
To make the language dropdown follow the user's locale, define keys via the [translations](../advanced-configuration/localization.md) API instead of hardcoding `label`. For each language the editor checks, in order:
1. `languages.{value}` — the `value` lowercased (`languages.en_us` for `en_US`)
2. The `label` as an exact key, or `labels.{label}` in snake_case (`labels.english_us` for `English (US)`) — both skipped when the language has no `label`
3. Falls back to `label` if set, then to `value`
```javascript
unlayer.init({
features: {
multiLanguage: true,
},
translations: {
en: { 'languages.en_us': 'English', 'languages.pt_br': 'Portuguese' },
'pt-BR': { 'languages.en_us': 'Inglês', 'languages.pt_br': 'Português' },
},
});
unlayer.setLanguages([{ value: 'en_US' }, { value: 'pt_BR' }]);
```
:::info Lowercase keys
Translation keys are always lowercase, even when the language `value` contains uppercase characters: for `en_US`, the key is `languages.en_us`.
:::
## Data structure
Content edited in the default language is stored at the root of the element's values. Other languages store only their overrides in a `_languages` object; anything not translated falls back to the default language:
```json
{
"text": "Hello World",
"_languages": {
"es_ES": { "text": "Hola Mundo" },
"fr_FR": { "text": "Bonjour le Monde" }
}
}
```
Multi-Language composes with [device overrides](../customization/editor-behavior/responsive-controls.md): the root `_languages` translates the base (desktop) values, and each device override carries its own `_languages` inside `_override` — so e.g. a background image can vary by device **and** language:
```json
{
"backgroundImage": { "url": "https://example.com/pt_desktop.jpg" },
"_languages": {
"en_US": {
"backgroundImage": { "url": "https://example.com/en_desktop.jpg" }
}
},
"_override": {
"mobile": {
"backgroundImage": { "url": "https://example.com/pt_mobile.jpg" },
"_languages": {
"en_US": {
"backgroundImage": { "url": "https://example.com/en_mobile.jpg" }
}
}
}
}
}
```
## Supported content types
| Content Type | Translatable Properties |
| :------------- | :------------------------------------------------------ |
| Text | Text content, font family |
| Paragraph | Text content, font family |
| Heading | Heading text |
| Button | Button text |
| Image | Source image, alt text |
| Menu | Menu items (text and links) |
| Table | Cell content; header, content, and footer font families |
| Form | Field, label, and button font families |
| Timer | Countdown settings (labels, locale, fonts), alt text |
| Row Background | Background images (for localized visuals) |
Font families being per-language lets you pick a script-appropriate font for each language (e.g. Arabic, Hebrew, or CJK content).
## Exporting in a specific language
Pass `language` to any export method — `exportHtml`, `exportPlainText`, `exportImage`, `exportPdf`, `exportZip` (see [Export HTML](../get-started/export/export-html.md) for all options). Element dimensions (e.g. button width) are recalculated for the specified language's content:
```javascript
unlayer.exportHtml(
function (data) {
var html = data.html;
},
{ language: 'es_ES' },
);
```
If omitted, the export uses the language currently selected in the editor (initially the default language).
Server-side exports also accept `languages` — the list of language codes configured for the template. The editor sends it automatically. If you call the Cloud API directly with a `language` and no `languages` list, the languages the template JSON carries content in (every `_languages` code — the editor stores default-language content edited with multi-language enabled there too) plus the requested one must fit within your plan's limit, otherwise the request is rejected with a `403` asking you to send `languages`. Send `languages` whenever you build the JSON yourself: it is the only way to tell the API which languages, default included, the export should count. Only the first _N_ entries of `languages` (where _N_ is your plan limit) can be rendered.
---
## Templates

Templates are pre-designed layouts that serve as starting points for creating content such as emails, landing pages, or popups. They provide a structure and design framework, allowing users to quickly customize and build their content without starting from scratch.
### Key Features
- **Reusable**: Templates can be saved and reused, saving time and ensuring design consistency.
- **Customizable**: Users can modify every aspect of a template, from text and images to layouts and styles, to fit their specific goals.
- **Efficient**: Templates reduce the time required to create new content by offering a ready-made structure that users can quickly adapt.
There are two ways you to manage templates in Unlayer. You can either use Unlayer's template manager, or you can save the templates in your own database.
---
## Template Management
Our platform provides two flexible options for managing templates. You can either design and store templates on our servers using the template manager, or manage them locally in your own database.
## Unlayer Template Manager (Easy)
Unlayer provides a template manager where your team members can easily collaborate, create and modify templates. This is available in Library > Templates section of the [developer console](https://console.unlayer.com). Each template is given a unique ID which can be used during initialization or any time after that.
Here's an example on how you can do it **during initialization** by passing a `templateId`.
```javascript JavaScript
unlayer.init({
projectId: 1,
templateId: 123,
});
```
Or, you can do it **after initialization** by calling the following function.
```javascript JavaScript
unlayer.loadTemplate(1); // 1 is the templateId
```
You can also use our [Cloud API](/server/cloud-api/reference) to fetch the templates from your server at any time.
---
## On Your Own Servers (Advanced)
If you want to save the templates on your own servers, that can be easily done. Templates are exactly like regular designs created using our editor. So they can be [saved and loaded](../get-started/load-and-save-designs.md) using the same API.
Once you create the template in Unlayer's template manager, switch to the JSON tab to get its' JSON. You can save this JSON in your database.
After the editor is initialized, you have to pass the template JSON to the `loadDesign` method.
```javascript
var template = {...}; // template JSON
unlayer.loadDesign(template);
```
---
## Which Option to Choose?
- **Unlayer Template Manager** if you prefer to offload the complexity of template storage and focus solely on loading templates. This is ideal for those who want quick integration without managing backend infrastructure.
- **On Your Own Servers** if you need more control over template storage, want to integrate templates with other internal systems, or prefer to maintain full ownership of template data.
---
## Template Permissions
The builder includes an **_Editor Mode_** for developers and administrators who create templates for end-users. This mode allows you to lock or restrict certain parts of a template so that end-users cannot modify them, ensuring critical design elements remain intact while allowing flexibility in other areas.
## Enable Editor Mode
To enable this mode, initialize the builder with the designMode set to 'edit'. This activates additional controls within the builder, specifically in a new "Admin" section at the bottom of the editor panel, which provides granular control over content elements.
```javascript
unlayer.init({
designMode: 'edit', // default value is 'live'
});
```
---
Admin Section Controls
When editor mode is enabled, the "Admin" section in the editor panel provides the following options to control how rows and content blocks behave for end-users:
Selectable: Allows you to control whether the end-user can select the content block for editing.
Draggable: Determines if the end-user can drag the content to reposition it.
Duplicatable: Controls whether the end-user can duplicate the content block.
Deletable: Determines if the end-user can delete the content block.
Hideable: Lets you control whether the end-user can hide the content on specific devices (e.g., mobile or desktop).
Locked: Determines if the end-user can change anything in block. When applied to a Row or Column, this also affects their content.
These controls allow developers or administrators to lock specific parts of the template, ensuring that the end-user cannot accidentally modify or delete essential elements of the design.
---
## Use Case Example
Imagine a scenario where a company has a standard email template with a header, body, and footer. To maintain brand consistency, the header and footer should remain locked and uneditable for end-users, while the body section can be customized with different content.
By creating the template in editor mode, the administrators can:
- Lock the header and footer by disabling **Selectable**, **Deletable**, and **Draggable** options.
- Allow the end-user to only edit the body content, ensuring the core design elements remain intact.
- If you also want to prevent content editing, you can mark either the content or their parent container as **Locked**.
### Locked Row Example
If you mark a Row as **Locked**, here is how it will look like in the editor on `live` mode:
---
## Notes
- The admin section is only available in editor mode (`designMode: 'edit'`)). When the builder is running in `live` mode, end-users will not see these options.
- This feature is ideal for ensuring that essential design elements remain unchanged while still giving end-users the flexibility to customize other areas of the template.
- These settings provide granular control, allowing administrators to create templates with different levels of flexibility for end-users.
---
## Angular Component
## Installation
```bash
npm install angular-email-editor
```
## Module setup
Add `EmailEditorModule` to your application's imports:
```typescript title="app.module.ts"
@NgModule({
imports: [
// ...other imports
EmailEditorModule,
],
})
export class AppModule {}
```
## Basic usage
```typescript title="app.component.ts"
@Component({
selector: 'app-root',
template: `
Export HTML
Save Design
`,
})
export class AppComponent {
@ViewChild('emailEditor') emailEditor!: EmailEditorComponent;
options = {
projectId: 1234, // replace with your Unlayer Project ID
displayMode: 'email',
features: {
ai: true,
},
};
onReady() {
// Editor is ready. Optionally load a saved design here:
// this.emailEditor.editor.loadDesign(savedDesign);
}
exportHtml() {
this.emailEditor.editor.exportHtml((data: any) => {
const { design, html } = data;
console.log('HTML output:', html);
});
}
saveDesign() {
this.emailEditor.editor.saveDesign((design: any) => {
console.log('Design JSON:', design);
});
}
}
```
If you prefer separate template/HTML files, the same component split looks like:
```html title="app.component.html"
Export
```
## Loading a saved design
```typescript
onReady() {
const savedDesign = /* fetch from your backend */;
this.emailEditor.editor.loadDesign(savedDesign);
}
```
## Methods
Available on `this.emailEditor.editor`:
| Method | Params | Description |
| :------------- | :---------------- | :----------------------------------------------------- |
| **loadDesign** | Object data | Loads a saved design JSON into the editor |
| **saveDesign** | Function callback | Returns the current design JSON via callback |
| **exportHtml** | Function callback | Returns the rendered HTML and design JSON via callback |
## Props
| Name | Type | Description | Default |
| :------------- | :------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------ |
| **minHeight** | String | Minimum height to initialize the editor with | `500px` |
| **options** | Object | Options passed to the Unlayer editor instance. See the [configuration options](../get-started/installation.md#configuration-options) for everything available. | `{}` |
| **tools** | Object | Configuration for built-in and custom tools | `{}` |
| **appearance** | Object | Configuration for appearance and theme | `{}` |
| **projectId** | Integer | Unlayer Project ID (alternative to passing via `options`) | |
| **ready** | Output | Emits when the editor has finished loading | |
| **loaded** | Output | Emits when the editor instance is created | |
## Example
A full working reference implementation lives in the [`angular-email-editor` demo](https://github.com/unlayer/angular-email-editor/tree/master/src).
---
## React Component
## Installation
```bash
npm install react-email-editor
```
## Basic usage
```jsx title="src/EmailComponent.jsx"
export default function EmailComponent() {
const emailEditorRef = useRef(null);
const onReady = (unlayer) => {
// Editor is ready. Optionally load a saved design here:
// unlayer.loadDesign(savedDesign);
};
const exportHtml = () => {
emailEditorRef.current?.editor.exportHtml((data) => {
const { design, html } = data;
console.log('HTML output:', html);
});
};
const saveDesign = () => {
emailEditorRef.current?.editor.saveDesign((design) => {
console.log('Design JSON:', design);
});
};
return (
Export HTML
Save Design
);
}
```
Render it from your app:
```jsx title="src/App.jsx"
export default function App() {
return ;
}
```
`onReady` fires once the editor has fully loaded. Inside it, you can call any of the [methods](#methods) below — most commonly `loadDesign` to populate the editor with a saved template.
## TypeScript
`react-email-editor` ships its own types. Pass the editor ref the right shape with `EditorRef`, and type the `onReady` handler with `EmailEditorProps['onReady']`:
```tsx title="src/EmailComponent.tsx"
export default function EmailComponent() {
const emailEditorRef = useRef(null);
const onReady: EmailEditorProps['onReady'] = (unlayer) => {
// unlayer is fully typed here
};
return ;
}
```
## Configuration
Pass editor configuration through the `options` prop. The shape matches the [full `unlayer.init` configuration](../get-started/installation.md#configuration-options):
```jsx
```
## Loading a saved design
```jsx
const onReady = (unlayer) => {
const savedDesign = /* fetch from your backend */;
unlayer.loadDesign(savedDesign);
};
```
## Methods
Available on `emailEditorRef.current.editor`:
| Method | Params | Description |
| :------------- | :---------------- | :----------------------------------------------------- |
| **loadDesign** | Object data | Loads a saved design JSON into the editor |
| **saveDesign** | Function callback | Returns the current design JSON via callback |
| **exportHtml** | Function callback | Returns the rendered HTML and design JSON via callback |
## Props
| Name | Type | Description | Default |
| :--------- | :------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------ |
| style | Object | Style for the editor container | `{}` |
| minHeight | String | Minimum height to initialize the editor with | `500px` |
| onLoad | Function | Called when the editor instance is created | |
| onReady | Function | Called when the editor has finished loading | |
| options | Object | Options passed to the Unlayer editor instance. See the [configuration options](../get-started/installation.md#configuration-options) for everything available. | `{}` |
| tools | Object | Configuration for built-in and custom tools | `{}` |
| appearance | Object | Configuration for appearance and theme | `{}` |
## Example
A full working reference implementation lives in the [`react-email-editor` demo](https://github.com/unlayer/react-email-editor/blob/master/demo/src/example/index.tsx).
---
## React Image Editor
The official `@unlayer/react-image-editor` component loads the standalone Image Editor, mounts it into your React application, and cleans it up when the component unmounts. It requires React 18 or later and Node.js 18 or later.
The component and manual editing tools are free. The optional [AI Assistant](../builders/image-editor/ai-assistant.md) is a paid feature.
## Installation
```bash
npm install @unlayer/react-image-editor
```
## Basic Usage
```tsx title="src/ImageEditorComponent.tsx"
type ImageEditorRef,
type ImageEditorSaveResult,
} from '@unlayer/react-image-editor';
export default function ImageEditorComponent() {
const imageEditorRef = useRef(null);
const saveImage = async ({ blob }: ImageEditorSaveResult) => {
const formData = new FormData();
formData.append('file', blob, 'edited.png');
await fetch('/api/images', {
method: 'POST',
body: formData,
});
};
return (
{
// Close your image editor view
}}
onLoadError={() => {
// The image could not be loaded because of CORS, a 404, or a decode error
}}
onError={(error) => {
// The embed script or editor instance could not be loaded
console.error('Image Editor failed:', error);
}}
/>
);
}
```
The `image` prop accepts an image URL or base64 data URL. The save result contains both a `dataUrl` for previews or inline use and a `blob` that is ready to upload.
## Configuration
Pass standalone Image Editor configuration through `options`:
```tsx
```
:::note Newer Image Editor options
Newer editor builds also support `features.imageEditor.dock` and `features.imageEditor.tools.corners`. These fields type-check once your installed `@unlayer/types` version includes them.
:::
See [Configuration](../builders/image-editor/configuration.md) for tools, icons, theme, and localization, and [AI Assistant](../builders/image-editor/ai-assistant.md) for AI setup.
## Props
| Name | Type | Description | Default |
| :------------ | :----------------------- | :---------------------------------------------------------------------------------------------------------- | :------ |
| `image` | `string` | Image URL or base64 data URL to edit. **Required.** | |
| `options` | `ImageEditorOptions` | Standalone editor options such as `projectId`, `features`, `theme`, `locale`, and `translations`. | `{}` |
| `editorId` | `string` | ID applied to the container element. The editor mounts by element reference, so this is primarily cosmetic. | |
| `minHeight` | `number \| string` | Minimum height of the outer editor container. | `500` |
| `style` | `React.CSSProperties` | Inline styles applied to the inner editor container. | `{}` |
| `scriptUrl` | `string` | Advanced override for the image-editor embed script URL. Use one script URL across all instances on a page. | CDN URL |
| `onLoad` | `(editor) => void` | Called with the editor instance after it mounts. | |
| `onSave` | `(result) => void` | Called with `{ dataUrl, blob }` when the user saves. | |
| `onCancel` | `() => void` | Called when the user cancels editing. | |
| `onLoadError` | `() => void` | Called when the image fails to load into the canvas. | |
| `onError` | `(error: Error) => void` | Called when the script, editor creation, or an image reset fails. | |
`onLoadError` and `onError` cover different failures: use `onLoadError` for an image that cannot be decoded or fetched, and `onError` for wrapper-level loading or lifecycle failures.
## Editor Instance
The forwarded ref exposes `{ editor }`. It is `null` until the editor mounts:
```tsx
const dataUrl = imageEditorRef.current?.editor?.getImage();
const hasUnsavedChanges = imageEditorRef.current?.editor?.hasChanges() ?? false;
await imageEditorRef.current?.editor?.reset(nextImageUrl);
imageEditorRef.current?.editor?.updateOptions({ theme: 'dark' });
```
| Method | Description |
| :----------------------- | :------------------------------------------------------------------------------- |
| `getImage()` | Returns the flattened canvas as a data URL, or `null`. |
| `hasChanges()` | Returns whether the editor has unsaved edits. |
| `reset(imageUrl?)` | Clears history and AI chat, and optionally loads another image. |
| `updateOptions(options)` | Updates editor options at runtime. |
| `destroy()` | Unmounts the editor. React calls this automatically when the component unmounts. |
## Updating Props
The wrapper applies prop changes according to their impact:
| Change | Behavior |
| :------------------------------------------- | :------------------------------------------------------------------------------------------- |
| `image` | Calls `reset(newImage)` and clears undo/redo history and AI chat. |
| `options.theme`, `locale`, or `translations` | Calls `updateOptions()` without remounting, preserving editor state. |
| Any other `options` value | Destroys and recreates the editor, discarding unsaved changes. |
| `scriptUrl` | Remounts the editor; do not mix URLs because the page's first installed embed wins globally. |
| Callback props | Uses the latest callback without remounting. |
Rapid `image` changes are serialized and collapse to the latest value, so an earlier image load cannot overwrite a newer one.
## Next.js and React Server Components
The package ships as a client component and only accesses the DOM from effects, so it can be imported directly in Next.js App Router and other React Server Components environments.
For a complete runnable example, see the [`react-image-editor` demo](https://github.com/unlayer/react-image-editor/tree/main/demo).
---
## Vue Component
## Installation
```bash
npm install vue-email-editor
```
## Basic usage (Vue 3 Composition API)
```html title="App.vue"
Export HTML
Save Design
```
## Vue 2 / Options API
```html title="App.vue"
Save Design
Export HTML
```
## Nuxt.js
Wrap the editor in `` so it renders only on the client:
```html title="pages/editor.vue"
```
## Configuration
Pass editor configuration through the `options` prop, or via dedicated props for the most common knobs. The `options` shape matches the [full `unlayer.init` configuration](../get-started/installation.md#configuration-options):
```html
```
## Loading a saved design
```javascript
const onReady = () => {
const savedDesign = /* fetch from your backend */;
emailEditor.value.editor.loadDesign(savedDesign);
};
```
## Methods
Available on `this.$refs.emailEditor.editor` (Options API) or `emailEditor.value.editor` (Composition API):
| Method | Params | Description |
| :------------- | :---------------- | :----------------------------------------------------- |
| **loadDesign** | Object data | Loads a saved design JSON into the editor |
| **saveDesign** | Function callback | Returns the current design JSON via callback |
| **exportHtml** | Function callback | Returns the rendered HTML and design JSON via callback |
## Props
| Name | Type | Description | Default |
| :------------- | :------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------ |
| **minHeight** | String | Minimum height to initialize the editor with | `500px` |
| **options** | Object | Options passed to the Unlayer editor instance. See the [configuration options](../get-started/installation.md#configuration-options) for everything available. | `{}` |
| **tools** | Object | Configuration for built-in and custom tools | `{}` |
| **appearance** | Object | Configuration for appearance and theme | `{}` |
| **locale** | String | Translations locale | `en-US` |
| **projectId** | Integer | Unlayer Project ID (alternative to passing via `options`) | |
## Example
A full working reference implementation lives in the [`vue-email-editor` demo](https://github.com/unlayer/vue-email-editor/tree/master/src).
---
## Custom Blocks
## What is a Custom Block?
Custom blocks allow host applications to define and provide reusable design components for their end-users. These blocks can be pre-designed by your team and then made available for users to drag and drop into their designs, ensuring consistent branding and efficient content creation. Custom blocks can include a variety of elements such as text, images, buttons, and more.

---
## How Custom Blocks Work
Custom blocks are flexible components that can be reused across multiple designs or templates. These blocks can be built with any available [tools](../tools/built-in-tools/overview.md). These blocks are stored and displayed under the **Blocks** tab in the builder, ready to be dragged into new designs.
Each custom block is created with the following information to make it easier to navigate and search the blocks tab.
### Block Category
All blocks are organized under a _category_. This helps users find different blocks easily. For example: **Headers**, **Footers**, **Features**, etc.
### Block Tags
Each block can have comma-separated tags which are searchable and make it easier for users to filter and find different blocks.
---
## Enable or Disable
By default, custom blocks are enabled in the builder. However, developers can control whether custom blocks are available using the following.
```javascript
unlayer.init({
features: {
blocks: false, // Disables custom blocks
},
});
```
This example disables the availability of custom blocks in the editor. However, this does **not** hide the Blocks tab. You can do that using [Tab Management](../advanced-configuration/tab-management.md).
---
## Creating a Custom Block
There are 2 ways to create and load custom blocks.
### **Console**
This is the quickest way to create tons of custom blocks. They are stored on our servers, and automatically loaded when you initialize the editor with the correct `projectId`.
1. Open Unlayer [Console](https://console.unlayer.com).
2. Go to your Project. If you don't have one, create a new one.
3. Go to the Blocks menu under Library.
4. Click New Block
5. Fill the form and click Create Block
---
### **JavaScript API**
If you want to save and load blocks from your own servers, you can load them up using the following API. Here's a code sample.
#### Load Blocks
```javascript
// Load the blocks from your database
let blocks = [
{
/* Block JSON Object */
},
{
/* Block JSON Object */
},
{
/* Block JSON Object */
},
];
unlayer.registerProvider('blocks', function (params, done) {
console.log('blocks provider', params);
done(blocks);
});
```
#### Reload Provider
If you added or removed blocks, you can reload the provider so it reflects in the editor.
```javascript
unlayer.reloadProvider('blocks');
```
#### Events
You can catch events when a block is added, modified or removed by the end-user.
```javascript
unlayer.registerCallback('block:added', function (newBlock, done) {
console.log('block:added', newBlock);
// Save the block to your database here
// and pass the object to done callback.
// Each block should have it's own unique id
done(block);
});
unlayer.registerCallback('block:modified', function (existingBlock, done) {
console.log('block:modified', existingBlock);
// Update the block in your database here
// and pass the updated object to done callback.
done(block);
});
unlayer.registerCallback('block:removed', function (existingBlock, done) {
console.log('block:removed', existingBlock);
// Delete the block from your database here.
done(block);
});
```
---
## Plan Limits
The number of custom blocks you can use is governed by your plan's Custom Blocks
limit. This limit is enforced across **every** way blocks can be loaded:
- Blocks stored in the [Console](https://console.unlayer.com).
- Blocks passed to `unlayer.init({ blocks: [...] })`.
- Blocks returned by a custom blocks provider registered with
`unlayer.registerProvider('blocks', …)`.
- Blocks created through the REST API (`POST /v2/editor/blocks`), which rejects
requests over the limit with a `Blocks limit exceeded` error.
When more blocks are loaded than your plan allows, only the first _N_ (up to your
plan limit) are made available in the editor; the rest are dropped and a warning
is logged to the browser console. Blocks within your plan limit are unaffected.
To raise this limit, upgrade your plan.
---
## Best Practices
- **Efficiency**: Pre-define commonly used sections, such as headers, footers, or call-to-action sections, so end-users can easily reuse them without having to recreate them from scratch.
- **Preview**: Always test and preview custom blocks to ensure they are responsive and display well on different devices and screen sizes.
- **Categorization**: Organize custom blocks into clear categories like “Headers,” “Footers,” “Content,” etc., to make them easy to find for users.
---
## Synced Blocks
## What are Synced Blocks?
Synced Blocks allow users to create and maintain reusable content blocks that stay synchronized across multiple designs. When a Synced Block is updated, those changes become available to all instances of that block. The updates are applied when designs containing those blocks are loaded, but only if the instance hasn't been locally modified (is not "dirty"). This feature is perfect for maintaining consistency across designs where certain elements need to remain identical.
---
## How Synced Blocks Work
When a user creates a Synced Block, the system assigns it a unique sync ID and stores metadata about its synchronization status. The block can then be used across multiple designs, all connected to the original version.
### Sync States and Behavior
Synced Blocks can exist in different states:
1. **Clean State** - Block is synced and unchanged locally
2. **Dirty State** - Block has local modifications that haven't been saved to the synced version
3. **Outdated State** - A newer version of the synced block is available
When changes are made to any instance of the block, users can:
1. **Update the Synced Block** - Save local changes to make them available to all instances when they are loaded
2. **Restore the original** - Discard local changes and restore the block to its last synced version
3. **Convert to Standard Block** - Turn the block into a regular block, breaking the sync connection
### Intelligent Sync Logic
The system uses sophisticated logic to determine when to apply updates:
- **Dirty State Protection** - Local changes are never overwritten automatically. Blocks marked as "dirty" remain unchanged until manually updated or restored.
- **Timestamp Comparison** - Updates are only applied if the synced block is newer than the local version.
- **Auto-save Behavior** - Regular blocks auto-save on changes, but synced blocks require manual confirmation to prevent unintended updates to linked designs.
### Sync Metadata Structure
Synced Blocks maintain their status through several properties:
- **Sync ID** - Unique identifier connecting all instances of the same block
- **Sync Enabled** - Whether the block is currently part of the synchronization system
- **Updated At** - Timestamp indicating when the block was last updated
- **Dirty** - Boolean flag indicating if the block has unsaved local changes
---
## Enable or Disable Feature
Synced Blocks are an advanced feature that requires both feature enablement and a plan that includes the Synced Blocks feature. The feature must be enabled in two places:
### Feature Configuration
Developers can control whether Synced Blocks are available in the editor using the following configuration:
```javascript
unlayer.init({
features: {
syncedBlocks: true, // Enables synced blocks feature
},
});
```
### Plan requirement
Your project's plan must also include the Synced Blocks feature. Both the feature flag and the plan feature must be enabled for synced blocks functionality to be available.
The editor automatically checks both conditions and only shows synced blocks options when both are satisfied.
## Using Synced Blocks
### Creating a Synced Block
Users can create a Synced Block through the Unlayer Console by enabling sync functionality when creating a new block.
To create Synced Blocks in your project:
1. Log in to **[Unlayer Console](https://console.unlayer.com)**
2. Navigate to your project
3. Go to Library > Blocks section
4. Click "New Block"
5. Fill in the block details and enable the sync option
6. The block will be created with sync capabilities enabled
#### JavaScript API
If you want to save and load synced blocks from your own servers, you can use the following API.
When you load a design containing synced blocks, the editor automatically calls your blocks provider with the `syncIds` found in the design.
##### Load Synced Blocks
```javascript
unlayer.registerProvider('blocks', function (params, done) {
console.log('blocks provider called with:', params);
// For regular block loading:
// params = { userId: 123, displayMode: 'email', category: '', search: '' }
// For synced block loading (when design contains sync blocks):
// params = { userId: 123, displayMode: 'email', syncIds: ['sync-id-1', 'sync-id-2'] }
if (params.syncIds) {
// Called when loading a design with synced blocks
// Return only blocks that match the requested syncIds
const syncBlocks = blocks.filter((block) =>
params.syncIds.includes(block.syncMetadata?.id),
);
done(syncBlocks);
} else {
// Called for regular block browsing in the editor
done(blocks);
}
});
```
**Example synced block data structure:**
```javascript
const blocks = [
{
id: 'block-123',
name: 'Header Block',
data: {
/* Your block design data */
},
// Required for synced blocks
syncMetadata: {
id: 'sync-456', // Unique sync identifier
enabled: true, // Must be true for synced blocks
updatedAt: '2024-01-15T10:30:00Z', // Last update timestamp
},
},
];
```
##### Events
```javascript
unlayer.registerCallback('block:modified', function (existingBlock, done) {
console.log('block:modified', existingBlock);
// Update the synced block in your database here
if (existingBlock.syncMetadata?.enabled) {
// Handle synced block update
updateSyncBlockInDatabase(existingBlock)
.then((savedBlock) => {
// IMPORTANT: Update timestamp for proper sync
savedBlock.syncMetadata.updatedAt = new Date().toISOString();
done(savedBlock);
})
.catch((error) => {
console.error('Failed to save sync block:', error);
done(existingBlock); // Fallback to original data
});
} else {
done(existingBlock);
}
});
```
##### Error Handling
```javascript
// Handle provider errors gracefully
unlayer.registerProvider('blocks', function (params, done) {
try {
if (params.syncIds) {
fetchSyncBlocks(params.syncIds)
.then((blocks) => done(blocks))
.catch((error) => {
console.error('Failed to load sync blocks:', error);
done([]); // Return empty array as fallback
});
} else {
fetchAllBlocks()
.then((blocks) => done(blocks))
.catch((error) => {
console.error('Failed to load blocks:', error);
done([]); // Graceful degradation
});
}
} catch (error) {
console.error('Provider error:', error);
done([]); // Always call done() to prevent hanging
}
});
```
### Managing Synced Blocks in the Editor
When a Synced Block is selected in the editor, users will see a special "Synced Block" panel in the property editor with sync management options:
#### Clean State (Unmodified)
When the block hasn't been modified locally:
- Shows sync status information
- Displays last sync timestamp
- Offers option to convert to a standard block (removing sync)
#### Dirty State (Modified)
When the block has local changes that haven't been saved:
- Shows warning about unsaved changes
- Offers three options:
- **Update Block** - Save changes to the synced block (affects all instances)
- **Restore Original** - Discard local changes and restore from synced version
- **Convert to Standard Block** - Remove sync and keep local changes
### Visual Indicators
Synced Blocks are clearly identified throughout the interface:
#### In the Editor
1. **Sync Block Indicator**: Purple badge showing "Synced Block" with sync timestamp
2. **Dirty State Warning**: Visual indicator when block has unsaved changes
3. **Property Panel**: Special "Synced Block" section in the properties panel
#### In Block Libraries
1. **Sync Icon**: Special link icon next to synced blocks in block lists
2. **Sync Metadata**: Shows sync status and last update information
#### For Content Within Synced Blocks
When editing content inside a synced block (but not the block itself), a placeholder message appears directing users to select the entire row to manage sync settings.
## Best Practices
### When to Use Synced Blocks
- **Branding Elements**: Logo blocks, company signatures, or branded sections
- **Legal Content**: Disclaimers, unsubscribe sections, or compliance text
- **Contact Information**: Address blocks, social media links, or contact details
### When NOT to Use Synced Blocks
- **Dynamic Content**: Blocks that frequently change or need customization per design
- **Campaign-Specific Content**: Content that varies between different campaigns or audiences
- **One-off Designs**: Content that won't be reused across multiple designs
### Design Workflow Tips
1. **Plan Ahead**: Identify reusable content before creating blocks
2. **Test First**: Create and test blocks as regular blocks before converting to synced
3. **Communicate Changes**: When updating synced blocks, ensure team members are aware of the impact
4. **Version Control**: Consider creating new synced blocks for major changes rather than updating existing ones
5. **Regular Audits**: Periodically review synced blocks to ensure they're still relevant and being used
### Performance Considerations
- Synced blocks are loaded on-demand when designs are opened
- The system includes intelligent caching to minimize API calls
- Updates only occur when both the feature flag and the plan feature are enabled
- Dirty state tracking prevents unnecessary overwrites and preserves user intent
### Troubleshooting
#### Synced Block Options Not Visible
- Verify the `syncedBlocks` feature is enabled in your configuration
- Ensure your plan includes the Synced Blocks feature
- Check that you're selecting the row-level element, not content within it
#### Changes Not Syncing
- Confirm the block has a valid sync ID and is enabled
- Check if the block is in a "dirty" state (has unsaved local changes)
- Verify timestamp comparison - newer versions may not override older ones
#### Auto-save Not Working
- This is expected behavior for synced blocks
- Synced blocks require manual save confirmation to prevent unintended updates
- Use the "Update Block" button to save changes to all instances
#### Common Development Issues
**Provider never receives syncIds:**
```javascript
// Check the feature flag
unlayer.init({
projectId: 'your-project',
features: {
syncedBlocks: true, // Must be enabled
},
});
```
Also confirm your project's plan includes the Synced Blocks feature — both must be in place for synced blocks to work.
**Sync blocks not updating across designs:**
- Ensure `block:modified` callback updates `syncMetadata.updatedAt`
- Check that timestamp format is ISO string: `new Date().toISOString()`
- Verify the updated block is returned with correct `syncMetadata.id`
**Editor hangs or freezes:**
- Always call `done()` in your provider, even on errors
- Implement timeouts for async operations
- Use `done([])` as fallback for errors
**Memory leaks with many sync blocks:**
- Implement proper caching with expiration
- Clear old cache entries periodically
- Avoid storing large objects in global scope
**Debug logging:**
```javascript
// Enable comprehensive logging
unlayer.registerProvider('blocks', function (params, done) {
console.log('Provider called:', {
timestamp: new Date().toISOString(),
params,
hasSyncIds: !!params.syncIds,
syncIdCount: params.syncIds?.length || 0,
});
// Your provider logic...
done(blocks);
});
```
---
## User Saved Blocks
This feature allows end-users to save any block of content they’ve created so it can be reused in their designs. This is particularly useful for maintaining design consistency and speeding up content creation. These blocks are saved within the builder’s environment and can be inserted into any design with just a few clicks. Developers can enable and configure this feature for end-users in their applications.
---
## Enable or Disable Feature
### Prerequisites
In order for this feature to work, you must have set up [End-User Identification](../advanced-configuration/end-user-identification.md) in the builder to correctly identify and associate a saved block with a user.
- [Setup End-User Identification](../advanced-configuration/end-user-identification.md)
### Enable Custom Blocks
User saved blocks is a sub-feature of [Custom Blocks](./custom-blocks.md). By default, custom blocks are enabled in the builder. The **save button** for blocks will automatically appear once the user is identified and this feature is enabled.
You can enable or disable this feature using the following example:
```javascript
unlayer.init({
features: {
blocks: true,
},
});
```
---
## How It Works
Users can save their blocks by clicking the save button at the bottom right of a selected block.

Once they click save, they will be asked a **Category Name** and optional **Tags**. This helps organize the blocks and make them searchable.

---
## File Manager
The **File Manager** feature in the builder allows end-users to upload and manage their own images in a uploads tab. It can also be configured to display images stored on your server.
---
## Enable / Disable Feature
### Prerequisites
Before using the File Manager, you need to set up [End-User Identification](../advanced-configuration/end-user-identification.md) in the builder to correctly identify and associate uploaded images with a specific end-user. This ensures that images uploaded or managed within the builder are tied to the correct user account.
- [Setup End-User Identification](../advanced-configuration/end-user-identification.md)
### Enable / Disable File Manager
If you do not wish to use the File Manager, you can easily disable it by setting the `userUploads` feature to false during the builder’s initialization.
```javascript
unlayer.init({
features: {
userUploads: {
enabled: true,
},
},
});
```
---
## Search Uploads
The File Manager also has the ability for end-users to search their uploaded files easily. This feature is enabled by default but you can choose to disable search if that's what you prefer.
```javascript
unlayer.init({
features: {
userUploads: {
enabled: true,
search: true,
},
},
});
```
---
## Custom Database
If your users’ images are already stored in your database, you can configure the File Manager to display those images by using the `unlayer.registerProvider` API.
Here is an example that shows how to load images from your server and display them in the file manager:
| Attribute | Description |
| :-------------- | :---------------------------------------------------- |
| **id** | A unique identifier for the image. |
| **location** | The URL where the image is stored. |
| **width** | Image width in pixels. |
| **height** | Image height in pixels. |
| **contentType** | MIME type of the image (e.g., image/png). |
| **source** | Set as `user` to indicate it’s a user-uploaded image. |
| **size** | Optional. File size of the image |
You can check out a [full example](https://examples.unlayer.com/media/user-uploads) using custom database to load user uploaded images.
```javascript
unlayer.registerProvider('userUploads', function (params, done) {
// Load images from your server here...
var images = [
{
id: Date.now() + i,
location: 'https://picsum.photos/id/1/500',
width: 500,
height: 500,
contentType: 'image/png',
source: 'user',
},
{
id: Date.now() + i,
location: 'https://picsum.photos/id/2/500',
width: 500,
height: 500,
contentType: 'image/png',
source: 'user',
},
];
done(images);
});
```
---
### Saving Uploads
If you want to save the reference to uploaded images from the builder to a custom database so you can send it to the File Manager, you will have to use the `image:uploaded` event. You can do it like this:
```javascript
unlayer.addEventListener('image:uploaded', function (data) {
var image = data.image;
var url = image.url;
var width = image.width;
var height = image.height;
// Save image info to your custom database here
});
```
---
### Pagination
The File Manager supports pagination to efficiently load and display large collections of images. To enable pagination, provide the necessary attributes when returning the images from your server.
| Attribute | Description |
| :---------- | :--------------------------------------------------------------------- |
| **page** | The current page number being requested. |
| **perPage** | The number of images to display per page. |
| **total** | The total number of images available. |
| **hasMore** | A boolean indicating whether more images are available for pagination. |
```javascript
unlayer.registerProvider('userUploads', function (params, done) {
var page = params.page || 1; // Current page number
var perPage = params.perPage || 20; // Number of images per page
var total = 100; // Total number of images available
var hasMore = total > page * perPage; // Check if there are more images to load
// Load images for the current page from your server here...
var images = [];
// Return the images along with pagination data
done(images, { hasMore, page, perPage, total });
});
```
---
### Searching
The File Manager supports searching to efficiently load and display large collections of images. To enable searching, provide the necessary attributes when returning the images from your server.
```javascript
unlayer.registerProvider('userUploads', function (params, done) {
var page = params.page || 1; // Current page number
var perPage = params.perPage || 20; // Number of images per page
var total = 100; // Total number of images available
var hasMore = total > page * perPage; // Check if there are more images to load
var searchText = params.searchText; // The search term
// Load images that match the search term, for the current page from your server here...
var images = [];
// Return the images along with pagination data
done(images, { hasMore, page, perPage, total });
});
```
---
### Handling Deletions
End-users can delete their uploaded images from the File Manager. To handle this, you can use the `unlayer.registerCallback` method to register a callback for the image deletion event. This allows your application to remove the image from your server and synchronize the changes with the builder.
```javascript
unlayer.registerCallback('image:removed', function (image, done) {
// image will include id, userId and projectId
console.log(image);
// call this when image has been deleted
done();
});
```
The image object contains:
- **id**: The unique identifier of the image.
- **userId**: The ID of the end-user who uploaded the image.
- **projectId**: The ID of your project
Once the image is deleted from your server, call the `done()` function to notify the builder that the image has been removed.
---
## Amazon S3
:::info Availability
Using your own S3 bucket requires a plan that includes the Amazon S3 Storage feature. See [pricing](https://unlayer.com/pricing).
If the plan doesn't include it, uploads, exports, and thumbnails are stored in Unlayer's storage, even when a bucket is configured. You can still view and remove existing buckets in the storage settings, but you can't add, edit, or test one.
:::
We have file storage support built-in with Amazon S3 that can be configured without any coding. Follow these steps to set up your S3 file storage.
## Choose an Access Mode
Uploaded files must be publicly retrievable so the editor (and your end users) can load them. There are two supported ways to achieve that — pick one before you continue:
1. **Public bucket** — the bucket itself serves public reads. This requires unchecking **Block all public access** and adding a public-read bucket policy (both covered below).
2. **Private bucket behind a CDN** — the bucket stays fully private (all public access blocked) and a CDN such as CloudFront, granted read access to the bucket, serves the files. Set the CDN as the **URL Prefix** in your Unlayer storage settings (see [Connect your CDN](#connect-your-cdn-optional)).
The public-access and bucket-policy steps below apply to the **public bucket** mode only. If you use a CDN, skip them and keep the bucket private.
Your choice also determines how to set the **Public bucket** option in your Unlayer storage settings (see [Add Credentials](#add-credentials-in-your-unlayer-project) below). When checked, every upload carries a `public-read` ACL — only check it for a public bucket with ACLs enabled (**Object Ownership** set to Object Writer). Leave it unchecked for a private bucket behind a CDN, and for any bucket with ACLs disabled — such buckets reject uploads that carry an ACL.
## Create S3 Bucket
If you already have a S3 bucket, skip this step.
The first step is to create a bucket in your AWS S3 console. If you chose the **public bucket** mode, uncheck "**Block all public access**" when creating the bucket; in the CDN mode, leave public access blocked.
Prefer a bucket name **without dots** (`.`). A dotted bucket name cannot be served over HTTPS as a subdomain (it fails certificate validation), so Unlayer falls back to path-style S3 URLs for such buckets — a URL form AWS supports but has said it intends to retire for new buckets. Serving through a CDN avoids the issue entirely.

---
## Create IAM User
If you already have access key id and secret access key, skip this step.
Go to your AWS IAM console and create a new user with **Programmatic Access** so you can get the access key id and secret access key.
---
## Attach Policy and Permissions
If possible, attach the **AmazonS3FullAccess** policy to the user. However, if you want to give a minimum set of permissions, use the following policy:
Make sure to replace `BUCKET-NAME` with your actual bucket name.
`s3:DeleteObject` is required so Unlayer can clean up temporary files — for example the test file created by the storage connection test.
```json
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "VisualEditor0",
"Effect": "Allow",
"Action": [
"s3:GetBucketPublicAccessBlock",
"s3:PutObject",
"s3:GetObject",
"s3:DeleteObject",
"s3:PutBucketPublicAccessBlock",
"s3:GetBucketCORS",
"s3:ListBucket",
"s3:PutBucketCORS",
"s3:GetBucketAcl",
"s3:GetBucketLocation",
"s3:PutObjectAcl",
"s3:PutBucketTagging"
],
"Resource": ["arn:aws:s3:::BUCKET-NAME/*", "arn:aws:s3:::BUCKET-NAME"]
},
{
"Sid": "VisualEditor1",
"Effect": "Allow",
"Action": "s3:ListAllMyBuckets",
"Resource": "*"
}
]
}
```
---
## Allow Public Access (Public Bucket Mode)
_Using a private bucket behind a CDN? Skip this section and the bucket policy below — the bucket can keep all public access blocked._
In public bucket mode, the bucket must be permitted to serve public reads:
- Go to S3 in AWS Console
- Select your S3 Bucket
- Click **Edit public access settings**
- Uncheck **Block all public access** if it's checked
- Update the **Object Ownership** on your bucket to be Object Writer.
- Click **Save**

---
## Grant Public Read Access with a Bucket Policy
_Public bucket mode only — with a private bucket behind a CDN, grant read access to the CDN instead (see the CDN section below)._
Unchecking **Block all public access** only _permits_ public access — it does not _grant_ it. Without an explicit grant, uploaded files return **403 Access Denied** when the editor tries to load them.
Add a bucket policy that grants public read access to the objects. Make sure to replace `BUCKET-NAME` with your actual bucket name:
- Go to your S3 Bucket in AWS Console
- Click the **Permissions** tab
- Under **Bucket policy**, click **Edit** and add:
```json
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "PublicReadGetObject",
"Effect": "Allow",
"Principal": "*",
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::BUCKET-NAME/*"
}
]
}
```
Alternatively, if your bucket has ACLs enabled (**Object Ownership** set to Object Writer, as above), Unlayer uploads objects with a `public-read` ACL, which also grants read access. The bucket policy is the more reliable option because it works regardless of the object ownership setting and covers every object in the bucket.
The **Public bucket** option in your Unlayer storage settings controls which mode Unlayer uses: when checked, uploads carry a `public-read` ACL (requires ACLs enabled on the bucket); when unchecked, uploads are sent without an ACL and readability must come from your bucket policy or CDN. If your bucket has ACLs disabled, leave **Public bucket** unchecked — buckets with ACLs disabled reject uploads that carry an ACL.
If you serve files through a CDN such as CloudFront instead (see below), you can keep the bucket itself private and grant read access to the CDN only — in that case public bucket access is not required.
---
## Enable CORS for your S3 Bucket
Your S3 Bucket must have CORS (cross-origin resource sharing) enabled. Follow these steps:
- Go to your S3 Bucket in AWS Console
- Click the **Permissions** tab
- Click the **CORS Configuration** button
- Add the following in the configuration editor
```json
[
{
"AllowedHeaders": ["*"],
"AllowedMethods": ["GET", "PUT", "POST", "DELETE"],
"AllowedOrigins": ["https://*.unlayer.com"],
"ExposeHeaders": []
}
]
```
```xml
https://*.unlayer.com
GET
HEAD
PUT
POST
```
---
## Add Credentials in your Unlayer Project
Simply enter your information of S3 storage against your project. For this:
- Login to Unlayer dashboard
- Select your Project
- Click **Settings** in the navigation bar and select the Storage tab
- Click the **Add Storage** button
- Enter your **Access Key Id, Secret Access Key, and Bucket**
- Set **Public bucket** according to your access mode: check it only for a public bucket with ACLs enabled (**Object Ownership**: Object Writer); leave it unchecked for a private bucket behind a CDN or any bucket with ACLs disabled
- Check **Primary Storage** at the end

---
## Test your File Storage
Click the **Test Storage** button and see if all the items are working properly. If any of these are red, the storage will not work. In that case, please make sure all permissions are properly attached and the bucket exists in the correct region.

In some cases, we attempt to fix certain permissions so you can try clicking Test Storage multiple times. Note that this means Test Storage may modify your bucket's configuration — it can adjust the public-access block settings and add an Unlayer rule to the bucket's CORS configuration (existing customer CORS rules are preserved). It also uploads a small test file and deletes it afterwards.
---
## Connect your CDN (Optional)
You can connect your CDN (content delivery network) such as Cloudfront (or any other) with your storage. It will add caching and load images faster.
A CDN is optional **only if your bucket itself serves public reads** (see the bucket policy section above). If your bucket is private, a CDN (or another URL prefix that can read the bucket) is required for uploaded files to load.
Note: Your CDN must be set up to access your S3 Bucket.
- Login to Unlayer dashboard
- Select your Project
- Click **Settings** in the navigation bar and select the **Storage** tab
- Choose your connected storage
- In **URL Prefix**, add the root URL to your CDN such as `https://cdn.mydomain.com/`
- Optionally, you can also add a path prefix if the URL path also changes
That's it. You are all set 😀
---
## Troubleshooting
If your files are not being uploaded to your S3 bucket correctly, check these:
1. Make sure your plan includes the Amazon S3 Storage feature. Without it, files go to Unlayer's storage instead.
2. Make sure the storage is marked as **Primary**.
3. You must pass **projectId** when initializing the editor.
```javascript
```
4. Make sure the domain you are running the editor on is added under **Allowed Domains** in your project settings > Embed.
If files upload successfully but fail to load in the editor (for example with a **403 Access Denied** from S3), your bucket most likely permits public access without granting it — add the bucket policy from the [Grant Public Read Access](#grant-public-read-access-with-a-bucket-policy) section above. If you use a private bucket behind a CDN instead, verify the CDN has read access to the bucket and that the CDN is set as the **URL Prefix** in your storage settings.
Note on file names: file names may contain spaces and other special characters. Unlayer keeps them in the stored file name and URL-encodes them (e.g. a space becomes `%20`) when building the file's public URL — no renaming is required on your side.
---
## Custom File Storage
:::caution Who needs to do this?
This is only required if you want to host the files somewhere other than Amazon S3. Amazon S3 is supported out of the box and requires no code. You can simply add your AWS Keys and Bucket info under project settings.
:::
By default, we have file storage support built-in with Amazon S3 that can be configured without any coding. If you need to store files somewhere other than Amazon S3 such as your local data center or your own cloud, it can be done by the following way.
## Image Upload Callback
Register this callback function to handle image uploads. The AI Assistant also uses it for image attachments and for generated or edited images applied to the design. Multiple chat attachments invoke the callback once per file, in selection order. Return a URL that Unlayer’s AI service can fetch; an expired or private network URL cannot be used for image editing. See [AI image storage and limits](/ai/assistant/how-it-works/image#upload-storage-and-limits).
The callback stores attachment bytes in your storage. Unlayer may record the returned URL in the File Manager. Generated and edited previews are initially hosted by Unlayer; applying one to the design passes it through this callback.
```javascript
unlayer.registerCallback('image', function (file, done) {
// Handle file upload here
});
```
The function returns 2 parameters. We'll call them file and done.
| Parameter | Type | |
| :-------- | :------- | :----------------------------------------------------------------------------------- |
| **file** | Object | Contains an array, `attachments`. |
| **done** | Function | This is the callback function to update progress bar and handling upload completion. |
## Updating Progress Bar
You can call the done callback and pass an object with progress parameter containing the percentage of completion.
```javascript
unlayer.registerCallback('image', function (file, done) {
// File upload code goes here
done({ progress: 10 }); // Updates the progress bar to 10%
});
```
## Finishing Upload
Once the upload has finished, pass the URL of the image to Unlayer. Passing an HTTP(S) URL without `progress` also completes the upload. Local `blob:` or `data:` previews remain pending until `progress: 100`; include a progress value below 100 for a hosted preview.
```javascript
unlayer.registerCallback('image', function (file, done) {
// File upload code goes here
done({ progress: 100, url: 'URL OF THE FILE' });
});
```
## Aborting or Failing an Upload
If your upload cannot complete — for example, the file fails a custom validation check, your storage backend returns an error, or the user cancels — you can reset the upload state instead of passing a URL. Pass `abort` or `error` to `done`:
| Signal | Result |
| :---------------------------------- | :------------------------------------------------------------------------------ |
| `done({ abort: true })` | Silently resets the upload back to its default state, with no error shown. |
| `done({ error: true })` | Resets the upload and shows a generic "Upload Failed" state. |
| `done({ error: 'Custom message' })` | Resets the upload and shows the "Upload Failed" state with your custom message. |
Use `abort` when the user backs out or you handle the error yourself (e.g. in your own modal), and `error` when you want the builder to surface the failure.
```javascript
unlayer.registerCallback('image', function (file, done) {
// Reject unsupported file types with your own validation
if (!isSupportedImage(file.attachments[0])) {
done({
error: 'Only JPG, PNG, GIF, SVG, or WebP files under 5 MB are supported.',
});
return;
}
// ... upload logic, then done({ progress: 100, url: '...' })
});
```
```javascript
unlayer.registerCallback('image', function (file, done) {
showMyCustomErrorModal(); // you handle the error UI yourself
done({ abort: true }); // just reset the builder's upload state
});
```
:::note
Both `abort` and `error` are optional and fully backward compatible — existing callbacks that pass `{ url }` are unaffected.
:::
## Full Sample Code
We will use **fetch** to upload the file in this sample code. We'll post it to **/uploads** on our server. The following is a complete sample code that handles a file upload.
```javascript
unlayer.registerCallback('image', function (file, done) {
var data = new FormData();
data.append('file', file.attachments[0]);
fetch('/uploads', {
method: 'POST',
headers: {
Accept: 'application/json',
},
body: data,
})
.then((response) => {
// Make sure the response was valid
if (response.status >= 200 && response.status < 300) {
return response;
} else {
var error = new Error(response.statusText);
error.response = response;
throw error;
}
})
.then((response) => {
return response.json();
})
.then((data) => {
// Pass the URL back to Unlayer to mark this upload as completed
done({ progress: 100, url: data.filelink });
});
});
```
---
## File Storage
By default, we support Amazon S3 for storing your files and images. It can be easily set up from the dashboard. You can also connect to a custom storage to save files in your cloud.
Check the following resources to set up your file storage.
---
## Custom Image Library
:::caution Not Recommended
This will take full control of all **Upload Image** buttons in the editor. If you want to give users a way to pick their uploaded images, try [**File Manager**](../file-manager.md) which puts uploaded images in the Uploads tab.
:::
If you want to take full control of the image uploading and management, you can use the following callback.
```javascript
unlayer.registerCallback('selectImage', function (data, done) {
// Open your image library
// Once a user picks an image, call the done function with URL
done({ url: 'IMAGE URL GOES HERE' });
});
```
---
## Full Example

You can try the full example of custom image library: [Custom Image Library Example](https://examples.unlayer.com/media/custom-media-library)
---
## Image Editor(Images)
:::info Looking for the standalone Image Editor?
This page covers the image editor built into the builders, configured through `unlayer.init`. To embed the image editor on its own — outside the builder — see the standalone [Image Editor](../../builders/image-editor/overview.md) docs.
:::
We have a built-in image editor that can be used to resize, crop or apply effects to images. It's enabled by default but you can disable it if you want. You can also access it by double-clicking on any image.
The image editor and its manual editing tools are free. Its optional AI chat requires AI Assistant access and available credits. Legacy Magic Image access alone no longer enables AI editing. The builder forwards its `user` identity and image model/quality settings to this modal. The [standalone AI Assistant guide](../../builders/image-editor/ai-assistant.md) describes its controls.
The builder's [AI Assistant image chat](/ai/assistant/how-it-works/image) also edits images directly in the design. Its granular `features.ai.image` action switches apply to that chat; they do not disable the Image Editor's separate AI panel.
```javascript
unlayer.init({
features: {
imageEditor: {
enabled: false,
},
},
});
```
The editor ships a full tool set: **Crop** (with rotate in 90° steps, flip, a straighten slider for fine-angle rotation, and a corner-rounding radius slider for rounded corners, all built into the same tool), **Resize**, **Draw** (brush color/type/size), **Text** (one-tap style presets grouped into Basic, Handwriting, and Effects, a bundled font library picked from a dropdown that previews each face, and font, color, background, outline, and shadow controls; double-click the text on the canvas to edit it), **Shapes** (circles, rectangles, arrows, stars, and more, grouped into Filled, Outline, and Gradient palettes with search, plus drag/resize/rotate, flip, duplicate, and per-shape color, opacity, outline, and shadow controls), **Stickers** (a bundled sticker library — emoticons, doodles, landmarks, and more — with search and per-category browsing; single-color stickers in the doodles, landmarks, beach, and transportation categories can be recolored and given an outline or shadow after adding), **Frame** (9 preset frames with an adjustable size and a color picker for the basic frame), and **Filters** (one-tap presets like Sepia, Vintage, or Polaroid plus adjustment sliders for brightness, contrast, saturation, vibrance, hue, gamma, blur, pixelate, and noise), alongside the AI Assistant. When the AI Assistant is available it leads the tool rail and its chat panel opens automatically when the editor loads.
The tools appear as a vertical tab rail with a properties panel that opens beside it when a tool is selected. Changes persist automatically — closing a tool's panel, switching to another tool, or saving commits its pending edits, and undo/redo reverts or restores them. There is no separate Apply/Cancel step. The AI Assistant behaves like any other tool — its chat opens in the same panel slot. By default the rail docks to the same side as the builder's own tools panel (`appearance.panels.tools.dock`, which defaults to the right edge), so the image editor stays visually consistent with the rest of the editor; set `dock` to `'left'` or `'right'` to override it for the image editor specifically.
Text, shapes, stickers, and drawings are a **live, re-editable layer** on top of the photo: they stay selectable after you switch tools or close a panel. Click an object on the canvas at any time to re-select it — its tool reopens with the object's current styling so you can move, resize, recolor, reorder (bring to front/forward, send backward/to back), or delete it from the floating toolbar above the selection. The photo underneath is the only raster surface; the layers are flattened onto it when you export or save the image, send it to the AI Assistant, or click the **Flatten layers** toolbar button (which bakes them in as a single undoable step). Most edits keep the object layer live: **resize** scales the layers to match, an **axis-aligned crop** shifts them with the photo, and **filters/adjustments** apply to the photo only (overlaid objects keep their own colors). A few transforms can't be applied to vector objects exactly, so they bake (rasterize) the object layer into the photo and it becomes part of the image: **rotate, flip, and the straighten slider** (all inside the Crop tool). Undo restores the live layer in one step.
```javascript
unlayer.init({
features: {
imageEditor: {
dock: 'left', // 'left' | 'right'; omit to follow appearance.panels.tools.dock
},
},
});
```
### Pinning the image editor version
By default the editor always loads the **latest** image editor, so improvements and fixes reach your editor automatically. If you need a specific, reproducible build — for example to match a version you tested against or to stage a change — pin it with `version`. An unknown or unpublished version transparently falls forward to the latest, so a stale pin never breaks image editing.
```javascript
unlayer.init({
features: {
imageEditor: {
version: '1.500.0', // pin an exact published bundle; omit to always use the latest
},
},
});
```
### Image Editor Tools
You can also choose to disable any of the image editor tools. By default, all of these tools are enabled: Filter, Resize, Crop, Draw, Text, Shapes, Stickers, and Frame. Rotate, flip, and rounded corners all live inside the Crop tool (disabling `corners` hides the corner-radius section).
Here's an example if you want to disable the **Resize** tool in the image editor.
```javascript JavaScript
unlayer.init({
features: {
imageEditor: {
tools: {
resize: false,
},
},
},
});
```
### Customize Tool Icons
Each tool entry also accepts an object form so you can customize its icon while keeping the tool enabled. The `icon` field accepts a FontAwesome icon name (with or without the `fa-` prefix), an image URL (`http(s):`, `data:`, or absolute path), or inline SVG markup (must start with `… ' },
resize: { enabled: false },
},
},
},
});
```
When the icon string cannot be resolved, the editor falls back to the default icon for that tool.
### Translations
The image editor ships with built-in translations for the locale you pass to `unlayer.init({ locale })` and falls back to English when a locale is not yet available. You can override any string — or supply translations for a brand-new locale — through the same `translations` config you use for the rest of the editor (see [Localization](../../advanced-configuration/localization.md)). All image editor keys are grouped under the `image_editor.*` prefix.
> If your project uses [`@unlayer/types`](https://www.npmjs.com/package/@unlayer/types), every translation key (and the rest of the `unlayer.init` config) is fully typed, so your editor will autocomplete translation keys as you write them.
```javascript JavaScript
unlayer.init({
locale: 'fr-FR',
translations: {
'fr-FR': {
'image_editor.toolbar.save': 'Enregistrer',
'image_editor.tools.filter': 'Effets',
'image_editor.ai_assistant.placeholder':
'Décrivez ce que vous souhaitez modifier…',
},
},
});
```
Browse every Image Editor key and built-in locale in [Localization](../../advanced-configuration/localization.md#translation-reference). Select **Image Editor**, then choose a language or copy the locale as JSON.
---
## Images
Images are an important part of designing an email or a landing page. Check the following resources to see what options are available to show user uploaded images or a custom media library.
For AI-powered image search, generation, editing, and alt text, see [AI Assistant images](/ai/assistant/how-it-works/image). The [Images API](/server/cloud-api/images) exposes generation and editing to your backend.
---
## Stock Images
We have a built-in stock image library with millions of royalty-free images from Unsplash, Pexels and Pixabay. It's enabled by default but you can disable it if you want. You can also choose to change the safe searching option and the default search term.
The [AI Assistant](/ai/assistant/how-it-works/image) can also search these libraries when `features.ai.image.search` is enabled. Turning `features.stockImages` off disables stock search in both places; setting only `features.ai.image.search: false` leaves the Images tab available. The Assistant preserves source attribution when showing results.
Users open the **Images** tab in the tools panel, search for a term, and drag or click any result to insert it into the design.
```javascript
unlayer.init({
features: {
stockImages: {
enabled: true,
safeSearch: true,
defaultSearchTerm: 'people',
},
},
});
```
---
## SVG Images
If you would like to allow SVG image uploads, you can use the following feature flag. By default, SVG image uploads are disabled.
```javascript
unlayer.init({
features: {
svgImageUpload: true,
},
});
```
---
## Authentication
Every Unlayer server-side surface — the [Cloud API](/server/cloud-api), the [TypeScript SDK](/sdk), the [CLI](/cli), and the [MCP server](/ai/mcp) — authenticates with a **bearer token** in the `Authorization` header:
```
Authorization: Bearer
```
API Keys and PATs work with the Cloud API and MCP. OAuth access tokens are resource-bound to MCP and cannot be used directly against Cloud API routes.
| Prefix | Token type | When to use |
| --------------- | ---------------------- | ---------------------------------------------------------- |
| `unlayer_sk_*` | API Key | Server-side scripts, CI jobs, single-project integrations. |
| `unlayer_pat_*` | Personal Access Token | Personal use across multiple projects or workspaces. |
| (OAuth JWT) | OAuth 2.1 access token | Interactive MCP clients such as Claude and ChatGPT. |
Both API Keys and Personal Access Tokens are managed from [Console](https://console.unlayer.com/home) — from a project's **Settings** sidebar, or all in one place under **Profile → API Tokens**. Don't have an Unlayer account? [Sign up free](https://accounts.unlayer.com/signup/console). The direct URLs below open the same pages.
## Getting an API Key (`unlayer_sk_*`)
Best for server-side scripts, CI jobs, and single-project integrations. Scoped to **one project** — pick the project whose templates and data the token should be able to read/write.
1. Sign in to [Console](https://console.unlayer.com/home), or [sign up free](https://accounts.unlayer.com/signup/console).
2. Pick the project you want the integration to act on and note its **Project ID** (it's in the URL once you open the project: `console.unlayer.com///...`).
3. Open the project's **Settings → API Keys** (the **v3** entry — not the v2 one, which is a separate legacy key), or navigate directly to:
```
https://console.unlayer.com/builder//settings/project-api-keys
```
Replace `` with your project's numeric ID.
4. Under **Create New API Key**, enter a descriptive name (e.g. _"Production"_, _"CI/CD"_, _"Claude Desktop"_) and click **Create**.
5. Copy the value that starts with `unlayer_sk_` — it's only shown once.
:::warning Show-once secret
API keys are displayed **only once at creation time**. Store the value in a secret manager or `.env` file immediately — Console only displays a partial fingerprint after that. If you lose the value, revoke the key and create a new one.
:::
### Using it
```bash
# Cloud API (Bearer token, v3 endpoints)
curl -H "Authorization: Bearer unlayer_sk_..." \
https://api.unlayer.com/v3/templates
```
```ts
const unlayer = new Unlayer({
apiKey: process.env['UNLAYER_API_KEY'],
});
```
## Getting a Personal Access Token (`unlayer_pat_*`)
Best for personal use when you want one token that works across multiple projects under your account. A PAT inherits your user's access — anywhere you can sign in to, the PAT can act.
1. Sign in to [Console](https://console.unlayer.com/home), or [sign up free](https://accounts.unlayer.com/signup/console).
2. Note any **Project ID** from one of your projects (the route is scoped to a project ID for URL consistency, but the token itself isn't tied to that project).
3. Open **Settings → Personal Access Tokens** from any project (or **Profile → API Tokens**), or navigate directly to:
```
https://console.unlayer.com/home//profile/tokens
```
Replace `` with any project ID you have access to.
4. Click **Create New Token** and fill out:
- **Token Name** (e.g. _"CLI Token"_, _"My laptop — Claude Desktop"_).
- **Scope**: **All Workspaces** (cross-workspace access) or **Single Workspace** (pick one).
- **Expiration**: **Never** or a custom date (up to one year out).
5. Copy the value that starts with `unlayer_pat_` — it's only shown once.
PATs follow the same show-once rule as API keys. Revoke them from the same page if a laptop or client is lost.
:::note Enterprise SSO
A PAT follows the user's current workspace access policy. If a workspace
requires Enterprise SSO, a PAT cannot provide interactive SSO proof and cannot
discover or access that workspace. Project API keys are machine credentials and
are not affected by the interactive sign-in policy.
:::
### Project ID with PATs
Because a PAT isn't bound to a single project, server endpoints that need to know which project to act on require an explicit `projectId` query parameter or `X-Project-Id` header. API keys don't need this — the project is bound to the key on the server.
The TypeScript SDK accepts the PAT and project ID as client options:
```ts
const unlayer = new Unlayer({
personalAccessToken: process.env['UNLAYER_PERSONAL_ACCESS_TOKEN'],
projectID: 'your-project-id',
});
```
## OAuth (no manual token)
:::info Live for Unlayer MCP
OAuth browser sign-in is live for the [Unlayer MCP server](/ai/mcp). OAuth-capable clients can connect now without asking users to generate or paste a token.
:::
You won't generate OAuth tokens by hand — the **MCP client** does it for you. Unlayer's implementation follows the **MCP authorization spec**:
- Authorization-server discovery at [`accounts.unlayer.com/.well-known/oauth-authorization-server`](https://accounts.unlayer.com/.well-known/oauth-authorization-server)
- Protected-resource discovery at [`api.unlayer.com/.well-known/oauth-protected-resource`](https://api.unlayer.com/.well-known/oauth-protected-resource)
- **PKCE** on every flow
- **Dynamic Client Registration** at [`accounts.unlayer.com/oauth/register`](https://accounts.unlayer.com/oauth/register), so MCP clients can self-register without manual setup
- Authorization-code and refresh-token grants, with refresh-token rotation
- Single-project consent: the OAuth token is bound to the project selected during connection
- Resource-bound access and refresh tokens, plus revocation
The resource binding is retained across refreshes. Clients may repeat the MCP resource in a
refresh request or omit it; if they send a different resource, Unlayer rejects the refresh.
This lets Claude Desktop, ChatGPT, and other OAuth-capable clients connect with a browser-based **"Sign in with Unlayer"** flow. The browser handles consent, while the client stores the resulting bearer token and refreshes it automatically. CI should continue to use a project-scoped API key rather than trying to automate an interactive OAuth consent flow.
See the [MCP](/ai/mcp) page for connection instructions.
## Security checklist
- **Server-side only.** Never ship API keys or PATs to the browser — they grant full access to your project's data. Always proxy through your backend.
- **Use a secret manager.** Don't commit tokens to source control. Use Vercel/Netlify/AWS secret stores, GitHub Actions secrets, etc.
- **Rotate on compromise.** If a laptop is lost, a CI job is exposed, or a key leaks into a log — revoke it in Console immediately and issue a new one.
- **Least-privilege scope.** Prefer an API key (project-scoped) over a PAT (account-scoped) when the integration only needs one project.
## Related
- **[Cloud API](/server/cloud-api)** — REST endpoints these tokens authenticate against.
- **[Cloud API reference](/server/cloud-api/reference)** — full endpoint reference with auth headers shown per operation.
- **[CLI](/cli)** — terminal tool for managing templates and projects.
- **[TypeScript SDK](/sdk)** — typed access to supported Cloud API operations with the credential required by each operation.
- **[MCP](/ai/mcp)** — Model Context Protocol server with the same token model + OAuth.
PAT-authenticated project configuration updates use the token owner's current
project permissions and workspace SSO policy. They do not require a Console
browser session.
---
## AI Credits API & Webhooks
If you embed the Unlayer builder and resell the [AI Assistant](/ai/assistant) to your own end-users, these endpoints give you programmatic visibility into AI credit consumption so you can build billing, set limits, and message your users.
Everything here is measured in **credits** — the single unit exposed across every endpoint and webhook.
:::info Credits are pooled per workspace
A project's AI credits belong to its **workspace**. Every project in the same workspace draws from — and reports against — one shared balance. Webhook and alert **settings**, however, are configured **per project**.
:::
All endpoints require an **API Key** (`unlayer_sk_*`) scoped to the project, sent as a bearer token. See [Authentication](/server/authentication). A key can only access its own project.
If you call these endpoints with a **Personal Access Token** instead, your account must be an **admin or owner** of the project — these endpoints expose the webhook signing secret and destination URL. Other roles receive `403`.
---
## Endpoints
### Get credit balance
```
GET /v3/projects/:id/ai-credits
```
Returns a near-real-time snapshot of the current **workspace** credit pool. The
project ID identifies the workspace and authorizes the request; it does not
limit the balance to that project. Calling this endpoint for two projects in
the same workspace returns the same balance.
```json
{
"is_capped": true,
"credits_total": 10000,
"credits_used": 7400,
"credits_remaining": 2600,
"reset_date": "2026-08-01T00:00:00.000Z"
}
```
`is_capped` reports whether enforcement can constrain AI usage, not whether
Console has a positive allowance to display. A shadow-mode workspace with a
plan or add-on allowance can show a remaining allowance in Console while this
endpoint returns `false`; the editor balance indicator stays hidden and
threshold/exhausted webhooks do not fire.
When `is_capped` is `false`, usage is metered for visibility but remains
uncapped: `credits_total` and `credits_remaining` describe the metered
allocation, not an available balance, and reaching zero does not pause AI or
create overage charges. Use `credits_used` to report consumption, but do not
render an exhausted state from `credits_remaining`.
`reset_date` is the end timestamp returned for the current credit window, or
`null` when the service cannot resolve an active future billing window. That
includes a subscription that has been cancelled, deactivated, or reached the
end of its term.
A scheduled cancellation does not make `reset_date` null while the current
window is still active. If the subscription ends with that window, credits
expire on that date rather than renewing. Annual subscriptions can still have
monthly credit resets before their final term end, so do not interpret every
`reset_date` as a subscription renewal or cancellation date.
AI credit balances update asynchronously after usage is recorded. Re-delivery of
the same usage event does not consume additional credits. Current-day activity
is counted by the live usage processor; reconciliation finalizes previous UTC
days without adding the same activity again. A delayed or failed live update
may remain absent until the next day's reconciliation.
### Get usage breakdown
```
GET /v3/projects/:id/ai-credits/usage
```
Returns the selected **project's** credit consumption, broken down by end user
and feature type. Usage is grouped by the UTC date when the AI activity
occurred. The current UTC day is updated near real time and may take a short
time to appear. Each recorded AI event contributes once to this breakdown,
including when its delivery is retried.
| Query param | Description |
| -------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `start` | Start date (inclusive), `YYYY-MM-DD`. Must be on or before `end`. Defaults to the active credit window's start, or 30 UTC dates before today when no active window is available. |
| `end` | End date (inclusive), `YYYY-MM-DD`. Defaults to the active credit window's end, or today when no active window is available. |
| `end_user_id` | Filter to a single end user. |
| `feature_type` | Filter to a single [feature type](#feature-types). |
| `limit` | Max breakdown rows to return (1–1000). Defaults to `100`. |
| `offset` | Number of breakdown rows to skip (pagination). Defaults to `0`. |
| `sort` | Field the breakdown is ordered by: `credits`, `end_user_id`, or `feature_type`. Defaults to `credits`. |
| `order` | Sort direction: `asc` or `desc`. Defaults to `desc`. |
```json
{
"total_credits_used": 6300,
"total": 3,
"breakdown": [
{ "end_user_id": "user_123", "feature_type": "block_edit", "credits": 200 },
{
"end_user_id": "user_456",
"feature_type": "full_template_gen",
"credits": 4000
},
{ "end_user_id": null, "feature_type": "image_generation", "credits": 2100 }
]
}
```
:::note Why the totals may differ
In the examples above, the workspace has used `7400` credits, while the
selected project accounts for `6300`. Usage from other projects in the
workspace is included in `credits_used` but not in `total_credits_used`.
The totals may also differ briefly because the workspace balance and project
breakdown are updated independently from the same asynchronous event stream.
Even for a single-project workspace and an unfiltered current-period query,
recent usage may reach one view before the other. Settled-day finalization
keeps the detailed ledger aligned with the authoritative analytics data.
:::
When neither date is supplied and the workspace has no active credit window,
the fallback covers the 30 UTC dates before today plus today itself (31
calendar dates, inclusive).
The `breakdown` is **paginated** — one `end_user_id` × `feature_type` row per entry, up to `limit`. It defaults to highest-credit rows first; use `sort` / `order` to change that (e.g. `sort=credits&order=asc` for lowest first, or `sort=end_user_id` alphabetically). `total` is the number of breakdown rows matching the filter (across all pages), for paging. `total_credits_used` is the credit total across the **entire filtered range**, not just the returned page — so you can reconcile without walking every page. Narrow the response with `end_user_id` / a smaller date range, or page with `limit` / `offset`.
:::note Per-user attribution
`end_user_id` is populated when the AI call identifies an end user:
- **Builder** — identify the user via [`unlayer.init({ user })`](/builder/end-user-identification). The builder forwards this user to its built-in Image Editor automatically; no additional configuration is needed.
- **Standalone Image Editor** — when you initialize it yourself, pass a `user` to [`ImageEditor.createEditor()`](/builder/image-editor/ai-assistant).
- **Server-side AI endpoints** — send `end_user_id` in the request body of `POST /v3/templates/generate`, `POST /v3/templates/import`, and `POST /v3/images/generate`.
Calls made without an identified end user are reported with `end_user_id: null` and still consume credits. If you already identify your users and see unexpected unattributed usage, contact support so the originating requests can be investigated.
:::
### Settlement and reconciliation
Treat the current UTC day's breakdown as provisional. After the day closes,
Unlayer replaces the streaming projection with the complete settled result.
That replacement can move a total up or down because the streaming and settled
pipelines are separate views and the settled snapshot replaces the day rather
than adding to it.
For reliable billing and limits:
1. Verify and deduplicate webhooks as described below, then use them for fast
updates.
2. Reconcile completed UTC days from this endpoint.
3. Compare a workspace balance only with the sum of **all projects** in that
workspace over the same monthly window, with no end-user or feature filter.
The workspace balance remains the authority for whether more AI work can run.
The settled usage endpoint is the durable source for project, end-user, and
feature attribution.
:::note Legacy activity
Billable legacy AI actions are included in this breakdown and the
`usage_recorded` webhook. Identify the user in the builder configuration to
attribute them automatically. Historical events without a recorded user ID
remain unattributed. The older per-element text suggestion endpoints exclude
calls made with a supported custom provider key from their usage reporting.
Current AI Assistant and image requests still consume Unlayer credits when using
a custom provider key, in addition to the provider billing that account. A stored
key that is not used does not change a call made with Unlayer’s key.
:::
### Update settings
```
PUT /v3/projects/:id/ai-credits/settings
```
```json
{
"exhaustion_behavior": "show_error",
"threshold_alerts": [80, 95],
"webhook_url": "https://partner.com/webhooks/unlayer"
}
```
| Field | Description |
| --------------------- | ----------------------------------------------------------------------------------------- |
| `exhaustion_behavior` | `"disable"` hides AI features when credits run out; `"show_error"` shows an error prompt. |
| `threshold_alerts` | Usage percentages (1–100) at which a `threshold_reached` webhook fires for capped usage. |
| `webhook_url` | HTTPS endpoint that receives AI credit webhooks. |
All fields are optional; omitted fields keep their current values.
:::warning Save your signing secret
The first time you set a `webhook_url`, the response includes a **`signing_secret`** — used to verify webhook signatures. It is returned **once** and never shown again. Store it securely.
:::
```json
{
"exhaustion_behavior": "show_error",
"threshold_alerts": [80, 95],
"webhook_url": "https://partner.com/webhooks/unlayer",
"has_signing_secret": true,
"signing_secret": "b1946ac9…"
}
```
### Read settings
```
GET /v3/projects/:id/ai-credits/settings
```
Returns the project's current configuration. The signing secret itself is never returned — only whether one exists.
```json
{
"exhaustion_behavior": "show_error",
"threshold_alerts": [80, 95],
"webhook_url": "https://partner.com/webhooks/unlayer",
"has_signing_secret": true
}
```
| Field | Description |
| --------------------- | ------------------------------------------------------------- |
| `exhaustion_behavior` | `"disable"` or `"show_error"`. |
| `threshold_alerts` | Configured usage percentages that fire `threshold_reached`. |
| `webhook_url` | The configured HTTPS endpoint, or `null`. |
| `has_signing_secret` | Whether a signing secret exists (the secret is never echoed). |
---
## Webhooks
When a `webhook_url` is configured, Unlayer POSTs the following events to it.
The setting applies to the whole project; it cannot be limited to selected end
users. Filter `data.end_user_id` in your receiver, or query that end user from
the usage endpoint.
| Event | Fires when… |
| ------------------------------ | ------------------------------------------------ |
| `ai.credits.usage_recorded` | After each classified real-time AI call. |
| `ai.credits.threshold_reached` | Capped usage crosses a configured percentage. |
| `ai.credits.exhausted` | A capped workspace balance reaches zero credits. |
Every request body has the shape `{ "event": "", "data": { … } }`.
### `ai.credits.usage_recorded`
```json
{
"event": "ai.credits.usage_recorded",
"data": {
"project_id": 123,
"end_user_id": "user_123",
"feature_type": "block_edit",
"credits_deducted": 3,
"timestamp": "2026-07-01T12:00:00.000Z"
}
}
```
`feature_type` carries the same values as the usage endpoint, listed under
[Feature types](#feature-types). Handle an unrecognized one rather than
switching exhaustively: `image_edit` is new, and the set can grow again.
Use this event for low-latency updates, not as the final billing total. The
payload for an individual call is not revised after delivery, while the settled
usage endpoint aggregates a complete day. Summing webhook
`credits_deducted` values can therefore differ from the settled API total.
### `ai.credits.threshold_reached`
Fires once per configured threshold per billing period for a capped workspace.
Uncapped usage does not emit threshold events. If the credit allocation
increases mid-period (an add-on or plan change), the threshold re-arms and
fires again the next time it's crossed against the larger allocation.
```json
{
"event": "ai.credits.threshold_reached",
"data": {
"project_id": 123,
"threshold": 80,
"credits_remaining": 2000,
"credits_total": 10000,
"timestamp": "2026-07-01T12:00:00.000Z"
}
}
```
### `ai.credits.exhausted`
Fires once per billing period when a capped workspace pool reaches 0. Uncapped
usage does not emit exhausted events because reaching the metered allocation
does not pause AI. If the customer tops up mid-period (an add-on or plan change)
and then exhausts the larger allocation, it fires again — so a top-up that runs
out is not silently missed.
```json
{
"event": "ai.credits.exhausted",
"data": {
"project_id": 123,
"workspace_id": 45,
"timestamp": "2026-07-01T12:00:00.000Z"
}
}
```
:::info Delivery timing
`usage_recorded` is delivered in real time. `threshold_reached` and `exhausted` are derived from aggregated usage and may lag actual consumption by up to an hour.
:::
### Verifying signatures
Each delivery carries four headers:
| Header | Value |
| ----------------------- | ------------------------------------------------- |
| `X-Unlayer-Signature` | `sha256=` HMAC of the request. |
| `X-Unlayer-Timestamp` | Unix milliseconds when the request was signed. |
| `X-Unlayer-Event` | The event name. |
| `X-Unlayer-Delivery-Id` | Stable id for tracing a delivery across attempts. |
### Handling duplicates
Delivery is **at-least-once**: a failed delivery is retried automatically, and a
delivery can occasionally be sent more than once even after it has succeeded —
for example if a retry was already in flight when the first attempt landed.
Verify the signature and timestamp freshness before processing or deduplicating
a request. Then use `X-Unlayer-Delivery-Id` to collapse ordinary at-least-once
retries; it stays the same across attempts of one delivery:
```js
const deliveryId = headers['x-unlayer-delivery-id'];
if (typeof deliveryId !== 'string' || !deliveryId) {
return res.sendStatus(400);
}
if (await alreadyProcessed(deliveryId)) {
return res.sendStatus(200); // already handled — acknowledge and stop
}
```
The signature authenticates the timestamp and raw body, but not
`X-Unlayer-Event` or `X-Unlayer-Delivery-Id`. Use the event name from the
verified body. The delivery id handles normal retry duplication; it is not
replay-proof because it is unsigned. Keep the timestamp tolerance narrow, make
downstream writes idempotent where your data model allows it, and use the
settled usage endpoint—not webhook deduplication alone—as the billing authority.
Always respond `2xx` to a duplicate. A non-2xx response marks the delivery
failed and schedules another retry.
The signature is an HMAC-SHA256 over the string `` `${timestamp}.${rawBody}` `` using your `signing_secret`. Compute it yourself and compare in constant time:
```js
function isValid(rawBody, headers, secret) {
const timestamp = headers['x-unlayer-timestamp'];
const received = headers['x-unlayer-signature'];
const signedAt = Number(timestamp);
if (
typeof timestamp !== 'string' ||
typeof received !== 'string' ||
!Number.isSafeInteger(signedAt) ||
Math.abs(Date.now() - signedAt) > 5 * 60 * 1000
) {
return false;
}
const expected =
'sha256=' +
crypto
.createHmac('sha256', secret)
.update(`${timestamp}.${rawBody}`)
.digest('hex');
return (
expected.length === received.length &&
crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(received))
);
}
```
Sign over the **raw request body**, before any JSON parsing — re-serializing can
change bytes and break the comparison. The five-minute tolerance above is an
example; choose a short window that fits your delivery latency and clock-skew
requirements.
### Delivery & retries
Return a `2xx` to acknowledge a webhook. A non-`2xx` response (or a timeout — endpoints have ~10s to respond) is retried. Each delivery is attempted up to **3 times** in quick succession (~90s apart); if it still hasn't succeeded, it is **re-attempted periodically** for a while afterward, so a transient outage on your endpoint recovers on its own. Because a delivery can be retried, your endpoint **must be idempotent** — the same event may arrive more than once, and events are not guaranteed to arrive in order.
### Delivery history & manual retry
All events — `usage_recorded`, `threshold_reached`, and `exhausted` — are tracked in the delivery history. Inspect recent deliveries and re-send failed ones without waiting for the automatic retry.
#### List deliveries
```
GET /v3/projects/:id/ai-credits/webhooks/deliveries
```
The delivery history, newest first.
| Query param | Description |
| ----------- | -------------------------------------------------------------- |
| `status` | Filter to a single status: `pending` / `delivered` / `failed`. |
| `event` | Filter to a single [event](#webhooks). |
| `limit` | Max deliveries to return (1–100). Defaults to `50`. |
| `offset` | Number of deliveries to skip (pagination). Defaults to `0`. |
Each delivery has `event`, `status`, `attempts`, `last_status_code`, `end_user_id` (when the event carries one), `created_at`, and `delivered_at`. The response also includes `total` — all deliveries matching the filter, ignoring paging.
#### List a delivery's attempts
```
GET /v3/projects/:id/ai-credits/webhooks/deliveries/:deliveryId/attempts
```
The per-attempt history for one delivery, newest attempt first. Returns `404` if the delivery isn't found for this project.
| Query param | Description |
| ----------- | --------------------------------------------------------- |
| `limit` | Max attempts to return (1–100). Defaults to `50`. |
| `offset` | Number of attempts to skip (pagination). Defaults to `0`. |
Each attempt has `attempt` (the attempt number), `status_code`, `error`, and `attempted_at`, plus a `total`.
#### Retry a delivery
```
POST /v3/projects/:id/ai-credits/webhooks/deliveries/:deliveryId/retry
```
Re-queue one delivery for another attempt. Returns `409` if it was already delivered. Retries deliver to your **current** webhook URL and signing secret, so correcting a wrong URL and retrying recovers the events that failed against the old one.
:::note Retention
`usage_recorded` is high volume (one per AI call), so its rows are pruned from the history: successfully-delivered rows after 30 days, and failed or pending rows after 90 days (long past the last automatic retry) — filter with `?event=ai.credits.usage_recorded` to find recent ones. `threshold_reached` and `exhausted` deliveries are retained. For a complete billing record, the [usage breakdown](#get-usage-breakdown) endpoint remains the durable source of truth.
:::
### Rotating the signing secret
`POST /v3/projects/:id/ai-credits/settings/rotate-secret` returns a new signing secret **once**. The previous secret stops working immediately, so update your verification before rotating. To check whether a secret is set without rotating, use [Read settings](#read-settings).
A `webhook_url` is required — the signing secret is generated when you first set one. Rotating before then returns `400`.
---
## Feature types
`feature_type` classifies what an AI call did:
| `feature_type` | Meaning |
| ------------------- | ----------------------------------------------------------------------------------- |
| `full_template_gen` | Generating a full template / layout. |
| `block_edit` | Editing a block, generating text suggestions, or automatically describing an image. |
| `html_import` | Importing a design from HTML. |
| `image_import` | Reconstructing an editable design from an image or screenshot. |
| `image_generation` | Generating a new image from a prompt. |
| `image_edit` | Editing an image that already exists. |
The last two are distinguished by the operation. The builder AI Assistant and [Images API](./images.md) can generate new images or edit existing ones; the standalone Image Editor edits its current image.
One Assistant turn can produce a text/design usage event plus one `image_generation` or `image_edit` event per image operation. The chat and conversational API total include those image operations; they are not charged again as text. Automatic alt text is a separate `block_edit` call after an image is added or changed through AI. Ordinary uploads, URL changes, and edits made without AI do not trigger this call. Uploading, reordering, previewing, adding a result to the prompt, and using **Undo change** do not themselves run a paid image operation.
Legacy Smart Headings, Smart Text, Smart Buttons, and image-to-text suggestions
are included as `block_edit`. Legacy Magic Image generation and its image-prompt
suggestions are included as `image_generation`. These actions already consumed
credits; including them in the usage breakdown and usage webhooks does not add
another charge. The builder's existing user identification supplies their
end-user attribution automatically. Direct project-key calls to legacy text
routes have no end-user identity and are reported as unattributed.
Older legacy events that are reprocessed can appear in these categories, but
events recorded without an end-user ID remain unattributed. This change does
not reconstruct missing identities or automatically backfill all past usage.
:::note `image_edit` is new
AI image edits used to be reported as `image_generation`. They now have their own
`feature_type`, so a filter or chart pinned to `image_generation` no longer includes them.
If you break usage down by feature, add `image_edit` to whatever you already do for
`image_generation`. Usage recorded before this change keeps its original
`image_generation` classification; nothing is reclassified retroactively.
:::
---
## Related
- **[Authentication](/server/authentication)** — how to create the API Key these endpoints require.
- **[Cloud API overview](/server/cloud-api)** and the **[API reference](/server/cloud-api/reference)**.
- **[End-User Identification](/builder/end-user-identification)** — pass `user.id` in `unlayer.init()` so usage is attributed per end user.
- **[End-User AI Credits & Upsell](/ai/credit-upsell)** — display a host-managed per-user allowance and purchase flow.
- **[AI Assistant Events & Callbacks](/ai/assistant/events-callbacks)** — session telemetry that complements, but does not replace, billing usage.
- **[AI Assistant](/ai/assistant)** — the feature these credits pay for.
---
## Blocks API
Blocks are reusable design fragments your users save in the editor. They come in two flavors:
- **Shared project blocks** — available to everyone in the project.
- **[User-saved blocks](/builder/blocks/user-saved)** — saved by one of your end-users and visible only to them (the user id your app passes to the editor at init time).
The Blocks API lets your backend list **all of them in one sweep** — you don't need to know or enumerate your end-user IDs. Each user-saved block carries the `userId` it was saved under, so you can:
- **Report usage** — which of your end-users rely on saved blocks, and how many each has.
- **Back up or migrate** — export every block's design JSON, including blocks saved by users you can no longer identify individually.
:::warning Server-side only
This endpoint returns blocks saved by **every** end-user in the project. Never call it from a browser, and never proxy its unfiltered response to one of your end-users — if you expose blocks to an end-user, filter with the `userId` parameter to that user's own blocks. See [Authentication](/server/authentication) for token handling guidelines.
:::
---
## List blocks
```
GET https://api.unlayer.com/v3/blocks
```
Authenticate with a bearer token — a project **API Key** is recommended. With a **Personal Access Token**, also pass `projectId` (query param or `X-Project-Id` header).
```bash
curl "https://api.unlayer.com/v3/blocks?displayMode=email" \
-H "Authorization: Bearer unlayer_sk_your_api_key"
```
### Query parameters
| Parameter | Type | Default | Description |
| ------------- | ------- | ------- | ------------------------------------------------------------------------------------------------------------- |
| `limit` | integer | `20` | Blocks per page (1–100). |
| `cursor` | string | — | Pagination cursor from the previous response. |
| `displayMode` | string | — | Filter by display mode: `email`, `web`, `popup`, or `document`. Omit to list blocks across all display modes. |
| `scope` | string | `all` | `shared` for project blocks only, `user` for end-user saved blocks only, `all` for both. |
| `userId` | string | — | Only blocks saved by this end-user (exact match on the user id your app passes to the editor). |
| `category` | string | — | Filter by category (case-insensitive search). |
| `includeData` | boolean | `true` | Whether to include each block's design JSON. Pass `false` for lightweight sweeps such as usage reports. |
| `projectId` | string | — | Required with a Personal Access Token; omit with an API key (the project is embedded in the key). |
### Response
```json
{
"data": [
{
"id": "918",
"userId": "u_4f8a12",
"displayMode": "email",
"category": "Headers",
"tags": ["header", "promo"],
"data": { "columns": ["…"] },
"thumbnailUrl": "https://…/thumbnail.png",
"syncId": null,
"isSyncEnabled": false,
"createdAt": "2026-06-14T09:12:33.000Z",
"updatedAt": "2026-07-01T16:40:05.000Z"
},
{
"id": "702",
"userId": null,
"displayMode": "email",
"category": "Footers",
"tags": [],
"data": { "columns": ["…"] },
"thumbnailUrl": null,
"syncId": "s-b41c…",
"isSyncEnabled": true,
"createdAt": "2026-03-02T11:00:00.000Z",
"updatedAt": "2026-03-02T11:00:00.000Z"
}
],
"next_cursor": "aWQ6NzAy",
"has_more": true
}
```
- `userId` is `null` for shared project blocks and set to the end-user id for user-saved blocks.
- `syncId` / `isSyncEnabled` identify [synced blocks](/builder/blocks/sync); designs reference synced blocks by `syncId`, so preserve it when migrating.
- `data` is the block's design JSON, returned exactly as stored. Pages can be large with `includeData=true` — keep `limit` modest when sweeping designs.
### Pagination
Follow `next_cursor` until `has_more` is `false`:
```bash
curl "https://api.unlayer.com/v3/blocks?limit=100&cursor=aWQ6NzAy" \
-H "Authorization: Bearer unlayer_sk_your_api_key"
```
The listing is a point-in-time sweep: blocks created while you are paginating may not appear until the next sweep.
---
## Recipe: who uses saved blocks, and how many each?
Sweep with `includeData=false` (no design payloads — fast and small), then group by `userId`:
```js
const headers = { Authorization: `Bearer ${process.env.UNLAYER_API_KEY}` };
const counts = {};
let cursor = null;
do {
const url = new URL('https://api.unlayer.com/v3/blocks');
url.searchParams.set('includeData', 'false');
url.searchParams.set('scope', 'user');
url.searchParams.set('limit', '100');
if (cursor) url.searchParams.set('cursor', cursor);
const page = await fetch(url, { headers }).then((r) => r.json());
for (const block of page.data) {
counts[block.userId] = (counts[block.userId] ?? 0) + 1;
}
cursor = page.next_cursor;
} while (cursor);
// counts = { "u_4f8a12": 12, "u_9c01d7": 3, … }
```
Drop `scope=user` to include shared project blocks in the same sweep — they arrive with `userId: null`.
For a **backup**, run the same loop without `includeData=false` and persist each block's `data` (and `syncId`, if set).
---
## Notes
- **The API can return more blocks than the editor shows.** The editor displays blocks up to your plan's Blocks limit; this endpoint is a faithful dump of everything stored in the project, so counts can differ — for example after a plan downgrade. That is intentional: backups must not silently lose blocks.
- The API does not modify blocks — creating, updating, and deleting blocks still happens through the editor.
---
## Export Allowances
enforcementStartDate,
exportsPerPack,
negotiatedPackageAbove,
packPrice,
} from '@site/src/components/ExportAllowances';
# Export Allowances
Every current plan includes a monthly allowance of **exports rendered on Unlayer's servers**. Every export counts once, whatever the format.
## What counts
| Export | Counts toward the allowance |
| -------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------- |
| Cloud API exports: HTML, PDF, image and ZIP | Yes |
| Builder [`exportImage`](/builder/export-image), [`exportZip`](/builder/export-zip) and, outside the Document Builder, [`exportPdf`](/builder/export-pdf) | Yes — they render on Unlayer's servers |
| Document Builder PDFs rendered in the browser ([PDF Rendering](/builder/latest/document-builder/pdf-rendering)) | No — they run in the browser |
| Builder [`exportHtml`](/builder/export-html) and `exportPlainText` | No — they run in the browser |
Exports from **test projects count** the same as exports from live projects.
The allowance belongs to the **workspace**: every project in the workspace draws from one monthly pool, which resets at the start of each monthly usage window.
## Monthly allowances
Workspaces that need more than {negotiatedPackageAbove} exports per month can arrange a high-volume package with Unlayer. Older plans show their allowance in Console under **Billing → Usage & add-ons**.
## When allowances apply
Allowances are enforced from the first billing period that starts on or after **{enforcementStartDate}**: the first renewal on or after that date for monthly subscriptions, and the next renewal after it for annual subscriptions. Until then, exports are counted and shown in Console but never blocked. Allowance periods run in whole UTC days: each one counts exports from 00:00 UTC on its renewal date to the end of the day before the next renewal, so every export counts toward exactly one period. The first enforced period starts counting the day after its renewal date, so exports made before enforcement began never count toward it.
## Tracking usage
Console shows the workspace's exports for the current window under **Billing → Usage & add-ons**. Once allowances apply to your subscription, the workspace owner also receives alerts at 75%, 90% and 100% of the allowance.
Successful export responses include:
| Header | Meaning |
| --------------------- | ------------------------------------------------------------------------ |
| `X-Credits-Total` | The workspace's allowance for the current window, including add-on packs |
| `X-Credits-Remaining` | Exports left in the current window |
## Reaching the allowance
Once the allowance is used, export requests return `429` with the error code `CREDITS_EXHAUSTED` until the next monthly window or until more capacity is added.
To add capacity on a plan with an allowance, buy **Export Credits** in Console under **Billing → Usage & add-ons**. Each {packPrice} pack adds {exportsPerPack} exports per month, in any mix of formats.
---
## Images(Cloud-api)
Choose the endpoint that matches your workflow:
| Workflow | Endpoint |
| ----------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- |
| Generate one image or edit one source image | `POST /v3/images/generate` |
| Combine text/design changes, image generation, multiple-reference edits, and follow-up messages | `POST /v3/templates/generate` with `features.ai.image` |
| Reconstruct an editable template from a screenshot | `POST /v3/templates/import` — see [Template Importer](/ai/template-importer) |
## Generate or edit one image
`POST /v3/images/generate` creates one custom image. Supply an optional `image` to edit an existing image instead. It uses the same image service as the AI Assistant and the standalone Image Editor.
Authenticate with your project API key. Personal Access Tokens and OAuth tokens also support this endpoint with a `projectId` query parameter; OAuth tokens require `designs:write` scope. Personal Access Tokens use your workspace permissions rather than OAuth scopes. The project must have AI Assistant access and available AI credits.
```bash
curl https://api.unlayer.com/v3/images/generate \
--header "Authorization: Bearer $UNLAYER_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
"prompt": "Create a watercolor illustration of a turtle swimming underwater",
"end_user_id": "customer-123"
}'
```
```json
{
"operation": "image_generation",
"image": { "url": "https://assets.example/generated-image.png" }
}
```
To edit, include the source URL and describe the change. Prompts may be written in the user's language.
```json
{
"prompt": "Remove the background and keep the turtle",
"image": "https://your-cdn.example/turtle.png",
"background": "transparent",
"end_user_id": "customer-123"
}
```
The response has `operation: "image_edit"`. Check for `image` before using its URL: a successful provider response may contain a text `message` without an image, for example when clarification is needed. There is no separate `/v3/images/edit` endpoint.
| Field | Purpose |
| ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `prompt` | Required instruction, up to 20,000 characters. |
| `image` | Optional publicly reachable image URL or PNG, JPEG, WebP, or GIF base64 data URL, at most 10 MB after decoding or downloading. Omit to generate a new image. |
| `background` | Optional `transparent` or `opaque`. Omission keeps the existing provider behavior. Use `transparent` to require real alpha or `opaque` for a filled background. |
| `end_user_id` | Optional stable identifier for end-user usage attribution. |
| `model` | Optional image provider/model selection. Omit to use Unlayer's default. |
| `quality` | Optional `low`, `medium`, or `high`; omission uses the selected provider's default. |
| `fallbackModels` | Optional boolean or ordered array of image models for transient provider failures. |
`model` accepts a provider (`openai` or `google`), a supported model ID, or a `provider/modelId` pair. Leave it unset to use Unlayer’s default. Supported model IDs are `gpt-image-2.5-flare`, `gpt-image-2.5-sunburst`, `gemini-nano-banana-2.1`, `gpt-image-1.5`, `gpt-image-2`, and `gemini-3.1-flash-image`. The direct Images API and Assistant API retain the earlier Gemini 3.1 default; select a new model explicitly to use it. The retired Gemini IDs `gemini-2.5-flash-image` and `gemini-3.1-flash-image-preview` are still accepted and run on `gemini-3.1-flash-image`.
`gpt-image-1.5` and `openai/gpt-image-1.5` now run on GPT Image 2.5 Flare as
compatibility aliases, including with `fallbackModels: false`. OpenAI retires
1.5 on December 1, 2026. Quality and provider selection are preserved; usage is
attributed to Flare without changing historical 1.5 records. A key without Flare
access fails when fallbacks are disabled. Automatic legacy fallback chains no
longer call 1.5; ordinary requests retain GPT Image 2, while automatic transparent
output uses Flare. A bare `openai` setting also uses Flare when transparency is
required. The legacy API v2 image-suggestions
endpoint also defaults to Flare without a model-version header, while its
supported `2026-05-13` header continues to select GPT Image 2.
When both `model` and `fallbackModels` are omitted, Unlayer may use its default fallback chain. Pinning `model` disables that chain unless `fallbackModels` is `true` or an ordered list. Use `fallbackModels: false` to disable it explicitly, or an array of up to ten models to replace it. The chain also supplies compatible models when real transparency is required. Fallback handles temporary provider failures; invalid input, unsupported models, and rejected credentials do not trigger a switch. Configured custom provider keys are selected for the provider actually called.
Transparency requires a supported OpenAI image model that returns native transparent PNGs. Only compatible models from your configured model/fallback chain are used; if none are available, the request returns `400` before generation. An opaque result is rejected with `422`, without returning an image or charging image credits. To request a transparent new asset, pass `background: "transparent"`; a prompt alone does not enforce the pixel check. Validated transparent results support non-animated images up to 25 megapixels.
GPT Image 2 transparency is a provider preview. Automatic alpha routing uses
Flare; exact model selections and caller-provided fallback lists are preserved.
An exact Image 2 transparency request can be rejected by the provider, and an
invalid transparency option does not trigger outage fallback.
For OpenAI, omitted `quality` means `medium`. For Gemini, omission leaves resolution at the provider default; explicit low/medium/high requests map to 1K/2K/4K, subject to model support. Higher resolution can consume more credits.
GIF inputs use the first frame and produce still images. Both the original GIF and its first frame converted to PNG must fit the image-operation byte limit; the frame is limited to 25 megapixels.
Source URLs must return a supported image directly and be reachable without your application’s cookies or authorization headers. Use a sufficiently long-lived signed URL when the source is private. Redirect destinations must also be publicly reachable.
Returned images are temporary: copy the image to your own storage within seven days. If temporary storage is unavailable, `image.url` may be a data URL; store those bytes directly.
The direct endpoint returns the image or message, not a per-request `usage` object. Usage is reported as `image_generation` or `image_edit` in [AI credits reporting](./ai-credits.md). A project without access receives `403`; exhausted credits return `429`. Invalid input returns `400`, oversized request bodies return `413`, and an unavailable image provider returns `502`. Provider key failures also return `502`, with `CUSTOM_AI_KEY_INVALID` for a rejected project key or `AI_PROVIDER_AUTH_FAILED` for an Unlayer provider configuration issue. A valid Unlayer credential does not need to be replaced in either case. Structured provider safety refusals return `422` with `IMAGE_SAFETY_REJECTED` and are not retried or charged image credits. A normal provider clarification can return `200` with only `message`; that successful provider response consumes credits for its reported input and output usage. This endpoint does not search stock libraries.
## Images in an Assistant conversation
Assistant edits preserve existing real transparency unless the prompt explicitly requests a filled background. Pure black-and-white conversions preserve the displayed orientation, dimensions and alpha mask. Single-color replacements in supported flat logos change all occurrences of the selected color, including foreground and background pixels of that color, while preserving dimensions, other colors and alpha. They decline complex or ambiguous sources. Background-only and selected-region changes use generative editing. An existing painted checkerboard requires explicit background removal or the original alpha asset. Flat-logo replacement supports sources up to 4 megapixels. Assistant alpha inspection and grayscale conversion support non-animated sources up to 25 megapixels; ordinary JPEG edits do not require alpha inspection.
Use the existing `POST /v3/templates/generate` endpoint when a request combines design changes, text, and images. Its `messages` accept image parts alongside text. Use the optional `features.ai.image` configuration to enable image generation and editing, with the same option names as `unlayer.init()`. Omitting it preserves existing request behavior; older clients do not need any changes.
```json
{
"messages": [
{
"role": "user",
"content": [
{ "type": "text", "text": "Make image #1 black and white" },
{ "type": "image", "image": "https://your-cdn.example/portrait.png" }
]
}
],
"output": { "kind": "template", "displayMode": "email" },
"features": {
"ai": {
"image": { "generation": true, "editing": true, "upload": true }
}
},
"end_user_id": "customer-123"
}
```
Image numbers follow the order of image parts in the last user message. Include earlier messages to continue editing a previous result. Keep the conversation to at most ten messages and six image parts across those messages, including earlier assistant image results. Data URLs have a combined decoded limit of 10 MB. Each image operation also limits its downloaded or decoded source images to 10 MB in total. Public image URLs and PNG, JPEG, WebP, or GIF base64 data URLs are supported. A URL pasted in user text can also be selected as an edit source. The last user message must include text. Trim older history as the conversation grows.
| `features.ai.image` option | Behavior |
| ------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `enabled` | Set to `false` to disable image generation, editing, and image destinations. Defaults to `true` when the image configuration is supplied. |
| `generation` | Allow custom image generation. Defaults to `true`. |
| `editing` | Allow editing an existing image. Defaults to `true`. |
| `upload` | Allow image attachments as references, unchanged photos, or edit sources. Pasted-URL edits also require `editing`. Defaults to `true`. |
| `enableDesignImageTargeting` | Use existing images and resolve replacement or insertion destinations from `context.fullDesign`. Defaults to `true`. Set to `false` to keep image results separate from design destinations. |
| `model`, `quality`, `fallbackModels` | Configure image providers independently of the top-level conversation `model`. See the image options above. |
`features.ai.image: {}` enables the default image actions. Every option is optional. To target an existing template image, supply `context.fullDesign`; use `context.selection` to identify a selected image, or describe the image in the prompt. Without a full design, the assistant can still generate images and edit attachments. Requests for several images can return several independent results. Existing design permissions still apply.
Online image search is supported in the editor, but is not available through this public endpoint. Omit `search` or set it to `false`; explicitly requesting `search: true` returns `400`. `safeSearch` only affects editor stock search. Automatic alt-text configuration (`altText`) belongs to the editor, which applies images to the design; API integrations supply alt text when applying results.
### Combine HTML references and images
The existing `POST /v3/templates/generate` endpoint accepts HTML as an inline `file` part in a user message. Include images and the actual instruction in that same message:
```javascript
const request = {
output: { kind: 'template', displayMode: 'email' },
end_user_id: 'customer-123',
context: { fullDesign: savedDesign },
features: {
ai: { image: { upload: true, generation: false, editing: false } },
},
messages: [
{
role: 'user',
content: [
{
type: 'file',
file: {
mediaType: 'text/html',
name: 'inspiration.html',
text: htmlSource,
},
},
{ type: 'image', image: 'https://your-cdn.example/product.jpg' },
{
type: 'text',
text: 'Borrow the colors from this HTML, keep my copy, and use image #1 as the hero.',
},
],
},
],
};
```
`htmlSource` is the HTML string; `savedDesign` is the current Unlayer design. Omit the design when creating a new template. HTML attachments require full-template AI Assistant access. The instruction determines whether the HTML is inspiration or a template to recreate; attachment presence alone is not a replacement request. Existing design permissions apply.
The `file` object requires `mediaType: 'text/html'` and non-empty `text`; `name` is optional and limited to 255 characters. Do not combine `text` and `url` in one file part. This addition is optional and leaves existing text/image request bodies unchanged. Remote HTML file URLs are not fetched through this attachment contract.
Current and retained user messages together accept at most three HTML references totaling 5 MiB of UTF-8 source. Include the earlier file parts on follow-up requests when they are still relevant, removing older references to stay within the limit. Current sources and the design must also fit the Assistant’s combined context limit after HTML cleanup. Older retained HTML that does not fit or cannot be prepared is omitted so it cannot block an unrelated follow-up. Invalid attachments return a validation error before generation.
Embedded image data and inline photo references used with HTML (or with `editing: false`) are hosted by the existing project-storage service before generation; ordinary image URLs are reused. Scripts and nonvisual markup are removed, and reference markup is treated as data rather than instructions. Source text and filenames are excluded from prompt tracking. These turns use normal Assistant credits, including any separately requested generative image operations. Placing an uploaded photo unchanged does not call an image generation model; the conversation itself still consumes credits.
For unchanged photos, accepted design edits appear directly in `output.data`. The separate `images` array below is for generated, edited, or searched image results.
### Target an image in a design
Pass the full saved design and, when the user selected an image, its authored content ID:
```javascript
const response = await fetch('https://api.unlayer.com/v3/templates/generate', {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.UNLAYER_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
messages: [
{
role: 'user',
content: [
{ type: 'text', text: 'Make the selected image black and white' },
],
},
],
output: { kind: 'content', displayMode: 'email' },
features: {
ai: { image: { generation: false, editing: true } },
},
context: {
fullDesign: savedDesign,
selection: { collection: 'contents', id: 'hero-image' },
},
end_user_id: 'customer-123',
}),
});
// A 304 means no changes and has no JSON body.
if (response.status !== 304) {
const result = await response.json();
const partial = !response.ok;
if (partial && !result.images?.length) {
throw new Error(`Image edit failed: ${response.status}`);
}
// Store result.images and apply their destinations, including partial results.
// When partial is true, also show result.message so the user sees the failure.
}
```
Run this code on your backend. `savedDesign` is your full Unlayer design JSON, and `hero-image` must match the image block's `id`, not an internal editor index. To target by description without a selection, omit `selection`, use `output.kind: 'template'`, and ask for the relevant image or insertion location in the prompt. Set `enableDesignImageTargeting: false` to use only attachments and prior results as image references, without automatic design destinations.
### Handle results and follow-up turns
Image results are returned in an optional top-level `images` array, alongside the existing `output`, `model`, and `usage` fields:
```json
{
"images": [
{
"id": "result-1",
"url": "https://assets.example/edited-image.png",
"source": "edited",
"destination": {
"kind": "replace",
"imageId": "hero-image",
"expectedSrc": "https://your-cdn.example/portrait.png"
}
}
]
}
```
`output.data` contains design changes; it does not automatically incorporate the returned images. Store each image on your CDN within seven days, then apply its optional `destination` to your current design. For a replacement, check that the image identified by `imageId` still has `expectedSrc` before changing it. An insertion identifies a `parentId` with `position` (`start`, `end`, `before`, or `after`) and an `anchorId` for relative positions. Images without a destination are previews for your application to present. For an insertion, `parentId` is an authored template body or column ID; `anchorId` is the sibling ID used by `before`/`after`. Recheck that destinations still exist and permissions still allow the operation before applying an asynchronous result. Supply content-based alt text when adding or changing an image.
When image work completes without a design change, the API returns `200` with the completed `images` and `usage`, and may omit `id`, `model` and `output`. Keep your current design when `output` is absent. A `304` has no body and is used only when there is no image work to report.
To continue an edit, append the returned image URL as an `image` part in an `assistant` message, followed by the next user instruction. Include any useful assistant reply text. Keep those URLs valid for the next request; use your stored copies after temporary URLs expire.
If the conversation fails after an image completes, the non-2xx response retains optional `images` and `usage` alongside its usual error fields. Read the JSON body before handling the error. Keep completed images and report the failure; do not automatically retry the whole request, which can generate and charge for them again. A provider response that consumes credits without producing an image can still contribute to `usage`. Network disconnects cannot deliver a response, so avoid long synchronous bulk requests when your client or proxy has a short timeout.
For a pure black-and-white request, the conversation can apply a grayscale conversion that preserves dimensions and transparency without an image-generation charge. Conversation and automatic image-description usage still apply.
`usage.aiCreditsUsed` includes both the conversation and image operations. Image generation and editing are recorded separately in usage reporting, attributed to the same `end_user_id`; adding their credits to the response does not charge them again. Token fields describe the conversation model, and raw provider costs are not exposed by the public API.
Authentication, AI access, and credit limits are the same as for design generation. Use `POST /v3/templates/import` to reconstruct a design from an existing screenshot; attaching an image here does not import its layout.
---
## Inbox Previews API
Use the Cloud API to manage a project's Inbox Previews defaults from your backend. Keep your API key server-side and see [Authentication](/server/authentication) before making requests.
An editor's [`features.inboxPreviews` init config](/builder/latest/email-builder/inbox-previews#override-the-project-defaults) can override these defaults for that editor instance.
## Read the defaults
```http
GET /v3/projects/:id
```
The response includes `data.inboxPreviews`. A `null` value means the recommended email clients or automatic data region is active.
## Update the defaults
```bash
curl --request PATCH 'https://api.unlayer.com/v3/projects/1234' \
--header 'Authorization: Bearer unlayer_sk_...' \
--header 'Content-Type: application/json' \
--data '{
"inboxPreviews": {
"clients": ["outlook19", "iphone16gmail_26"],
"dataRegion": "eu"
}
}'
```
| Field | Value |
| ------------ | ---------------------------------------------------------------------- |
| `clients` | A non-empty list of current IDs, or `null` to use the recommended set. |
| `dataRegion` | `us`, `eu`, or `null` to choose automatically from the project region. |
Both fields are optional. Omitted fields stay unchanged. Unknown client IDs return `400 VALIDATION_ERROR` without changing the project.
Paid plans accept up to 20 email clients in one run. Free plans accept up to three when Inbox Previews is explicitly enabled. Customer Success can configure an account-specific exception, but the platform never accepts more than 20. This per-run limit is separate from the billing-period allowance. A larger selection returns `400 VALIDATION_ERROR` without changing the project.
Automatic region selection follows the project's custom storage region when available, then its asset region. It never guesses from a user's location. A region change affects future runs only; existing previews stay in their original region.
See the [API reference](/server/cloud-api/reference) for the full request and response schemas.
## Read usage
Credits are shared by the whole workspace; these endpoints report one project's share.
```http
GET /v3/projects/:id/inbox-previews/usage?start=2026-08-01&end=2026-08-31
```
Returns the project's generations, credits, daily trend, usage by email client, and usage by end
user. Dates are inclusive, up to 366 days, and default to the last 30 days. Page the end-user list
with `limit` (default and maximum 100) and `offset` (up to 100,000). Add `end_user_id=customer-123`
to scope everything to one end user; send the same ID you gave the editor.
Two billing models can appear in one period, and `total_credits` combines them:
- **Per device** (current): one credit per selected email client. Broken down in
`per_device_credits`; `email_clients` and `end_users` cover these runs only.
- **Per generation** (previous model): one credit per accepted LIVE generation, none for TEST.
Broken down in `per_generation_credits`. Rows recorded before generation-level reporting are
counted in `per_generation_credit_details_unavailable` rather than shown as zero.
`total_device_credits` and the daily `device_credits` are kept as aliases for the per-device part.
```http
GET /v3/projects/:id/inbox-previews/usage/runs?start=2026-08-01&end=2026-08-31
```
Lists individual generations with the same filters, 25 per page by default.
| Field | Per-device run | Per-generation run |
| ------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------- |
| `billing_model` | `per-device` | `per-generation` |
| `credits_used`, `credit_details_available` | Credits charged | Credits charged, or unavailable for old rows |
| `clients` | The selected email clients | The clients the provider reported |
| `viewed_clients`, `automatically_viewed_clients`, `interactively_viewed_clients`, `click_viewed_clients`, `navigation_viewed_clients` | Which were viewed and how (auto, any interaction, thumbnail click, previous/next controls), or `null` without view tracking | `null` |
| `end_user_id`, `template_id`, `data_region` | When known | `null` |
| `configuration_source` | `editor`, `console`, `api`, `project`, or `recommended` | `previous-billing-model` |
Provider details and internal costs are never exposed. The project's **Usage** page in Console shows
the same data with the same filters, plus a CSV export of whatever the page shows.
## Remove end-user attribution
To fulfill an end-user erasure request without changing the project's billing totals:
```http
DELETE /v3/projects/:id/inbox-previews/usage/end-users
Content-Type: application/json
{"end_user_id":"customer-123"}
```
Send the same source ID that was supplied to the editor; whitespace and long IDs are normalized the same way as generation. This permanently removes the stored ID from matching usage rows. Generation and device-credit totals remain unchanged. End-user attribution is also removed automatically after 13 months.
## Email-client IDs
The catalog changes as email clients and devices evolve. Use this live list when setting `clients`:
You can also fetch the catalog directly:
---
## Cloud API
The Cloud API is the **server-side** interface to Unlayer. It runs outside the browser and lets your backend:
- **Send transactional email** from your own verified domains, with delivery tracking, webhooks, and suppression handling
- **Generate artifacts** (HTML, PDF, Image, ZIP) from a design JSON
- **[Generate or edit images with AI](./images.md)**, either directly or within an Assistant conversation
- **Manage templates** stored in your Unlayer project
- **[List blocks](/server/cloud-api/blocks)** — shared and end-user saved — for backup and usage reporting
- **Convert** designs between [Full and Simple schema forms](/design-schema/)
- **Validate** a design against the Unlayer schema
- **Execute secure operations** that should not run in the browser
**[View the full API reference →](/server/cloud-api/reference)**
---
## When to use the Cloud API
Reach for the Cloud API when:
- You want to **send transactional email** (welcome, receipts, password resets) from your own domain without running your own SMTP/ESP integration
- You need to **generate a PDF** from a design in a background job
- You want to **export HTML** without exposing API keys to the browser
- You want to **generate an image preview** server-side
- You are running a **cron job**, webhook handler, or worker process
- You need to **validate or convert** a design payload before storing or rendering it
:::tip Embedding the builder?
If your use case involves embedding a visual builder or editor in your frontend, see [Builders](/builder/installation) instead.
:::
---
## How it works
Most server workflows follow this pattern:

1. A **Builder** produces a design JSON (in the browser).
2. Your **backend** sends that JSON to the [Cloud API](/server/cloud-api/reference).
3. The API returns a **generated artifact** (HTML, PDF, Image, ZIP) — or a validated / converted design payload.
4. You **store**, **send**, or **distribute** the result.
:::info Exporting HTML
For **HTML export**, you often don't need the Cloud API — the builder can produce HTML directly in the browser via [`unlayer.exportHtml()`](/builder/export-html). Use the Cloud API when you need to export HTML server-side (for example, in a background job or when the user is not in the builder). Server-rendered exports count toward your plan's [export allowance](/server/cloud-api/export-allowances); browser HTML exports do not.
:::
---
## Sending email
Send transactional email from a verified domain using raw HTML or a saved template.
Email Sending is in private beta and requires workspace access.
Use `POST /v3/emails` for HTML or `POST /v3/emails/template` for a template. A new
accepted send returns `202` and an email ID. Track delivery with webhooks or the
email detail endpoint, and use an `Idempotency-Key` when retrying a request.
See the [Email Sending guide](/server/email-sending) for authentication, domain
verification, limits, and complete examples.
---
## Security model
The Cloud API uses **bearer-token authentication** — API Key, Personal Access Token, or OAuth. See **[Authentication](/server/authentication)** for token types, how to get each one from Console, and security guidelines.
### Traffic protection
Infrastructure protection is separate from your plan's usage allowance. When
enabled, protected server-side operations (exports and rendering, AI generation,
and template, block and other reads and writes) share their workspace's capacity
across projects and credentials. Each kind of work has its own capacity, so heavy
exports do not slow down routine reads. Test projects also use this capacity.
An exhausted capacity bucket returns HTTP `429` with error code
`INFRASTRUCTURE_RATE_LIMITED` and a `Retry-After` header in seconds. Wait at least
that long before retrying, spread retries out, and reduce concurrent requests.
Do not automatically replay a write unless the operation supports safe retries.
Changing credentials does not create another allowance.
Rejected operations do not start the expensive work or consume usage credits.
An operation that is too large to fit the configured capacity returns HTTP `400`
with `OPERATION_TOO_LARGE`; reduce its batch size instead of retrying it unchanged.
Browser-local HTML export does not call the server and is unaffected.
:::warning Keep tokens server-side
Tokens grant full access to your project's data:
- **Never** call the Cloud API directly from the browser
- **Always** proxy requests through your backend
- **Keep** tokens in secure server-side environments only
:::
---
## Typical use cases
| Use case | Description |
| ----------------------------------- | ----------------------------------------------------------------------------------------------------- |
| **Send transactional email** | Deliver receipts, password resets, and notifications from your verified domain via `POST /v3/emails`. |
| **Export PDF in background job** | Generate a PDF after a user submits a form, then email it automatically. |
| **Generate HTML for email sending** | Export HTML server-side and send it via the Send API — or pass it to your own email provider. |
| **Image thumbnail generation** | Generate preview images for templates or documents. |
| **ZIP export for asset bundles** | Produce downloadable packages including images and required assets. |
| **Validate user-supplied designs** | Check that an imported or uploaded design conforms to the schema. |
| **Convert between schema forms** | Round-trip designs between the editor's Full shape and the wire Simple shape. |
---
## What's next
- See the [**API reference**](/server/cloud-api/reference) for the full endpoint list.
- See [**Design Schema**](/design-schema/) for the shape of the design JSON the API accepts and returns.
- If you're embedding the builder, go to [Builders](/builder/installation).
---
## Deliverability & settings
Send only mail your recipients expect. Unlayer automatically suppresses addresses that
hard-bounce or generate a spam complaint. This protection cannot be disabled.
---
## Project email settings
Read the current configuration:
```bash
curl https://api.unlayer.com/v3/emails/settings \
-H "Authorization: Bearer unlayer_sk_xxx"
```
Update any subset of fields with `PATCH`:
```bash
curl -X PATCH https://api.unlayer.com/v3/emails/settings \
-H "Authorization: Bearer unlayer_sk_xxx" \
-H "Content-Type: application/json" \
-d '{ "defaultFromName": "Acme" }'
```
### Settings reference
| Field | Type | Notes |
| ----------------- | ------ | -------------------------------------- |
| `defaultFromName` | string | Default sender display name (max 255). |
`defaultFromName` and display names in `from` cannot contain carriage returns, line feeds,
`<`, `>`, `"`, or `\`. Invalid names return `400`.
---
## Suppression list
Future sends to a suppressed address are rejected with `400` before they are queued. Hard
bounces and complaints are always added automatically; you can also manage entries manually.
### List suppressed addresses
Console **Settings → Suppression List** includes **Load more suppressions** when
additional entries are available.
Cursor-paginated (`limit` 1–200):
```bash
curl "https://api.unlayer.com/v3/emails/suppressions?limit=100" \
-H "Authorization: Bearer unlayer_sk_xxx"
```
```json
{
"data": [
{
"email": "bounced@example.com",
"reason": "hard_bounce",
"createdAt": "2026-06-18T12:00:00.000Z"
}
],
"has_more": false,
"next_cursor": null
}
```
`reason` is one of `hard_bounce`, `complaint`, or `manual`.
Hard-bounce suppressions expire automatically after 90 days unless you remove them earlier.
Complaint suppressions do not expire automatically and cannot be removed
through the API. Manually added suppressions remain until you remove them.
### Check one address
```bash
curl "https://api.unlayer.com/v3/emails/suppressions/check?email=user@example.com" \
-H "Authorization: Bearer unlayer_sk_xxx"
```
### Add an address manually
```bash
curl -X POST https://api.unlayer.com/v3/emails/suppressions \
-H "Authorization: Bearer unlayer_sk_xxx" \
-H "Content-Type: application/json" \
-d '{ "email": "user@example.com", "reason": "manual" }'
```
### Remove an address
So it can receive mail again:
```bash
curl -X DELETE "https://api.unlayer.com/v3/emails/suppressions?email=user@example.com" \
-H "Authorization: Bearer unlayer_sk_xxx"
```
Only `manual` and `hard_bounce` entries can be removed. Complaint suppressions are
protected and return `403 Forbidden`; a recipient's spam complaint must be honored.
Suppressions are scoped **per project**.
---
## Sender reputation
Suppression helps reduce repeat bounces and complaints, but it does not guarantee inbox
placement. Send relevant messages to recipients who expect them, and monitor your bounce
and complaint rates through [webhooks and statistics](/server/email-sending/webhooks).
---
## Email Sending
Send transactional emails such as receipts, password resets, and account notifications
from your application using Unlayer's v3 Cloud API. Use raw HTML or a saved template,
send from a verified domain, and track delivery with webhooks.
:::note Private beta
Email Sending requires beta access. [Contact us](https://unlayer.com/contact) to request
access for your workspace. Requests to Send endpoints require this access in addition
to the endpoint's authentication and permissions.
:::
## Get started
1. [Verify a sender domain](/server/email-sending/sender-domains).
2. Create a [Project API Key](/server/authentication) in Console.
3. Send an email:
```bash
curl -X POST https://api.unlayer.com/v3/emails \
-H "Authorization: Bearer unlayer_sk_xxx" \
-H "Content-Type: application/json" \
-d '{
"from": "Acme ",
"to": ["customer@example.com"],
"subject": "Welcome to Acme 👋",
"html": "Hello!Thanks for signing up."
}'
```
A successful new send returns `202 Accepted` with an email `id` and `status: "queued"`.
This confirms acceptance, not delivery. Use [webhooks](/server/email-sending/webhooks)
or `GET /v3/emails/{id}` to follow its progress.
## Authentication
Use `https://api.unlayer.com/v3` as the base URL. Sending, history, settings,
suppressions, statistics, and webhooks accept a Bearer Project API Key (`unlayer_sk_`).
The key identifies the project; you do not need a `projectId` parameter.
[Sender-domain management](/server/email-sending/sender-domains) requires an owner/admin
Personal Access Token (`unlayer_pat_`) and project context because domains are shared
by a workspace.
Keep tokens on your server. Do not include them in browser or mobile application code.
See [Authentication](/server/authentication) for details.
## Data retention
| Data | Retention |
| --------------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
| Email details and event timelines | 90 days after acceptance |
| Aggregate statistics | Available in 7-day, 30-day, or 90-day query windows |
| Email content and attachments | Removed after processing where possible; retained queued or failed payloads become eligible for deletion after 30 days |
| Hard-bounce suppressions | 90 days, unless removed earlier |
| Complaint suppressions | No automatic expiration; cannot be removed through the API |
| Manual suppressions | Until removed |
Deletion is asynchronous. Do not rely on history remaining available beyond 90 days.
For a longer audit trail, [verify and store webhook events](/server/email-sending/webhooks#keep-a-longer-history).
## Guides
- [Sender domains](/server/email-sending/sender-domains): register a domain and configure DNS.
- [Sending emails](/server/email-sending/sending-emails): HTML, templates, attachments, retries, and credits.
- [Deliverability and settings](/server/email-sending/deliverability): sender names and suppression management.
- [Webhooks and events](/server/email-sending/webhooks): delivery updates, signatures, and statistics.
- [API reference](/server/cloud-api/reference): endpoint fields and responses.
---
## Sender domains
Verify a domain before sending from it. Verification confirms your workspace controls
the domain and sets up DKIM signing to authenticate your emails.
Domain management requires a **Personal Access Token** (`unlayer_pat_*`) belonging to a
workspace owner or admin. Because a PAT is not bound to a project, pass a project in that
workspace with `X-Project-Id` on every domain request. Project API keys can send mail but cannot
inspect or change workspace-shared sender domains.
:::tip Use a subdomain
Send from a dedicated subdomain like `mail.example.com` instead of your root domain. It
keeps your transactional reputation separate from the rest of your mail.
:::
## 1. Register the domain
```bash
curl -X POST https://api.unlayer.com/v3/domains \
-H "Authorization: Bearer unlayer_pat_xxx" \
-H "X-Project-Id: 12345" \
-H "Content-Type: application/json" \
-d '{ "domain": "mail.example.com" }'
```
The response returns the workspace domain `id`, an ownership challenge, and the
DKIM tokens. To get the **complete** set of DNS records to publish, fetch the domain detail
(next step).
If registration returns a `5xx`, list your domains before retrying. If the domain is
already listed, inspect its status and DNS records. Contact support if it cannot be verified.
If a previously registered domain returns a conflict because provider verification failed,
contact Unlayer support to restart verification.
## 2. Publish the DNS records
Fetch the domain to get both required record types: a workspace-specific ownership `TXT`
record and the SES DKIM `CNAME` records:
```bash
curl https://api.unlayer.com/v3/domains/42 \
-H "Authorization: Bearer unlayer_pat_xxx" \
-H "X-Project-Id: 12345"
```
```json
{
"data": {
"id": 42,
"domain": "mail.example.com",
"status": "pending",
"dkimTokens": ["abc123", "def456", "ghi789"],
"dnsRecords": [
{
"type": "TXT",
"name": "_unlayer-verification.mail.example.com",
"value": "6d4474...workspace-specific-token",
"purpose": "Unlayer ownership"
},
{
"type": "CNAME",
"name": "abc123._domainkey.mail.example.com",
"value": "abc123.dkim.amazonses.com",
"purpose": "DKIM"
},
{
"type": "CNAME",
"name": "def456._domainkey.mail.example.com",
"value": "def456.dkim.amazonses.com",
"purpose": "DKIM"
},
{
"type": "CNAME",
"name": "ghi789._domainkey.mail.example.com",
"value": "ghi789.dkim.amazonses.com",
"purpose": "DKIM"
}
],
"createdAt": "2026-06-18T12:00:00.000Z"
}
}
```
Add every `dnsRecords` entry (one ownership `TXT` and the DKIM `CNAME`s) at your DNS provider
exactly as returned. On Cloudflare, set CNAMEs to **DNS only** (grey cloud), not Proxied.
Propagation usually takes minutes, sometimes a few hours.
In Console, **Settings → Domains** displays this same complete record set. Its **Copy All**
action includes the ownership TXT record and every DKIM CNAME.
:::note Both checks are required
The TXT challenge proves that this Unlayer workspace controls the domain. DKIM authenticates
mail sent through SES. The domain becomes verified only after both checks succeed. SPF and
DMARC remain optional hardening (see below).
:::
### SPF and DMARC
Publish the DNS records returned by Unlayer. You do not need to change your existing
SPF record for this setup: the default sending configuration handles SPF, and DKIM
provides authentication aligned with your sender domain.
DMARC is optional for Unlayer verification. If you add it, start with `p=none` to monitor
your mail before choosing a stricter policy. Existing DMARC policies affect all mail
using the domain, so check other sending services before making changes.
## 3. Verify
Once the records propagate, check verification:
```bash
curl -X POST https://api.unlayer.com/v3/domains/42/verify \
-H "Authorization: Bearer unlayer_pat_xxx" \
-H "X-Project-Id: 12345"
```
```json
{
"data": {
"id": 42,
"domain": "mail.example.com",
"status": "verified",
"ownership": { "verified": true },
"dkim": { "status": "SUCCESS", "tokens": ["abc123", "def456"] }
}
}
```
The Console's **Verify** action reports whether verification succeeded, remains pending, or
failed. A pending result means the ownership TXT or at least one DKIM record has not propagated.
When `status` is `verified`, you can send from any address on that domain (for example,
`hello@mail.example.com`).
If the status becomes `failed`, check the DNS records and contact Unlayer support to restart
verification.
Verified domains are available to every project in their workspace. A domain can be
verified for only one workspace at a time; a conflicting verification returns `409`.
## Manage domains
List every registered domain and its status:
```bash
curl https://api.unlayer.com/v3/domains \
-H "Authorization: Bearer unlayer_pat_xxx" \
-H "X-Project-Id: 12345"
```
### Remove a domain
```bash
curl -X DELETE https://api.unlayer.com/v3/domains/42 \
-H "Authorization: Bearer unlayer_pat_xxx" \
-H "X-Project-Id: 12345"
```
After removal, projects in the workspace can no longer send from the domain.
### Verification statuses
| `status` | Meaning |
| ---------- | ----------------------------------------------------------------------------- |
| `pending` | Ownership TXT or DKIM is not yet confirmed. Publish all records, then verify. |
| `verified` | Workspace ownership and DKIM are confirmed. You can send from this domain. |
| `failed` | SES stopped the DKIM attempt. Contact Unlayer support to restart it. |
## Next
Domain verified? Head to [Sending emails](/server/email-sending/sending-emails).
---
## Sending emails
Two endpoints send mail. One takes **raw HTML**; the other renders a **stored template**.
Both queue the message and return `202 Accepted` with an email `id`.
## Send raw HTML
```bash
curl -X POST https://api.unlayer.com/v3/emails \
-H "Authorization: Bearer unlayer_sk_xxx" \
-H "Content-Type: application/json" \
-d '{
"from": "Acme ",
"to": ["customer@example.com"],
"subject": "Your receipt",
"html": "Thanks!Your order shipped.",
"text": "Thanks! Your order shipped."
}'
```
### Request fields
| Field | Type | Notes |
| ---------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `from` _(required)_ | string | Sender address or `Name `. The domain must be [verified](/server/email-sending/sender-domains). |
| `subject` _(required)_ | string | Max 998 chars. |
| `html` _(required)_ | string | HTML body. |
| `to` _(required)_ | string[] | Exactly one recipient. Send one request per independently tracked delivery. |
| `text` | string | Plain-text alternative. Sends `multipart/alternative` when present. |
| `replyTo` | string | Reply-To address. |
| `tags` | object | Key–value string labels for categorizing the email. See [Tags](#tags). |
| `headers` | object | Up to 9 printable-ASCII `X-*` headers. Names are at most 126 characters; values at most 995; name plus value at most 996. Unlayer and `X-SES-*` names are reserved. |
| `attachments` | array | Up to 10 files, 5 MB total. See [Attachments](#attachments). |
### Response
```json
{
"data": {
"id": "9b2c2f4e-7e3a-4f1d-9a8b-1c2d3e4f5a6b",
"from": "Acme ",
"to": ["customer@example.com"],
"subject": "Your receipt",
"status": "queued",
"createdAt": "2026-06-18T12:00:00.000Z"
}
}
```
`202` means _queued_, not delivered. Track progress with
[webhooks](/server/email-sending/webhooks) or by [polling the email](#check-delivery-status).
## Send from a stored template
Render a template you saved in the editor (it must have been saved at least once so it has
rendered HTML). The subject, the plain-text part, and the body all support `{{variable}}`
merge syntax, filled from `variables`.
```bash
curl -X POST https://api.unlayer.com/v3/emails/template \
-H "Authorization: Bearer unlayer_sk_xxx" \
-H "Content-Type: application/json" \
-d '{
"from": "Acme ",
"templateId": "12345",
"to": ["customer@example.com"],
"subject": "Welcome, {{firstName}}",
"variables": { "firstName": "Sam", "plan": "Pro" }
}'
```
`from`, `to`, and `templateId` are required. If you omit `subject` it falls back to the
template name. The same one-recipient, `replyTo`, and `attachments` rules apply. CC and BCC
are not supported by either send endpoint.
The email uses the template as it was when the request was accepted. Later edits or deletion
do not change an already queued email.
## Tags
Tags label an email for filtering (`GET /v3/emails?tag=campaign=welcome`). Up to 10 tags per
email. Keys and values may only contain **letters,
numbers, underscores, and hyphens** (`A–Z a–z 0–9 _ -`). Keys are 1–64 characters; values up to 256 characters. Anything outside that
charset (spaces included) is rejected with `400` at acceptance:
```json
{ "tags": { "campaign": "welcome", "order_id": "5512-A" } }
```
## Attachments
Each attachment is base64-encoded inline:
```json
{
"attachments": [
{
"filename": "receipt.pdf",
"content": "JVBERi0xLjQKJ...",
"contentType": "application/pdf"
}
]
}
```
All three fields are required — `filename`, `content`, and `contentType`. An attachment
without a `contentType` is rejected with `400`.
Limits: up to 10 files and a 5 MB decoded email payload. The limit is the sum of UTF-8 HTML,
UTF-8 plain text (when supplied), and decoded attachment bytes. Base64 transport overhead and
HTTP headers do not count. Whitespace and standard MIME line wrapping in `content` are removed
before validation. `contentType` must be an allowed MIME type.
## Idempotent sends
Use an `Idempotency-Key` when retrying a send. Repeating the same key and request within
24 hours returns the same accepted email ID instead of accepting another email. The returned
status may reflect delivery updates since the original request:
```bash
curl -X POST https://api.unlayer.com/v3/emails \
-H "Authorization: Bearer unlayer_sk_xxx" \
-H "Idempotency-Key: order-5512-receipt" \
-H "Content-Type: application/json" \
-d '{ "from": "...", "to": ["..."], "subject": "...", "html": "..." }'
```
If the first request is still in flight, the retry gets `409`. Reusing the key with a
different request also gets `409`; use a new key for new work. Idempotency is checked before
quota is reserved, so rejected duplicate requests do not consume another daily slot.
Idempotency prevents duplicate acceptance, but delivery cannot be guaranteed exactly once.
If a provider accepts a message and its response is lost, a delivery retry can produce a duplicate.
For template sends, retry with the same template ID, variables, and other request fields.
Editing or deleting the template after acceptance does not change the accepted email or
create another send.
## Preview without sending
Render a template to HTML without sending it. Handy for previews and tests.
```bash
curl -X POST https://api.unlayer.com/v3/emails/render \
-H "Authorization: Bearer unlayer_sk_xxx" \
-H "Content-Type: application/json" \
-d '{ "templateId": "12345", "variables": { "firstName": "Sam" } }'
```
```json
{ "data": { "html": "...", "subject": "Welcome email" } }
```
The preview uses the template's current saved HTML.
## Check delivery status
The `202` only means _queued_. Fetch the current status during the rolling 90-day history
window:
```bash
curl https://api.unlayer.com/v3/emails/9b2c2f4e-7e3a-4f1d-9a8b-1c2d3e4f5a6b \
-H "Authorization: Bearer unlayer_sk_xxx"
```
```json
{
"data": {
"id": "9b2c2f4e-7e3a-4f1d-9a8b-1c2d3e4f5a6b",
"from": "Acme ",
"to": ["customer@example.com"],
"subject": "Your receipt",
"status": "delivered",
"failureReason": null,
"tags": null,
"createdAt": "2026-06-18T12:00:00.000Z"
}
}
```
`status` moves from `queued` to `sent` to `delivered`, or ends at a failure state:
`bounced`, `complained`, or `failed`. When a send fails, `failureReason` tells
you why (for example, an unverified sender domain) so you can fix it without guessing.
If repeated provider or network errors exhaust the delivery retry budget, the send becomes
`failed` with an unconfirmed-delivery reason instead of remaining `queued` indefinitely. A late
provider event can still advance that record if the provider accepted an earlier ambiguous attempt.
:::tip Push instead of poll
For real-time updates, register a [webhook](/server/email-sending/webhooks) rather than
polling.
:::
## List and inspect emails
In Console, open **Sending → Delivery History** and use **Load older emails** to
browse beyond the first page. Select a delivery to view its status and event timeline.
List sent emails, newest first, with optional filters and cursor pagination:
```bash
curl "https://api.unlayer.com/v3/emails?status=bounced&limit=20" \
-H "Authorization: Bearer unlayer_sk_xxx"
```
| Query param | Purpose |
| ------------- | ---------------------------------------------------------------------------------------------------------------- |
| `status` | `queued`, `sending`, `sent`, `delivered`, `bounced`, `complained`, `failed` |
| `search` | Match recipient or subject |
| `tag` | Filter by a tag in `key=value` form (e.g. `campaign=welcome`) |
| `from` / `to` | ISO date range. Uses acceptance time normally, or the matching status-transition time when `status` is supplied. |
| `limit` | 1–100 (default 20) |
| `cursor` | `next_cursor` from the previous page |
To see one email's full history, fetch its event timeline:
```bash
curl https://api.unlayer.com/v3/emails/9b2c2f4e-.../events \
-H "Authorization: Bearer unlayer_sk_xxx"
```
```json
{
"data": [
{
"type": "send",
"timestamp": "2026-06-18T12:00:00.000Z",
"metadata": null
},
{
"type": "delivery",
"timestamp": "2026-06-18T12:00:03.000Z",
"metadata": null
}
]
}
```
Timeline event types are `accepted`, `send`, `delivery`, `bounce`, `complaint`, and
`failed`. Entries are returned in timestamp order; provider events can arrive late.
Email details and their event timelines are available for 90 days after the email is
accepted. After that window, detail and event requests may return `404`. Store verified
[webhook events](/server/email-sending/webhooks#keep-a-longer-history) if you need a longer
audit trail.
## Testing
Amazon SES provides simulator mailboxes that produce a given outcome without touching real
inboxes or your reputation. Send to these to exercise the whole pipeline safely:
| Recipient | Result |
| ----------------------------------- | ----------------------------- |
| `success@simulator.amazonses.com` | Delivered |
| `bounce@simulator.amazonses.com` | Hard bounce (auto-suppressed) |
| `complaint@simulator.amazonses.com` | Complaint |
A bounce or complaint here flows through exactly like a real one, so it's the easiest way to
verify your [suppression](/server/email-sending/deliverability#suppression-list) and
[webhook](/server/email-sending/webhooks) handling.
## Compose template values
Console keeps the same retry key for an unchanged Compose request in the same browser tab,
including after a reload when session storage is available. Within the 24-hour idempotency
window, retrying an accepted request returns the original email even if its saved template
has changed. Changing the compose fields starts a new send attempt.
In Console, **Compose** provides an input for each `{{variable}}` in the template and
subject. Fill in every required value before sending. Values are escaped in HTML and
inserted as plain text in the subject.
## Transactional email
Send supports transactional messages such as password resets, receipts, and requested
account activity. Both endpoints use the same delivery and suppression rules. There is
no message-purpose selector or built-in unsubscribe flow. Hard bounces, complaints,
and manual suppressions block delivery within the project.
## Quotas and credits
Each accepted single-recipient email consumes one credit, even if delivery later fails.
Retrying the same accepted request with its idempotency key does not consume another credit.
Your workspace has a monthly allowance and a daily limit, shared by its projects.
The daily limit resets at 00:00 UTC.
View your allowance and available **Email Credits** packs in Console **Billing**.
Packs increase both monthly and daily capacity. You can reduce a pack only when the
remaining monthly allowance covers credits already used in the current period.
If Send access is disabled, you can remove an existing pack even when prior usage
exceeds the remaining allowance.
If a purchase is interrupted, refresh Billing to check whether it completed before retrying.
Successful responses include `X-Credits-*` headers when quota information is available.
These headers are advisory and may be omitted; the response status and body tell you
whether your email was accepted.
| Response | `error` | Meaning |
| -------- | ---------------------- | ----------------------------------------- |
| `429` | `CREDITS_EXHAUSTED` | Monthly allowance exhausted. |
| `429` | `DAILY_LIMIT_EXCEEDED` | Daily limit reached; resets at 00:00 UTC. |
Statistics distinguish accepted, sent, and failed emails and may briefly lag behind sending.
A failed email with an unconfirmed delivery can later receive a provider confirmation, so
failed and sent counts can overlap. Use email details or webhooks to check an individual send.
---
## Webhooks & events
Webhooks send email status updates to your backend, so you don't have to poll
`GET /v3/emails/{id}`.
## Create a webhook
```bash
curl -X POST https://api.unlayer.com/v3/webhooks \
-H "Authorization: Bearer unlayer_sk_xxx" \
-H "Content-Type: application/json" \
-d '{
"url": "https://api.yourapp.com/hooks/unlayer",
"events": ["email.delivered", "email.bounced", "email.complained"]
}'
```
Leave `events` empty (or omit it) to receive everything. The response includes a signing
`secret`, shown **only this once**. Store it now; you can't read it back later, only
[rotate](#manage-webhooks) it.
```json
{
"data": {
"id": 7,
"url": "https://api.yourapp.com/hooks/unlayer",
"events": ["email.delivered", "email.bounced", "email.complained"],
"active": true,
"secret": "whsec_3f9a8b...store-me"
}
}
```
The URL must be HTTPS in production, and it can't point at a private or internal address.
A project can register up to five webhook URLs. Registering the same URL twice returns `409`.
## Event types
| Event | Fires when |
| ------------------ | -------------------------------------------------------- |
| `email.accepted` | Queued by Unlayer; one Email Credit consumed. |
| `email.failed` | Delivery failed or could not be confirmed after retries. |
| `email.sent` | Accepted by the sending provider. |
| `email.delivered` | Accepted by the recipient's mail server. |
| `email.bounced` | Delivery bounced, including exhausted soft bounces. |
| `email.complained` | Recipient marked the message as spam. |
## Event payload
Every event is a JSON `POST` with this shape:
```json
{
"schema_version": 1,
"id": "evt_8f3c2a1b9d4e5f6a7b8c9d0e1f2a3b4c",
"type": "email.delivered",
"data": {
"email_id": "9b2c2f4e-7e3a-4f1d-9a8b-1c2d3e4f5a6b",
"timestamp": "2026-06-18T12:00:03.000Z"
},
"created_at": "2026-06-18T12:00:04.000Z"
}
```
- `schema_version` identifies the webhook envelope contract. Additive fields may
appear without a version change; incompatible shape changes use a new version.
- `id` is a stable `evt_…` identifier (see [Duplicates](#duplicates-are-normal)).
- `type` is one of the events above.
- `data.email_id` matches the `id` from your send response.
- `data.timestamp` is when the event occurred. Acceptance and failed-send events originate
in Unlayer; delivery, bounce, and complaint events originate at the provider.
Each request also carries two headers: `X-Webhook-Signature` and `X-Webhook-Id`.
## Verify the signature
Always verify the signature before trusting a payload. It's the HMAC-SHA256 of the raw
request body, keyed with your webhook `secret` and hex-encoded, in `X-Webhook-Signature`:
```js
function verify(rawBody, signatureHeader, secret) {
const expected = createHmac('sha256', secret).update(rawBody).digest('hex');
const a = Buffer.from(expected);
const b = Buffer.from(signatureHeader || '');
return a.length === b.length && timingSafeEqual(a, b);
}
```
:::warning Sign the raw body
Compute the HMAC over the exact bytes you received, before any JSON parsing. Re-stringifying
the body changes those bytes and the signature won't match.
:::
## Duplicates are normal
The same event can arrive more than once. Every copy carries the same `id`, so dedupe on it
and keep your handler idempotent. Reply `2xx` quickly. Network failures, timeouts, `401`, `403`, `408`,
`429`, and `5xx` responses are retried with backoff; other `4xx` responses are treated as
permanent. A valid `Retry-After` response header is honored up to 15 minutes.
## Accepted and failed sends
`email.accepted` reports acceptance and credit consumption. `email.failed` reports a
failure before confirmed provider handoff, with `data.failure_reason` and `data.email_id`.
Their event IDs and timestamps stay the same across retries.
Events can arrive out of order. The stats endpoint includes `accepted` and `failed`
in both totals and daily rows, grouped by original acceptance date.
## Keep a longer history
Email details and event timelines are available from the API for 90 days after an email is
accepted. If you need a longer audit trail, store each verified webhook event in your own
system after deduplicating it by `id`. Do not treat the email history endpoints as a
long-term archive.
## Manage webhooks
List your webhooks (secrets are never returned here):
```bash
curl https://api.unlayer.com/v3/webhooks \
-H "Authorization: Bearer unlayer_sk_xxx"
```
Get one, update it, or delete it:
```bash
# Update the URL, events, or active flag
curl -X PATCH https://api.unlayer.com/v3/webhooks/7 \
-H "Authorization: Bearer unlayer_sk_xxx" \
-H "Content-Type: application/json" \
-d '{ "active": false }'
# Delete it
curl -X DELETE https://api.unlayer.com/v3/webhooks/7 \
-H "Authorization: Bearer unlayer_sk_xxx"
```
### Rotate the signing secret
Prepare a fresh secret. The current secret keeps signing deliveries. The prepared
secret is returned just once:
```bash
curl -X POST https://api.unlayer.com/v3/webhooks/7/rotate-secret \
-H "Authorization: Bearer unlayer_sk_xxx"
```
```json
{
"data": {
"id": 7,
"secret": "whsec_7c1d4f...store-me",
"updatedAt": "2026-06-18T12:00:00.000Z"
}
}
```
Configure your receiver to accept signatures from both the current and prepared
secrets, then activate the prepared secret:
```bash
curl -X POST https://api.unlayer.com/v3/webhooks/7/activate-secret \
-H "Authorization: Bearer unlayer_sk_xxx" \
-H "Content-Type: application/json" \
-d '{ "secret": "whsec_PREPARED_SECRET" }'
```
Keep accepting the old secret briefly for HTTP requests already in flight. Activation
switches later delivery attempts, including retries, to the new secret. Preparing
another rotation replaces the pending secret without affecting current signing.
Activation of a superseded pending secret returns `409`. Console provides the same
prepare, update-receiver, and activate sequence.
Authentication failures (`401`/`403`) retry with bounded backoff. After six failed
attempts, automatic retries stop. Contact support after repairing the receiver to
request recovery of exhausted deliveries.
Deduplicate by event `id`: replay can deliver an event again, but never sends another
customer email.
## Aggregate stats
For dashboards, read rolled-up totals instead of counting events yourself:
```bash
curl "https://api.unlayer.com/v3/emails/stats?period=30d" \
-H "Authorization: Bearer unlayer_sk_xxx"
```
```json
{
"data": {
"period": "30d",
"accepted": 1210,
"failed": 10,
"sent": 1200,
"delivered": 1180,
"bounced": 12,
"complained": 1,
"deliveryRate": 98.33,
"bounceRate": 1
}
}
```
`period` accepts `7d`, `30d`, or `90d` (default `30d`). Add `groupBy=day` for a daily
breakdown you can chart. Events are grouped by the date the email was accepted, including
later deliveries, bounces, and complaints. Rates are percentages from `0` to `100`.
Statistics update asynchronously and may lag behind individual events. Use webhooks or
the email detail endpoint to follow a specific email.
## Next
That's the full flow. For field-by-field detail on every endpoint, see the
[API reference](/server/cloud-api/reference).
---
## AI Agents
AI agents that use your app, such as ChatGPT's agent or Claude in Chrome, can build and edit designs in the builder without dragging blocks. The builder gives them a JSON API: they read the design, change it, and load it back. Your users see the result on the canvas and can undo it like any other change.
This API works with the design in an open builder inside your app. For agents that work with templates outside your app through Unlayer's hosted MCP server, see [Unlayer MCP](../mcp/overview.md).
It's on by default, and you can [turn it off](#turn-it-off).
:::info Requirements
Builder version **1.519.0 or later**. Use `version: 'latest'` or pin a newer version. A builder loaded without a `version` uses the stable version, which doesn't include this yet.
:::
```javascript
unlayer.init({
id: 'editor',
version: 'latest',
});
```
## How agents use it
There are two ways in. Both do the same thing.
### WebMCP tools
Some agents can't run code in your page. They use [WebMCP](https://developer.chrome.com/docs/ai/webmcp), a browser feature that lets a page offer tools to agents. The builder registers these tools on your page:
| Tool | What it does |
| --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| `unlayer_describe_editor` | Explains how to edit the design and lists what this builder supports: content types, custom tools, merge tags and fonts. Agents call this first. |
| `unlayer_get_design_schema` | Returns the JSON Schema of the design, including your custom tools. |
| `unlayer_get_design` | Returns the current design. |
| `unlayer_load_design` | Checks a design and loads it if it's valid. |
| `unlayer_preview` | Opens the preview at a device size (`desktop`, `tablet` or `mobile`), or closes it with `none`. |
| `unlayer_export_html` | Exports the current design as HTML. |
WebMCP is new, so browser support is still limited:
- **Chrome and Edge** offer it through an origin trial. Register your own domain on the [Chrome Origin Trials](https://developer.chrome.com/origintrials) page (search for "WebMCP") or the [Edge origin trial](https://developer.microsoft.com/en-us/microsoft-edge/origin-trials/trials/0b76fe60-b266-458e-a285-04e375c0c31a), then add the token to your pages:
```html
```
To try it locally, turn on `chrome://flags/#enable-webmcp-testing` and restart Chrome.
- **Some agent browsers**, such as ChatGPT's, support WebMCP on their own.
- **Firefox and Safari** don't support it.
In a browser without WebMCP, the builder skips the tools. Nothing else changes.
### JavaScript: `unlayer.agent`
Agents that can run code in your page use `unlayer.agent` directly. It works in every browser.
```javascript
// 1. Learn how to edit designs in this builder.
const { guide, contentTypes, customTools } = await unlayer.agent.describe();
// 2. Read the current design.
const design = await unlayer.agent.getDesign();
// 3. Change the design JSON. This adds a row with a heading and a button.
// Every new block needs an id that isn't already in the design.
const newId = (name) => `${name}-${crypto.randomUUID().slice(0, 8)}`;
design.body.rows.push({
id: newId('sale-row'),
cells: [1],
columns: [
{
id: newId('sale-column'),
contents: [
{
id: newId('sale-heading'),
type: 'heading',
values: { headingType: 'h1', text: 'Fall sale: 20% off' },
},
{
id: newId('sale-button'),
type: 'button',
values: {
text: 'Shop the sale',
href: {
name: 'web',
values: { href: 'https://example.com/sale', target: '_blank' },
},
},
},
],
values: {},
},
],
values: {},
});
// 4. Load it back.
const result = await unlayer.agent.loadDesign(design);
if (!result.ok) {
// Nothing changed. result.errors lists what to fix: [{ path, message, code }]
}
```
The `guide` from `describe()` explains the design format in full. `schema()` returns its JSON Schema, and the [Design object](/design-schema/design-object) page describes it too. Some types need more than this example shows: a paragraph, for example, stores its text in `values.textJson`.
| Method | What it does |
| --------------------- | ----------------------------------------------------------------------------------- |
| `describe()` | Returns a guide written for agents, plus what this builder supports. Call it first. |
| `schema()` | Returns the JSON Schema of the design, including your custom tools. |
| `getDesign()` | Returns the current design. |
| `loadDesign(design)` | Checks a design and loads it if it's valid. |
| `preview(device)` | Opens the preview at `'desktop'`, `'tablet'` or `'mobile'`. `null` closes it. |
| `exportHtml(options)` | Exports the current design. Takes the same options as `unlayer.exportHtml`. |
All methods return promises, and they can fail with an error. That happens when no builder on the page offers the API, when the builder isn't ready in time, or when it doesn't answer within 15 seconds (60 seconds for `getDesign`, `loadDesign` and `exportHtml`). `loadDesign` is the exception while the builder loads: it returns `ok: false` with the code `not_ready` instead.
## What happens when an agent loads a design
- **It's checked first.** If something is wrong, the design doesn't change, and the agent gets a list of errors. Each error names the JSON path to fix.
- **It's one undo step.** A valid design replaces the current one, and your users can undo it like any other change. It also replaces changes made after the agent read the design, so agents should read the design again right before changing it.
- **Protected content stays.** In `live` design mode (the default), content your [template permissions](/builder/templates/permissions) protect keeps its current value. Protected means locked, or set so it can't be edited, deleted or moved. The result lists what was kept in `protectedElements`.
- **Your autosave sees it.** The builder fires [`design:updated`](/builder/events) with the type `agent:modified`.
- **The audit runs.** The result includes the builder's checks, such as missing alt text or empty links.
A successful load returns:
```javascript
{
ok: true,
loaded: true,
errors: [],
errorCount: 0,
protectedElements: [],
audit: { status: 'PASS', issues: [], issueCount: 0 },
}
```
When `ok` is `false`, nothing changed. Each error in `errors` has a `path`, a `message` and a `code`:
| Code | Meaning |
| ------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `invalid_type` and other format codes | The design doesn't match the format at `path`, such as a paragraph without `values.textJson`. |
| `unknown_type` | The design adds a block this builder doesn't offer, or one you turned off. |
| `design_changed` | A different design was opened after the agent read it. The agent should read the design again. |
| `protected_content` | The change can't be applied without changing content your template protects. Ordinary edits to protected content don't cause this: they're kept as they were, and the load succeeds. A new block that reuses an id already in the design also returns this code. |
| `not_ready` | Only from `loadDesign`: the builder was still loading. Try again. |
## Several builders on one page
`describe()` lists the builders that offer the API in `editors`, each with its `index` and the `containerId` of the element it's in. Builders with `agentApi: false` aren't listed, so the indexes only count the others.
To pick a builder, pass its index in the last argument. The first builder is the default:
```javascript
const { editors } = await unlayer.agent.describe();
// [{ index: 0, containerId: 'editor' }, { index: 1, containerId: 'newsletter' }]
const design = await unlayer.agent.getDesign({ editor: 1 });
await unlayer.agent.loadDesign(design, { editor: 1 });
await unlayer.agent.preview('mobile', { editor: 1 });
```
WebMCP tools take an `editor` field with the same index, for example `{ "editor": 1 }`.
## Turn it off
```javascript
unlayer.init({
id: 'editor',
agentApi: false,
});
```
With `agentApi: false`, this builder is left out of `unlayer.agent` and the WebMCP tools. `unlayer.agent` itself still exists on the page, so don't check for it to see whether the API is on. Call `describe()` instead: it fails with an error when no builder on the page offers the API, and otherwise lists the builders that do in `editors`.
## How agents find it
The builder's iframe gets an accessible name (its `aria-label`) that tells agents the API exists:
```text
Design editor. Also editable as JSON via window.unlayer.agent: describe() returns the API guide.
```
Nothing changes on screen. Screen readers announce this name too. The iframe also gets `tabindex="0"`, so agents that read only focusable elements find it. Iframes are focusable by default, so keyboard navigation doesn't change. The name describes the API rather than instructing agents, because agents treat instructions in page content as possible prompt injection and ignore them.
## Related
- [Unlayer MCP](../mcp/overview.md) is for agents that work outside your app, such as Claude Desktop or coding agents, with the templates in your Unlayer account.
- [Load and save designs](/builder/load-and-save-designs) covers `loadDesign` and `saveDesign` for your own code.
---
## AI Credit Estimator
creditsPerPack,
packPrice,
pricePerThousandCredits,
} from '@site/src/components/AiCreditEstimator';
# AI Credit Estimator
Plan a monthly AI budget before you build. Enter how many end users you expect
and how often each one uses each AI feature in a month. The result is an
**estimate, not a quote or a limit**: your actual usage depends on your prompts,
designs, and configuration.
## How the estimate works
Each feature has two figures measured from recent production usage of paid
Unlayer workspaces:
- **Typical** is based on the median operation: half of the operations used
fewer credits.
- **High** is based on the 90th percentile: nine in ten operations used no
more.
Routing calls, retries and failed requests also use credits, but they aren't
operations of their own. Both figures are scaled by each feature's ratio of all
billed credits to the credits of its completed operations, so every operation
carries an average share of that extra work. Both figures count only requests
that ran a model.
The low end of the range multiplies each feature's monthly operations by its
typical figure. The high end uses the high figure.
Imports run much less often than other features. Their figures use the token
sizes of recent imports, from up to the last 90 days and only since the import
pipeline last changed in a way that affects cost. They're priced at the current
rates of the model that runs imports. When only a few workspaces back them, the estimator
marks them as based on limited usage. The high end adds up every
feature's high figure, so treat it as a conservative budget rather than a
likely month.
An AI Credit is a cost-based unit: at list price, 1,000 credits are worth
{pricePerThousandCredits}. AI Credits are added in recurring packs of
{creditsPerPack} credits for {packPrice} a month, and unused credits don't roll
over. The estimate shows the packs you would need at list price. Enterprise
plans have negotiated AI allowances, so [contact sales](https://unlayer.com/contact)
for Enterprise pricing. One-time welcome credits are not included. See
[Pricing](./pricing.md) for allowances, resets, and what happens when credits
run out.
## What changes your actual usage
The figures describe typical production requests, not yours. Expect higher
usage than the typical figure when:
- **Designs are large or carry embedded images.** The Assistant processes the
surrounding design, not just the selected block. Images embedded as data URLs
can add substantial input and output.
- **Requests carry more context.** [Brand Context](./customization/brand-guidelines.md),
long conversations, and follow-up turns add input to each request.
- **You register custom tools.** Custom-tool configuration can route a request
to a more capable model, even when it edits a built-in text block.
- **Assistant image requests include conversation work.** The image figures
cover the image operation. Asking for an image in the Assistant also uses
some text credits for the conversation.
- **The image model sets the image cost.** The default image models depend on
the editor version, and the public API keeps its own default. A model you
choose in your configuration can cost more or less than the defaults. The
estimator marks image figures that predate a change of default models.
The figures exclude legacy AI tools such as Smart Text. Unlayer refreshes the
figures when models, routing, or rates change; the dates under the estimate show
when they were measured.
## Check the estimate with your own usage
Before you commit to a budget, run representative requests in a test project
and compare them with the estimate. The
[AI Credits usage API](/server/cloud-api/ai-credits) reports credits by end
user and `feature_type`, using the same features as this estimator:
| Estimator input | `feature_type` |
| --------------------- | ------------------- |
| Whole-design requests | `full_template_gen` |
| Text and block edits | `block_edit` |
| Images generated | `image_generation` |
| Images edited | `image_edit` |
| HTML imports | `html_import` |
| Screenshot imports | `image_import` |
To turn the estimate into per-user budgets that your app enforces, see
[End-User AI Credits & Upsell](/ai/credit-upsell).
---
## Brand Context
# Brand Context
:::info Availability
Brand Context is available in Unlayer Editor **1.470.0 and later**.
:::
Brand Context gives the AI Assistant reusable details about your company,
audience, colors, logos, voice, and writing guidelines. People can then ask for
content without repeating the same brand instructions every time.
## Set it up in Console
Open **Settings → AI → Brand Context**. Enter the details yourself, or import a
public website to create a draft. Review the result, then select **Save brand**.
You can also add primary and secondary logos, describe the brand voice, and
include any rules the Assistant should follow.
## Set it in code
Use `features.ai.brand` when you want to provide Brand Context at runtime:
```javascript
unlayer.init({
id: 'editor-container',
projectId: 1234,
user: {
id: 'user-123',
},
features: {
ai: {
brand: {
companyName: 'Northstar Coffee',
productDescription: 'Freshly roasted, thoughtfully sourced coffee.',
targetAudience: 'People who make coffee part of their daily ritual.',
colors: {
primary: '#163B2D',
secondary: '#F7F1E7',
accent: '#D18B47',
},
logos: {
primary:
'https://cdn.northstarcoffee.example/northstar-coffee-logo.png',
},
voice: 'Warm, confident, and welcoming.',
guidelines: 'Keep copy concise and make the next step clear.',
},
},
},
});
```
Every field is optional. Logo URLs must be public, credential-free HTTPS URLs.
## See it in the Assistant
The Assistant uses Brand Context as a default while still following the
person's request. For example, a simple welcome-email prompt can reuse the
saved palette and voice:
## Which value is used
With a `projectId`, the saved Console Brand Context is the default. The
`features.ai.brand` value controls whether that default is used for the editor
session:
| `brand` value | Behavior |
| ---------------------- | ------------------------------------------------------------- |
| Omitted or `undefined` | Use the saved project Brand Context, when available. |
| A brand object | Replace the saved project value with this object. |
| `null` | Use no Brand Context and do not load the saved project value. |
For direct API requests, omit `context.brand` to use the saved value, provide
an object to override it, or send `null` to disable it for that request.
When no Brand Context is available, no brand instructions are added to the
Assistant prompt.
Brand Context affects AI Assistant copy and design generation. It does not
automatically configure the image provider or affect HTML and image imports. Include specific visual brand requirements in an image-generation or editing prompt.
## Effect on credits and speed
There is no fixed relationship between Brand Context and credit consumption.
It adds input context; the effect depends on how much brand information is
included, the model, and whether context can be reused from cache. Relevant
information provided up front can also help the AI reach the
desired result faster and with less work, which may reduce total time and total
credits.
Omitting `features.ai.brand` can still load the project's saved brand. Use
`features.ai.brand: null` when measuring a request without Brand Context.
The result can vary by prompt and design. To measure it for your product, run
the same prompt, design, and model with your Brand Context and with
`features.ai.brand: null`, then compare the completed request's credits and
elapsed time. Repeat each test a few times because model output varies.
If you include heading or body fonts, their names must exactly match a font
configured in the editor, including fonts enabled in
[Project Fonts](/builder/font-management/custom-fonts). The Assistant never
invents a font name.
## Related
- [AI Assistant setup](../setup.md)
---
## Events & Callbacks(Assistant)
The AI Assistant emits lifecycle callbacks that you can subscribe to from the
host app. Register them after the editor initializes with
`unlayer.addEventListener` (an alias of `registerCallback`). Use them for
prompt telemetry, support diagnostics, product analytics, or mirroring streamed
output in your own UI.
:::important Not a billing ledger
Lifecycle callbacks describe the editor session. Production success callbacks
do not include authoritative credit usage, and a client event can be missed or
modified. Use the server-side
[AI Credits API and webhooks](/server/cloud-api/ai-credits) for billing,
allowance enforcement, and reconciliation.
:::
Lifecycle callbacks are notifications, not authorization hooks. They fire only
after the editor has accepted the user action, and the editor does not wait for
or interpret their return values. Enforce plan access and per-user limits in
your backend, then pass the resulting UI state through the documented feature
and credits configuration.
## Common use case: logging prompts & per-user analytics
The most common reason to wire these callbacks is to track what users ask the
Assistant for product analytics, support correlation, or content moderation:
1. Subscribe to **`ai:assistant:on:request`** to capture the user's prompt and the target scope (which row / block / text selection it was scoped to).
2. Subscribe to **`ai:assistant:on:success`** (and `:on:error` / `:on:cancel`) to record the outcome. Success and error events may include `durationMs`; to cover every turn, measure elapsed time from the matching request event.
3. Forward each event to your analytics pipeline (Mixpanel, Amplitude, Segment, your own warehouse) keyed by the user id you already know in the host app.
Every lifecycle event carries the embed's attribution context (see
[Shared context fields](#shared-context-fields)), so you can key session
analytics directly from the payload. The end-user id is the one passed through
[End-User Identification](/builder/end-user-identification).
```javascript
unlayer.addEventListener('editor:ready', () => {
unlayer.addEventListener('ai:assistant:on:request', (params) => {
analytics.track('ai_prompt_sent', {
userId: params.endUserId, // end-user from unlayer.init({ user })
projectId: params.projectId,
workspaceId: params.workspaceId,
requestId: params.requestId,
prompt: params.prompt,
scope: params.dataType, // 'body_block' | 'row_block' | 'text' | ...
target: params.location, // { collection, id }
});
});
unlayer.addEventListener('ai:assistant:on:success', (data) => {
analytics.track('ai_prompt_completed', {
userId: data.endUserId,
responseId: data.responseId,
durationMs: data.durationMs,
locale: data.locale,
toolType: data.toolType,
});
});
});
```
The event reference below documents the full payload of each lifecycle event.
## Shared context fields
Every lifecycle event (`on:request`, `on:success`, `on:error`, `on:cancel`) carries these attribution fields in addition to its own payload:
- **`projectId`** — the numeric project id from `unlayer.init({ projectId })`; `null` when none was passed.
- **`workspaceId`** — id of the workspace the project belongs to; may be `null` on older API deployments.
- **`endUserId`** — id of the end-user identified via [`unlayer.init({ user })`](/builder/end-user-identification); `null` when no end-user is identified.
- **`featureType`** — classification of the AI feature used this turn: `'full_template_gen' | 'block_edit' | 'html_import' | 'image_import' | 'image_generation' | 'image_edit'`; `null` when the turn has no classification.
## `ai:assistant:on:request`
Fires at the start of every turn, before any AI call. Use it to time turns, count requests, or capture the prompt and target location.
For Template Importer turns, `dataType` is `import_html` or `import_image`, and `prompt` contains the optional instructions entered beside the attachment (or an empty string when none were provided). The uploaded HTML or image content is not included in callback payloads or lifecycle logs, but its bytes are sent to Unlayer's AI service and the selected model provider to perform the import.
Registering `ai:assistant:generate` gives the host application ownership of AI
Assistant generation. The embedded importer and image attachment picker are hidden while that callback is registered, because its single-result contract does not represent these workflows. Unlayer's default importer and conversational image operations are not invoked for host-owned turns.
When an import would replace a non-empty design, the turn does not start until the end-user clicks **Replace design**. Choosing **Cancel** at that confirmation is a local UI decision: it emits no `on:request` event and, because no lifecycle started, no `on:success`, `on:error`, or `on:cancel` event.
```javascript
unlayer.addEventListener('ai:assistant:on:request', function (params) {
console.info('AI turn started', {
requestId: params.requestId,
prompt: params.prompt,
dataType: params.dataType, // e.g. 'body_block', 'row_block', 'text'
location: params.location, // { collection, id }
});
});
```
## `ai:assistant:on:success`
Fires when a turn completes successfully. Carries the chat locale supplied by the editor and the design payload the assistant produced. Streaming Assistant turns also include the wall-clock duration as `durationMs`; Template Importer turns omit it, so time those from the matching `on:request` event.
In local development, dev, and QA environments, completion callbacks also include a diagnostic `usage` object with token counts, `estimatedCostMicroUsd`, and `aiCreditsUsed`. Usage diagnostics are intentionally omitted from these host callbacks in staging and production. For a verified edit blocked entirely by template permissions, `usage.aiCreditsUsed` is `0` when the normal aggregate charge is at most 200 credits, even though diagnostic token counts and provider cost may be nonzero. Larger protected no-change turns and partial edits use credits normally. See [Pricing](./pricing.md#protected-edits-that-make-no-changes).
```javascript
unlayer.addEventListener('ai:assistant:on:success', function (data) {
console.info('AI turn succeeded', {
responseId: data.responseId,
durationMs: data.durationMs,
locale: data.locale, // current AI chat locale
toolType: data.toolType,
});
});
```
## `ai:assistant:on:error`
Fires when a turn fails — after the editor has already retried internally. Includes the error name and HTTP status code if applicable. Structured service failures may also include `code`, `limitKey`, `remaining`, `total`, `upgrade_url`, and `canClaimStarterCredits`. Cancellations route to [`ai:assistant:on:cancel`](#aiassistantoncancel) instead — they do not fire here.
```javascript
unlayer.addEventListener('ai:assistant:on:error', function (data) {
console.warn('AI turn failed', {
name: data.name,
message: data.message,
statusCode: data.statusCode,
durationMs: data.durationMs,
});
});
```
## `ai:assistant:on:cancel`
Fires when a turn that already emitted `ai:assistant:on:request` is interrupted before completion — the user clicked Stop, started a new request, removed the target element, or the request timed out. The `reason` discriminates the cause. It does not fire when an end-user declines the Template Importer replacement confirmation because that choice happens before a request starts.
The lifecycle guarantee begins with `ai:assistant:on:request`: after that event, an interrupted turn emits `ai:assistant:on:cancel`. Actions taken before a request starts, including declining replacement confirmation, are outside the lifecycle and emit none of these callbacks.
For Template Importer turns, `stop_button` is reserved for the explicit **Stop** action. Target changes, target removal, and Assistant teardown use `item_removed`.
```javascript
unlayer.addEventListener('ai:assistant:on:cancel', function (data) {
console.info('AI turn cancelled', {
reason: data.reason, // 'stop_button' | 'new_request' | 'item_removed' | 'timeout'
});
});
```
## `ai:assistant:on:stream`
:::caution Beta
`ai:assistant:on:stream` is in beta. The set of `event.type` values, the shape of each payload, and the firing semantics may change as the streaming pipeline evolves.
:::
Fires for the supported stream events the assistant produces during a turn — optional status text for long generations, partial text deltas, follow-up suggestions, and design operations as they arrive. Useful for mirroring the assistant's output into your own UI, building progress indicators, or debugging.
Image results are currently rendered by the built-in chat and are not forwarded as image-result events through this callback. Use the [conversational Images API](/server/cloud-api/images#images-in-an-assistant-conversation) when building a separate image chat UI. Image references are sent to the image provider for the requested operation; lifecycle callbacks are not a file-upload API.
The payload is a discriminated union — switch on `event.type` to handle each kind:
```javascript
unlayer.addEventListener('ai:assistant:on:stream', function (event) {
switch (event.type) {
case 'start':
// A new assistant turn began.
console.info('AI stream started', {
toolType: event.toolType,
messageId: event.messageId,
});
break;
case 'status':
// Human-readable progress label (e.g. "Analyzing your request…").
console.info('AI status:', event.text);
break;
case 'text-delta':
// Incremental text chunk for the chat bubble identified by blockId.
appendToBubble(event.blockId, event.delta);
break;
case 'suggest-options':
// Quick-reply suggestions the assistant proposes for the user's next turn.
if (event.question) renderQuestion(event.question);
renderQuickReplies(event.options); // [{ label, prompt }, ...]
break;
case 'design-partial':
// Snapshot of the design after a structural update.
console.info('Design snapshot', event.full);
break;
case 'design-operation':
// A single design mutation (add/remove/move/update) about to be applied.
console.info('Design op', event.op);
break;
}
});
```
## Protected designs
Generation callbacks do not bypass [template permissions](./how-it-works/full-template.md#template-permissions). In live mode, the editor checks the callback result against the current design before applying it. Locked content and disabled properties remain unchanged. Return the original element IDs for existing blocks, including protected blocks, so the editor can match them reliably. Edit mode allows the same unrestricted editing access as the administrator.
---
## Examples
Screenshots and walkthroughs of the AI Assistant.
## Generating a full email from a prompt
## Restyling an existing template
## Editing a single block
## Picking from multiple suggestions
## Generating an image
Ask “Generate a watercolor illustration of a house and add it below the welcome paragraph.” To use a stock photo instead, ask “Find a photo of a modern house” and choose a result.
For an edit, select a design image and ask “Make this black and white,” or attach references with **+ → Add an image**. With several attachments, reorder the thumbnails and ask “Use the colors from image #1 in image #2.” See [Image workflows](./how-it-works/image.md) for result actions, undo, and configuration.
---
## FAQ & Troubleshooting
Missing something? Email [support@unlayer.com](mailto:support@unlayer.com) or use the in-product chat in [Console](https://console.unlayer.com).
## Pricing & credits
### How much does it cost?
AI uses one workspace-level credit bucket. An AI Credit is a cost-based usage
unit, not a model token or a fixed price per edit. A short text request can
still use hundreds of credits when it processes substantial design context or
needs more model work. Input, output, model choice, caching, and retries all
affect the total; measure representative workflows before setting user
allowances. See [what affects cost](./pricing.md#what-affects-text-edit-cost).
Eligible workspaces see a one-time welcome offer in Billing. It appears
only when the current plan, subscription status, and AI feature eligibility
qualify; current Free and legacy plans do not qualify. Eligibility to buy a
credit pack is separate. See [Pricing](./pricing.md).
### Can I get a surprise bill if my users go heavy on AI?
On a capped workspace, Unlayer stops new generations when the workspace reaches
its available credit allowance. By default the controls remain visible and show
an exhaustion message; a project can instead hide them. Grandfathered uncapped
workspaces continue to meter usage without pausing AI or creating overage
charges. Unlayer does not purchase another credit pack in response to an AI
request; the only automatic purchase is the opt-in
[automatic top-up](./pricing.md#automatic-top-ups), which stays within the
budget per period you set. See
[When credits reach zero](./pricing.md#when-credits-reach-zero).
### How do I track what my users ask the assistant?
Subscribe to the AI lifecycle callbacks from your host app and forward the
events to your analytics pipeline. **`ai:assistant:on:request`** carries the
prompt and target scope; after it fires, the corresponding
**`ai:assistant:on:success`**, **`:on:error`**, or **`:on:cancel`** callback
carries the outcome. Success and error events may include `durationMs`; to cover
every turn, measure elapsed time from the matching request event. Pre-request UI
choices, such as declining Template Importer replacement confirmation, emit no
lifecycle callback.
Each emitted event also carries the `projectId`, `workspaceId`, and identified
end-user (from
[End-User Identification](/builder/end-user-identification)), so per-user
analytics and support correlation can use the event payload. Callbacks are
after-the-fact notifications and cannot authorize or prevent an AI request, so
enforce free-tier limits and other access rules in your backend. Do not use
callbacks as a billing ledger: production success callbacks omit per-turn
credit usage. A structured exhaustion error can include the current limit state,
but it is not a complete usage record. Use the
[AI Credits API and webhooks](/server/cloud-api/ai-credits) for billable usage.
For a worked example, see
[Events & Callbacks → Common use case: logging prompts & per-user analytics](./events-callbacks.md#common-use-case-logging-prompts--per-user-analytics).
### Can I read credit usage and build my own billing on top of it?
Yes. The server-side
[AI Credits API and webhooks](/server/cloud-api/ai-credits) provide workspace
balances, project and end-user breakdowns, alert thresholds, and signed usage
events.
### Why does the chat say I'm out of credits in my dev project?
Every project in a workspace shares the same usage bucket, so dev and production
projects contribute to the same pool. There is no separate unmetered dev tier. If
Billing offers the 5,000-credit welcome bonus, someone with billing access must
claim it explicitly; the card shows when it expires. The grant does not unlock
features that the plan excludes, and eligibility to claim it is separate from
eligibility to buy a paid credit pack. Grandfathered uncapped workspaces are not
paused by their metered AI usage. See
[Reset and expiration](./pricing.md#reset-and-expiration).
### Is there a per-user rate limit?
Unlayer enforces one workspace pool, not separate per-user allowances or reset
cycles. Identify each end user, read their consumption from the usage API, and
enforce your commercial limit in your backend. The builder's `credits` and
`setCredits` APIs can display that backend state and block the UI, but they are
not a security boundary. See
[End-User AI Credits & Upsell](/ai/credit-upsell).
### Why might AI controls disappear when credits reach zero?
The project is using `exhaustion_behavior: "disable"`. Change it to
`"show_error"` with `PUT /v3/projects/:id/ai-credits/settings` to keep the
controls visible and show the out-of-credits message instead. The message can
also be customized with the
[documented translation keys](./pricing.md#customize-the-exhaustion-message).
### Why is full-template generation more expensive than a one-block edit?
Full-template turns reason over the entire layout and can emit a much larger
result, which adds model work. For a change to one paragraph or block, prefer a
per-element edit. It can avoid a full rewrite, but substantial surrounding
context can still make it expensive. See
[Full Template tradeoffs](./how-it-works/full-template.md#tradeoffs).
## Setup & visibility
### How do I enable or disable the AI Assistant?
The AI Assistant is **on by default** — you don't need a feature flag to turn it on. It becomes available in the editor's mode switcher when:
1. **`features.ai.assistant`** is left at its default of `true` (you only set it to `false` to disable).
2. The project belongs to a workspace whose **plan includes the AI Assistant**. Check the plan in [Console](https://console.unlayer.com) → Project → Settings.
3. The init **identifies the end-user** — a `user` object with an `id` is passed to `unlayer.init`. See [End-User Identification](/builder/end-user-identification).
To **disable** it on a specific embed (e.g. a free-tier user, an editor surface where you don't want AI), pass `features.ai.assistant: false` on that `unlayer.init` call. The assistant is hidden in that editor instance only.
If the AI Assistant is still missing, confirm that neither
`features.ai.enabled` nor `features.ai.assistant` is `false`, the init includes
`user.id`, and the workspace plan includes the AI Assistant. See
[Setup](./setup.md) for the full reference and
[Disabling per init](./setup.md#disabling-per-init) for the disable pattern.
### Why did the legacy Smart tools disappear?
Smart Text, Smart Paragraph, Smart Buttons, Smart Headings, and Smart Image
Alt Text were retired on **October 1, 2026**. Changing legacy `features.ai`
flags does not restore retired tools. Use the [AI Assistant](./setup.md)
instead; it has its own plan and setup requirements.
The former Magic Image panel has been replaced by image generation and editing
in the AI Assistant. AI editing in the standalone Image Editor also requires
AI Assistant access; legacy Magic Image access alone no longer enables it.
See [Image generation and editing](./how-it-works/image.md).
See the [Setup guide](./setup.md) for the Assistant's requirements.
### Can I run the assistant offline / on-premise?
No. The assistant requires a network call to Unlayer's AI service (and from there to the model providers). On-premise deployments are not currently supported.
## Privacy & data
### Does the AI Assistant train on my data?
No. Prompts and surrounding design context are sent to Unlayer's AI service and forwarded to the underlying model providers (OpenAI, Anthropic, and others Unlayer uses as subprocessors). Inputs are **not** used to train models. For data-handling specifics tied to your contract — data residency, retention, DPA — contact your account manager.
### Can my end users opt out of having their prompts sent to a third-party AI?
Yes — disable the assistant for that user by passing `features.ai.assistant: false` on the `unlayer.init` call that loads the editor for them. The editor doesn't ship a built-in "AI on/off" toggle for end users; that decision lives in your application's UI.
### Does the assistant store my prompts?
Unlayer logs prompts for short-term debugging and abuse prevention. The model providers may apply their own retention windows per their terms. For zero-retention agreements, contact your account manager.
## Behavior & quality
### The assistant skipped my custom block. Why?
Your custom tool likely uses **custom widgets or its own property editors**, which the assistant can't introspect on its own. Declare the tool's value shape by passing a `schema` field on the registration call. See [Custom Tools](./how-it-works/custom-tool.md#custom-widgets-and-property-editors).
### How do I keep the Assistant from changing protected content?
Set the appropriate template permission and load the end-user editor in
`designMode: 'live'`. **Locked** preserves an element's values and descendants,
including during whole-design rewrites. Use **Draggable** separately to pin its
position. The other permissions independently control editing, deletion,
duplication, and visibility. Custom tools can additionally use
`supportedByAI: false`; that option is not a supported built-in tool override. See
[Protect content from AI changes](./how-it-works/content-protection.md).
### Why doesn't the assistant know the values of my merge tags?
Merge tags are **preserved literally** in the output — `{{ first_name }}` comes back as `{{ first_name }}`, not "John". The assistant doesn't see your data; it sees the tag and treats it as an opaque placeholder. If you want the assistant to reason about realistic data, pass a sample value through your application copy ("e.g. _Hi John_") instead of relying on the tag itself.
### Why does the output look generic / not match my brand voice?
Configure [Brand Context](./customization/brand-guidelines.md) to give the
assistant your company identity, palette, exact fonts, voice, and guidelines.
If Brand Context is not configured, you can still guide the result:
- Ask explicitly in the prompt (_"sound less salesy and more helpful"_, _"match the tone of the heading above"_).
- Give the assistant nearby context — having well-written body copy in the same section makes it easier for the assistant to match.
### What languages does the assistant support?
The assistant auto-detects the language the user typed and replies in that language. A translation target in the request applies to the design copy, not the surrounding chat response. Generation works in any language the underlying model handles — Spanish, French, German, Portuguese, Italian, Japanese, Korean, Chinese, Arabic, and so on. The editor UI itself is translated separately — see [Localization](/builder/localization).
### Why is the assistant producing different results for the same prompt?
LLM outputs are stochastic; identical prompts will produce slightly different results each turn. That's expected. The **[Ask for multiple options](./how-it-works/text.md#ask-for-multiple-options)** flow takes advantage of this: ask for 5 alternatives and pick the best one.
### Why does the image picker or import action not appear?
The **+** menu appears only when at least one attachment action is available. Image attachments require AI Assistant access and enabled image upload; they also work when image editing is disabled. **Import from HTML or image** is a separate feature, disabled by default, and is available only for full-template assistance. Registering `ai:assistant:generate` hides both attachment actions. See [Configure image actions](./how-it-works/image.md#configure-image-actions).
### Will an image request always generate a new image?
No. For ordinary photo requests, the Assistant prefers enabled stock libraries. Ask explicitly to generate a custom image when that is what you need, or select an existing image and describe an edit. A clear request proceeds directly; an unclear subject or instruction can require a short question. Failed stock search does not silently switch to paid generation.
## Performance
### Is it fast?
**Yes.** Per-block edits (text, button, heading, image alt text) typically finish in **a few seconds**, and the assistant uses **real-time streaming** to apply changes to the visual editor as the model generates them: text streams into chat bubbles and design operations land on the canvas one at a time. Longer full-design generations can also show a progress update. Automatic routing can use a smaller, faster model for simpler requests. Custom-tool configuration or an explicit model choice can select a different route, even for a simple prompt. **Full-template generation** reasons over the entire layout and can take tens of seconds. Image generation and editing also wait for the image provider; editing several images takes longer than one edit. See [Full Template tradeoffs](./how-it-works/full-template.md#tradeoffs).
### Why is full-template generation taking 30+ seconds?
Full-template turns are the heaviest work the assistant does — they reason over the entire layout and emit a much larger payload. **Tens of seconds is the expected range** for full-template work; sometimes longer for very large designs. See [Full Template tradeoffs](./how-it-works/full-template.md#tradeoffs).
For faster iteration on a single block or paragraph, prefer per-element edits — those typically finish in a few seconds.
## Debugging
### Reporting an assistant failure to Unlayer support
The faster you give us context, the faster we can reproduce. When opening a ticket, include:
- **Your project ID** — find it in [Console](https://console.unlayer.com) → Project → Settings.
- **Editor version** — run `unlayer.version` in the browser console (with the editor loaded on the page) and paste the value.
- **The prompt** the user typed — exact text, ideally copied from the chat input.
- **When it happened** — approximate timestamp in your local time zone or UTC. A 5-minute window is enough for us to find the request in our logs.
- **What you expected vs. what actually happened** — _"I asked the assistant to translate this row to Spanish; it rewrote the row in English instead"_ is much more useful than _"AI broke"._
- **A screenshot or short screen recording** of the failure — especially anything visible in the chat (status text, partial output, error banner).
- **Browser console output**, if any errors logged — especially anything prefixed with `[unlayer]`.
## Related
- **[Setup](./setup.md)** — gating, plan requirements, and the disable-per-init pattern.
- **[Pricing](./pricing.md)** — credit-based model and what to do when you run out.
- **[Events & Callbacks](./events-callbacks.md)** — programmatic hooks for logging and analytics.
- **[AI Credits API & Webhooks](/server/cloud-api/ai-credits)** — read credit balance/usage and receive credit webhooks server-side.
- **[Content Protection](./how-it-works/content-protection.md)** — lock content and control whole-design rewrites.
- **[How it works](./how-it-works/full-template.md)** — what the assistant does at each scope.
---
## Protect content from AI changes
The AI Assistant has the same editing access as the current builder user. In
`designMode: 'live'`, it follows template permissions for selected elements,
row edits, and full-template rewrites. In `designMode: 'edit'`, administrators
and the Assistant can change protected content.
Use **Locked** when an element's values and descendant content must remain
unchanged. The Assistant also retains the minimum ancestor structure needed to
render a locked descendant, so a locked button or compliance footer cannot be
removed by replacing its row or the whole template. Movement is a separate
permission; set **Draggable** to false when a locked row must also stay in its
original position.
Set the permission while preparing the template in `designMode: 'edit'`, then
save the design. The saved item carries `values.locked: true` when it is loaded
for end users. Load that design in `designMode: 'live'` to enforce the lock:
```javascript
unlayer.init({
designMode: 'live',
});
```
An excerpt from a saved content block or row:
```json
{
"values": {
"locked": true
}
}
```
See [Template Permissions](/builder/templates/permissions) for the full editor
mode workflow.
## How each permission applies
Template permissions are independent. Turning off one action does not make the
element a blanket lock:
| Permission | Assistant behavior in live mode |
| --------------------- | ---------------------------------------------------------------------------------- |
| `locked: true` | Keeps the element's values and descendant content unchanged. |
| `selectable: false` | Does not edit that element's values; descendants keep their own access. |
| `deletable: false` | Does not delete or replace the element. Its other editable values remain editable. |
| `draggable: false` | Does not move or reparent the element. |
| `duplicatable: false` | Does not copy the element into a new one. |
| `hideable: false` | Does not change the element's desktop, tablet, or mobile visibility. |
Disabled properties and properties locked by a style guide also stay
unchanged. A hidden property editor alone does not make its value read-only.
The Assistant preserves the permission flags themselves so it cannot weaken a
restriction and edit the element later in the same turn.
## Selected-block edits
Editing a selected Text, Heading, or Button block updates that block without
copying its generated content into neighboring blocks. This also applies to a
new block inserted above existing content, including when
`features.ai.fullTemplateGeneration` is `false`. The selection stays on the same
block while the response streams and when you send a follow-up request.
## Full-template edits
Full-template generation enforces the same rules. For example, when translating
an English template to Portuguese, editable copy is translated while a locked
button in the middle and a locked compliance footer keep their original copy.
Set `draggable: false` too when their positions must remain fixed. A request
such as “clear everything” removes only removable content and keeps protected
elements with the containers required to render them. Clearing the template is
supported when the entire canvas is selected; clearing a property, such as a
background color, remains a property edit.
The Assistant also preserves body text and link colors when locked content may
inherit them. For locked rows, headers, and footers without an opaque background,
it preserves the body background too, including the popup container's fill and
background image in popup mode. This prevents a theme rewrite from making
locked text disappear against its background. Editable rows and blocks can still
use their own colors. These safeguards apply to AI changes; manual body styling
remains controlled by the editor's own permissions. Lock the whole row when its
background must also be protected.
When permissions block part of a request, the Assistant applies the allowed
edits and reports that protected content was preserved. Requests that only
change editable content do not show a protection notice, even when the template
contains locked content. For example, changing the copy of a non-deletable text
block does not show a warning about a separate locked button. If permissions
prevent every requested change, the design remains unchanged. Eligible protected no-change
turns use [zero AI credits](../pricing.md#protected-edits-that-make-no-changes).
Existing design element IDs must be unique. Invalid design structure or duplicate
IDs return a validation error before AI generation begins.
## Custom and built-in tools
For a custom tool, add `supportedByAI: false` to its registration when it
should not be a direct Assistant target. Use template permissions on a saved
instance when it must also be protected during row or full-template edits.
Built-in tools such as Button do not have a supported `supportedByAI` override.
Set the appropriate template permissions on the specific built-in content
instance instead.
## Related
- [Custom Tools](./custom-tool.md)
- [Full Template](./full-template.md)
- [Template Permissions](/builder/templates/permissions)
---
## Custom Tools(How-it-works)
Embedders can register their own content blocks via `unlayer.registerTool(...)` — see [Custom Tools](/builder/tools/custom/create) for the registration API. The AI Assistant can insert and edit these blocks too, with one configuration step for the cases it can't introspect on its own.
## Automatic support
If your custom tool only uses Unlayer's [**built-in property editors**](/builder/tools/custom/property-editors) (text, color, font, link, image, dropdown, checkbox, slider, etc.), it works with the AI Assistant automatically.
Once you [register the tool](/builder/tools/custom/create) and make it available in the current display mode, end users can ask the assistant to insert it. The design does not need to contain an existing instance first. For example, if your app registers a Product Card tool, an end user can ask:
> Add a Product Card for a Morning Mug priced at $24 below the heading.
End users can also select existing content and ask for a custom tool below it, or select an existing custom block and ask the assistant to edit its values.
Tools that use custom property editors still need a [schema on the widget](#custom-widgets-and-property-editors) for those properties. Insertions and edits follow the tool's AI support setting and [template permissions](#template-permissions) described below.
## Opt a custom tool out
Set `supportedByAI: false` when registering a custom tool to remove direct AI
support for that tool:
```javascript
unlayer.registerTool({
name: 'compliance_footer',
label: 'Compliance Footer',
supportedByAI: false,
// options, values, and renderer...
});
```
This option belongs to custom tool registration. It is not a supported way to
disable a built-in tool type, so setting `tools.button.supportedByAI` does not
remove Button from the Assistant. Lock the specific built-in content that must
remain unchanged, or disable the Assistant for that editor.
`supportedByAI: false` prevents a user from targeting the custom tool directly,
but it is not a hard protection for an existing instance during a whole-design
rewrite. For content that must remain unchanged, also mark the saved content as
locked. Full-template generation follows that lock in live mode. See
[Protect content from AI changes](./content-protection.md).
## Custom widgets and property editors
When a property uses a **custom property editor** built with `unlayer.createWidget(...)`, the assistant can't infer the shape on its own — the widget renders arbitrary UI and stores arbitrary values that Unlayer doesn't know about. In that case, you declare the shape explicitly by passing a `schema` field on the **widget**, not on the tool. The schema lives next to the widget's `mount` and `render` functions:
```javascript
unlayer.registerPropertyEditor({
name: 'my_color_picker',
Widget: unlayer.createWidget({
schema: {
type: 'string',
description: 'Hex color value, e.g. "#FF5733".',
},
render(value) {
/* return HTML for the editor */
},
mount(node, value, updateValue) {
/* wire up the editor */
},
}),
});
```
The `schema` is a [JSON Schema](https://json-schema.org/) describing the **value** the widget produces. The assistant uses it to understand what the field accepts and to write valid values into it. See [Custom Tools → Custom Property Editor](/builder/tools/custom/create#custom-property-editor) for the full registration API and a complete example.
Without a `schema` on the widget, the assistant skips properties backed by that custom editor — it surfaces a message to the user explaining the property isn't AI-aware instead of trying to write into a structure it doesn't understand. With the `schema`, those properties become first-class targets for the assistant.
### Schema tips
- Use `description` on the schema (and on nested properties when the value is an object) — the assistant reads descriptions like prompt instructions, so a sentence meaningfully improves output quality.
- Constrain enums (`enum: [...]`), formats (`format: 'uri' | 'email' | 'date-time'`), and ranges (`minimum`, `maximum`) where you can. Tighter constraints produce fewer invalid edits.
- Mark fields `required` only when the value genuinely won't render without them. Optional fields give the assistant room to leave existing values untouched.
- Keep nested objects shallow. Deeply nested schemas work, but a flatter shape is easier for the assistant to reason about and produces more predictable edits.
## Related
- **[Custom Tools (registration API)](/builder/tools/custom/create)** — how to register a custom tool with Unlayer.
- **[Custom Property Editor](/builder/tools/custom/create#custom-property-editor)** — the full `createWidget` + `registerPropertyEditor` reference.
- **[Design Schema](/design-schema/content-types#custom-tools)** — how custom tools appear in the design JSON.
- **[Protect content from AI changes](./content-protection.md)** — live-mode permissions across every editing scope.
- **[AI Assistant overview](../overview.md)** — what the assistant does and where users find it.
## Template permissions
Custom blocks follow the same [template permission rules](./full-template.md#template-permissions) as built-in blocks. In live mode, locked blocks remain intact and disabled custom properties cannot be changed by the assistant. `hidden` only controls an option's presentation; it does not make its value read-only. Edit mode gives administrators and the assistant unrestricted editing access.
---
## Full Template
The AI Assistant can generate or restyle an **entire template** in a single turn — not just a row, content block, or text selection. This is the heaviest design-quality work the assistant does, but also the **easiest and most powerful** path for a user to go from a blank canvas (or an existing template that needs a full overhaul) to a finished design.
## When it shines
- **Starting a new template from scratch** — _"build me a Black Friday email for a streetwear brand, dark mode, with a hero, three-column product grid, and a footer"_ → the assistant produces the whole layout in one shot.
- **Restyling an existing template** — _"keep the same content but switch this from a casual newsletter to a corporate enterprise tone"_ → multi-row restyle in a single turn.
- **Bulk content + layout edits** — anything that touches the body as a whole (translating an entire email, swapping the brand voice, regenerating around a new product).
## Template permissions
The AI Assistant has the same editing access as the user. In `designMode: 'live'` (the default), locked elements and their content stay intact, including required footers and custom blocks. Requests such as “clear everything” or “ignore the locks” do not override those restrictions. The assistant can remove editable content while keeping the containers needed to render protected content.
Document headers and footers follow the same permissions as rows in email, web, and popup designs.
Other [template permissions](/builder/templates/permissions) apply independently: **Deletable**, **Draggable**, **Duplicatable**, **Selectable**, and **Hideable** restrict their respective actions. A non-deletable block can still be edited when its other permissions allow it. Disabled custom properties and properties locked by a style guide stay unchanged. Hidden options alone are not locks.
In `designMode: 'edit'`, administrators and the assistant can edit or delete locked elements. Use live mode when end users must respect template restrictions.
Full-template generation supports both design modes. The conversation stays active while the generated design streams onto the canvas, so you can continue with a follow-up request after it completes.
The editor checks AI results before applying them, including results from a custom generation callback. Full rewrites of protected designs wait for a complete result, so an incomplete stream cannot temporarily remove required content. The assistant explains when protected content is kept. Allowed edits are retained even when another requested edit is blocked. If permissions prevent all changes, the design stays unchanged and the turn may use [zero AI credits](../pricing.md#protected-edits-that-make-no-changes) when it is within the protected no-change waiver ceiling.
### Direct generation requests
For `/v3/templates/generate`, provide the existing design in `context.fullDesign` and the builder mode in `context.designMode` (`live` by default; `edit` for administrators). Custom integrations can supply `context.elementPermissions` as a list of `{ id, permissions }` entries. Each permissions object can include `disabledValues` listing properties disabled on every device, `disabledBaseValues` for base properties, and `disabledDeviceValues` mapping devices to protected effective properties. IDs must be unique. An object keyed by element ID is also accepted for compatibility, but use the entry list for arbitrary authored IDs so they remain JSON values rather than object keys. These fields are application context, not instructions the model may change. The editor sends them automatically.
The JSON response and the stream's `data-complete` metadata may include `protection: { preservedIds: [...], outcome: "unchanged" | "partial" }` when protected content was retained. `outcome` is present when the server verifies that edits were blocked: `unchanged` means no effective edit survived; `partial` means allowed edits survived and normal billing applies. For an unchanged result, `usage.aiCreditsUsed` is `0` only when the request's normal aggregate charge is at most 200 credits. Preserved IDs alone do not imply a credit waiver. Apply the returned design rather than the model's raw tool input. These checks protect supplied design data; callers remain responsible for authenticating users and choosing the appropriate mode.
## Tradeoffs
Full template generation does more work than a per-block edit, and that shows up as:
- **Slower.** A full template turn typically takes **tens of seconds** (sometimes longer for very large designs), versus a few seconds for a single content rewrite. The assistant has to reason over the whole layout, propose a structure, and emit a much larger payload.
- **More credits per turn.** A full-template turn usually consumes more credits than a per-element edit (see [Pricing](../pricing.md)).
- **More moving parts.** The pipeline has more steps — schema validation, multi-step planning, larger context windows. That means more surface for transient provider hiccups; the automatic [fallback chain](../overview.md#reliability--uptime) handles most of these silently.
For users iterating on a single block or paragraph, prefer **per-element edits**. They avoid a full rewrite, but their cost still depends on the context and model work.
## Disabling full template generation
If the cost or latency profile doesn't fit your product — or you want to keep the assistant available for fine-grained edits while removing the heavyweight option — set `features.ai.fullTemplateGeneration` to `false` in `unlayer.init`:
```javascript
unlayer.init({
features: {
ai: {
enabled: true,
assistant: true,
fullTemplateGeneration: false,
},
},
});
```
When disabled:
- The template-level "generate" affordance disappears from the editor.
- Row, header, footer, content-block, and text-level edits remain fully available.
:::info Varying this per end-user
This flag applies to everyone who loads the editor. To allow full template generation for some
end-users and not others, sign the permission on your own server and pass it as
`user.featurePolicyToken`. See
[Restricting Features Per End-User](/builder/latest/security#restricting-features-per-end-user).
:::
Disabling full-template generation is a product and cost choice, not a content
protection requirement. When it remains enabled, full-template edits still
follow [template permissions](./content-protection.md) in live mode.
You can also vary it per surface — turn it on in a power-user editor but off on a customer-facing embed where cost predictability matters more — by passing different `features.ai.fullTemplateGeneration` values to each `unlayer.init` call.
:::note HTML & screenshot import
The [AI Template Importer](/ai/template-importer) always produces a full template. In the embedded builder, its AI Assistant action appears only when `features.ai.templateImporter` is `true`, follows `features.ai.fullTemplateGeneration`, and the host has not registered `ai:assistant:generate`. Disabling either flag or registering that host-owned generation callback hides the embedded action, but does not change the Console importer or the Template Import API.
:::
### Why disable it?
The most common reason is **cost predictability**. Full template generations can use substantial credits, so a project that opens the assistant up to non-power users may want to offer per-element editing alone. This limits the available workflow, not the maximum cost of each request. Other reasons embedders cite:
- **Latency budget** — keeping every AI turn under a few seconds for a snappier UX.
- **Output consistency** — per-element edits respect the existing design more tightly; full generations re-author large parts of the layout.
- **Plan tier gating** — exposing full template generation only to higher-tier customers, while keeping the per-element assistant on every paid plan. Because this varies per end-user, express it as a [signed feature policy](/builder/latest/security#restricting-features-per-end-user).
## Default behavior
When the AI Assistant is on, full template generation is **enabled by default** — no extra flag needed. You only need to set `features.ai.fullTemplateGeneration` if you specifically want to turn it off while keeping the rest of the assistant available.
## Related
- **[Row](./row.md)** — narrower scope when full-template is overkill.
- **[Text](./text.md)** — single-block edits for text, button, and heading tools.
- **[Pricing](../pricing.md)** — credit cost per request type.
- **[Full vs Simple schemas](/design-schema/schema-forms)** — the assistant reads and writes the compact Simple form of the design JSON; the editor converts to and from the Full form around each turn (the schema-validation step in the pipeline above).
- **[Events & Callbacks](../events-callbacks.md)** — `ai:assistant:on:success` reports the per-turn duration so you can see how much wall-clock time a full template turn costs.
- **[Content Protection](./content-protection.md)** — apply live-mode permissions to every editing scope.
---
## Image(How-it-works)
Use the AI Assistant chat to find existing photos, create custom images, and edit images. The standalone Image Editor keeps a separate chat for editing the image open in its canvas. Image generation and editing require AI Assistant access in both chats. Legacy Magic Image access alone no longer enables AI editing; manual Image Editor tools remain available.
## Find, generate, or edit an image
Open the AI Assistant from the toolbar and describe what you need:
- **Find an existing image:** “Find a photo of a mountain lake.” The assistant prefers your enabled stock libraries for ordinary image requests and shows results with attribution. Choose **Add to design** or **Replace image**, or drag a result into the design.
- **Create a custom image:** “Generate a watercolor turtle swimming underwater.” The assistant creates one image directly, without a style picker or prompt-scoring step. Describe a style in the prompt when you want one.
- **Edit an image:** Select an image in the design, or use **+ → Add files** (or **Add an image** when HTML references are disabled) in chat, then ask “Remove the background.” You can also paste or drop up to 6 PNG, JPEG, WebP, or GIF images totaling no more than 10 MB anywhere over the Assistant panel. Attachments start in selection order. Drag them to reorder, or focus a thumbnail and use the arrow keys. On a touch screen, hold a thumbnail briefly before dragging; swipe to scroll the attachments. Hover or focus a thumbnail to see its number, then refer to “image #1,” “the third image,” or “the last image” in your request.
- **Refine a result:** Choose **Add to prompt** under a result to attach it as a reference, or continue with “Make the background blue.” The assistant uses the recent conversation to understand the follow-up.
You can also paste a public image URL with an instruction such as “Remove the background from `https://example.com/photo.png`.” The assistant checks the image only when editing it. Page links remain page links; a URL without instructions prompts a short clarification. Disabling image uploads also disables pasted-URL image editing; editing selected canvas images and previous results remains available.
Ask for several edits in one request, such as “Make all images black and white.” Each image is edited separately and contributes to the turn’s total credits. Images already completed remain available if another image fails or the request is stopped.
The assistant asks a short question only when the subject or requested change is unclear. Stock search does not silently switch to paid image generation when it cannot find a match.
With an image selected, a request such as “Make the sky blue” targets that image. You can name a different source explicitly, including an attachment number. With nothing selected, describe the existing image and its location: “Remove the background from the product photo below the heading.” You can also specify where a new image belongs, such as “Generate a watercolor house and add it below the welcome paragraph.”
### Drop files into the Assistant
Drag files anywhere over the Assistant, including the conversation or header, or onto the prompt in the Content tab. The drop overlay shows the available actions. Dropping files only stages them; add your instructions and submit when ready. The Content tab stays open until submission, which carries your files and instructions into the Assistant. PNG, JPG/JPEG, WebP, and GIF images use the same uploader and limits as **Add an image**. HTML/HTM references require `features.ai.templateImporter: true` and full-template AI Assistant access. You can attach HTML and images together with **Add files**, or drop them in the same batch. Image uploads still follow `features.ai.image.upload`.
For example: “Use this HTML as inspiration for the colors, keep my existing copy, and replace the hero with image #2.” Or: “Recreate the attached HTML using these two product photos.” The prompt determines whether the assistant adapts the current design or rebuilds it; attaching HTML alone does not change the canvas. With an empty attachment draft, use **Import from HTML or image** for a straight conversion with replacement confirmation.
To place an attached image without sending a prompt, drag its thumbnail onto the design canvas. This uses the original uploaded image, rather than its thumbnail preview.
Attach up to three non-empty HTML files totaling 5 MB, alongside up to six images totaling 10 MB. HTML appears as named file cards; image numbers follow their thumbnail order. Recent successful HTML references are retained for follow-up turns within the same limits. Older references that no longer fit the design context or cannot be prepared are omitted; reattach a reference if it is needed again. Large HTML sources may also exceed the combined design/context limit after cleanup; simplify the source in that case.
HTML source is sent as structured reference data rather than inserted into the prompt text. Scripts and nonvisual markup are removed before AI processing. Embedded image data is prepared through the importer’s project-storage service, including configured project S3 storage; this server-side preparation does not invoke the browser’s `image` callback. Separately attached photos continue to use that callback. The HTML file itself is not uploaded as a public asset.
### Upload storage and limits
Images attached with **Add an image**, paste, or drop use the builder’s configured image uploader. By default, files go to Unlayer’s Amazon S3 storage. A project configured with its own S3 bucket uses that bucket instead. When your plan supports custom storage and you register the [`image` upload callback](/builder/file-storage/custom), the callback handles the file bytes and returns the URL used in the prompt. For returned HTTP(S) URLs, Unlayer does not copy those attachment bytes into its own bucket; it may save the URL in the File Manager. If your callback returns inline `data:` image bytes instead, unchanged placement with HTML references or with generative editing disabled prepares those bytes in project storage. Return a durable HTTPS URL to keep storage entirely in your callback.
When several images are selected, uploads within the queue run one at a time in selection order. The prompt can be sent after all uploads finish. Cancelling a pending attachment stops it from being added to the prompt; it cannot cancel an upload already running inside your callback or storage provider.
Two limits apply:
- Each file must fit your plan’s normal image upload limit, including uploads through a custom callback. This limit is not a public `unlayer.init()` option. Your callback can enforce a smaller limit with `done({ error: 'Your validation message' })`.
- AI operations accept up to six PNG, JPEG, WebP, or GIF references totaling 10 MB. This processing limit still applies with custom storage. The server checks the downloaded bytes for each image operation, including pasted image URLs.
GIF edits use the first frame and return a still image. The uploaded GIF stays unchanged. Its first frame must fit within 25 megapixels and the image-processing byte limit after conversion to PNG. Automatic descriptions also inspect the first frame.
Returned URLs must remain accessible to Unlayer’s AI service for later edits. Private network URLs and expired signed URLs cannot be used. Storage location does not change AI processing: the selected images are sent to the image model provider for the requested operation.
### Apply and store results
Click any image in the conversation to open a larger preview. Close it with the close button, Escape, or by clicking outside.
An edit to a template image is applied to that image after upload, even when it was identified by your prompt instead of selected. Generated images are inserted when you specify a destination. Ask for a preview to keep the result in chat. Attachment-only edits stay in chat unless you ask to place them. For stock search, choose **Add to design** or **Replace image** to apply your chosen result at the requested destination. Generated and edited images go through the same upload callback as the editor's image picker, so [custom file storage](/builder/file-storage/custom) continues to work. Chosen stock photos also use that uploader when added to the design or prompt, so the saved URL belongs to your configured storage. Use **Undo change** below an applied image to restore its previous source or remove a newly inserted image. It applies while the affected image is still eligible for undo; a different loaded design or subsequent manual changes can prevent it. This preserves unrelated edits and does not consume AI credits. The editor’s Undo/Redo controls also remain available.
Stopping a request keeps any images already returned in the conversation. A pending upload does not overwrite a newer manual edit or a different design.
Images upload as soon as you attach them, so they are ready when you submit. Removing a draft attachment does not delete an uploaded file or reverse an embedder's upload callback. Saved images remain available in **Uploads**; generated results also remain in the current chat. The previous Magic Image panel and its Recents view are no longer used.
Pass a stable `user.id` when initializing the builder to attribute image and credit usage to the end user. New images report as `image_generation`; edits report as `image_edit` in the [AI credits usage API](/server/cloud-api/ai-credits).
Use `features.ai.image.model` to choose an image model or leave it unset to let Unlayer pick. Set `features.ai.image.enabled` to `false` to disable image chat and attachments while keeping text/design assistance. The deprecated `features.ai.magicImage: false` also disables image chat unless `image.enabled` is explicitly set. Assistant chat image workflows use AI Assistant access.
### Standalone Image Editor
Double-clicking an image opens the Image Editor modal. Its AI chat edits the current canvas through the shared image service and keeps a separate conversation. AI changes can be undone in the modal before saving. Model and quality settings are shared; the action switches below apply to the builder Assistant chat. See [Image Editor user configuration](/builder/latest/image-editor/configuration#user) for end-user attribution.
## Image Alt Text
Images added or directly changed through AI receive automatic descriptions based on their actual pixels. This includes images applied from the builder Assistant and AI edits saved from its Image Editor modal. Ordinary uploads, manual URL changes, and edits made without AI do not generate descriptions or consume AI credits. An existing description stays unchanged if it is still accurate. Layout or text edits around an unchanged image do not fill in missing alt text or rewrite existing descriptions.
Descriptions are added after the image is applied and use AI Assistant credits. A manual edit, image replacement, language change, or cancellation takes precedence over a pending description. If the image cannot be inspected, no description is invented. Set `features.ai.image.altText: false` to turn automatic descriptions off; explicit requests remain available.
Ask the AI Assistant to add alt text to one image or several images. The description appears in the image's **Alternate Text** field and in the exported HTML's `alt` attribute. This works in the Email, Page, Popup, and Document builders.
### How users access it
With no image selected, open the AI Assistant from the main toolbar and ask _"Generate alt text for the first image."_
To fill missing descriptions throughout the design, ask _"Add missing alt text to all images."_ The assistant inspects the requested images and saves descriptions of what they show. Existing descriptions are preserved. To generate replacements, ask _"Regenerate alt text for all images."_ You can also provide the exact description to use.
The assistant inspects images when you explicitly ask it to generate visual descriptions. Supplied descriptions, clearing, translation, and unrelated edits do not need image inspection. A clear generation request proceeds without an extra confirmation. Inspection adds image processing to the normal AI Assistant credit usage.
A request can inspect up to eight images. For larger designs, work on smaller sections. If an image cannot be inspected, the assistant asks for a description instead of guessing from its filename.
Alt text is optional. Images without descriptions remain valid, and changing the layout preserves existing descriptions. To remove a description, ask the assistant to clear it or empty the **Alternate Text** field manually.
This uses your plan's AI Assistant access and credits; it does not require the legacy Smart Alt Text feature. If the assistant needs more information about an image, provide a description of what it shows. Review the resulting text for accuracy.
The assistant confirms accepted edits after validation. Replies and clarifying questions appear on their own, without an extra no-change notice. If a completed request makes no changes and has no reply or choices to show, **No changes were made to the design** appears as a message bubble. Time and credit usage remain below the reply. You can always edit **Alternate Text** manually.
| With a reply | Without a reply |
| ------------------------------------------------ | ------------------------------------------- |
| | |
### Why alt text matters
- **Accessibility** — screen readers use alt text to describe images to users with visual impairments.
- **Deliverability** — email clients show alt text when images fail to load (or are blocked by default), which is common in inbox previews.
## Configure image actions
Each image action is enabled by default when the editor session has AI Assistant access. All configuration below is optional; existing initialization code continues to work. The [Assistant API](/server/cloud-api/images#images-in-an-assistant-conversation) uses the same `features.ai.image` option names for supported image actions. Control them independently in `unlayer.init()`:
```javascript
unlayer.init({
features: {
ai: {
assistant: true,
image: {
upload: true,
generation: true,
editing: true,
search: true,
enableDesignImageTargeting: true,
altText: true,
},
templateImporter: false,
},
stockImages: true,
},
});
```
- `image.upload` controls the **Add an image** picker, paste, drop, and pasted-URL edits. Uploads can be used as references or placed unchanged even when generative editing is disabled. It does not prevent editing a canvas image or an earlier chat result.
- `image.generation` controls creation of new custom images.
- `image.editing` controls changes to existing images. **Add to prompt** follows the upload control.
- `image.search` controls online search in the Assistant. Search also requires stock-image access and `features.stockImages`; setting the latter to `false` disables online search throughout the editor.
- `image.enableDesignImageTargeting` controls whether image actions can use existing design images and resolve image replacement or insertion destinations. It defaults to `true`; set it to `false` to keep generated and edited images in chat until the user applies them. Attachments and previous results can still be edited.
- `image.safeSearch` controls safe search for online images. It defaults to `features.stockImages.safeSearch`, or `true` when that is unset.
- `image.altText` controls automatic descriptions for images added or directly changed through AI, including AI edits saved from the builder's Image Editor modal. An explicit `features.ai.smartImageAltText: false` also disables them.
- `image.enabled: false` disables image actions and automatic descriptions in the builder Assistant chat. The standalone Image Editor keeps its own AI editing configuration; `image.altText` controls automatic descriptions when its AI edits are saved back to the builder. Set `features.imageEditor: false` to hide the Image Editor modal independently; its availability also depends on your plan.
The **+** button appears only when at least one attachment action is available. HTML references and **Import from HTML or image** use `features.ai.templateImporter`, which defaults to `false`, and require full-template AI access. They also follow `features.ai.fullTemplateGeneration`. **Add files** accepts HTML and images together when both capabilities are enabled; otherwise the picker accepts only the enabled types. Dropped HTML stages a reference, and dropped images attach to chat when uploads are enabled. If uploads are disabled and import is enabled, dropping a single supported image stages an import. The explicit import action appears only while the reference draft is empty. Adding references to a staged import keeps its source and instructions in the normal conversation. Both attachment actions are hidden when the host owns generation through `ai:assistant:generate`. See [embedded template import](/ai/template-importer#embedded-builder-access).
## Related
- **[File Manager](/builder/file-manager)** — where generated images are stored.
- **[AI Assistant overview](../overview.md)** — what the assistant does and where users find it.
---
## Row
When the user selects a **Row**, the AI Assistant operates on the whole container — every column, every content block inside it — in a single turn. Useful for changes that need to be consistent across multiple blocks at once: translation, restyling, swapping layouts, regenerating around a new product.
## How users access it
- Select the row on the canvas — the layer control surfaces a Sparkles button. Clicking it opens the AI Assistant scoped to that row.
- Or open the AI Assistant chat and ask while the row is selected (_"translate this entire row to Spanish"_, _"restyle this row to be dark mode"_).
## What it can do
- **Translate the whole row** — _"translate this row to French, keep the merge tags."_ Every content block — text, button labels, headings, alt text — comes back in the target language.
- **Restyle / re-tone** — _"make this row darker and more enterprise"_, _"give this row a friendlier voice."_ The assistant rewrites copy across the row to match.
- **Swap the layout** — _"turn this row into a 2-column hero with the image on the left."_ The assistant restructures cells and columns while preserving the underlying content.
- **Regenerate content** — _"keep the layout, but redo the copy as if this is for Black Friday."_ Layout stays, content blocks come back rewritten.
- **Targeted edits across multiple blocks** — _"replace every CTA in this row with a single one at the bottom"_, _"swap both images for product shots."_
## When to use it instead of per-block edits
Per-block edits (text, button, heading, image) are faster and cheaper for single-element tweaks. Reach for row-level edits when:
- You need **consistency** across blocks — same tone, same translation, same restyle applied to several content items at once.
- You need to **restructure** the row's layout, not just its copy.
- You're doing a **batch** of related edits and would otherwise click between blocks one at a time.
For changes that touch the whole design (cross-row restyle, regenerate entire email), use [Full Template](./full-template.md) instead.
## Related
- **[Text](./text.md)** — single-block edits for text, button, and heading tools.
- **[Image](./image.md)** — image generation, editing, and alt text.
- **[Full Template](./full-template.md)** — whole-design edits in one turn.
- **[AI Assistant overview](../overview.md)** — what the assistant does and where users find it.
---
## Text(How-it-works)
The AI Assistant treats **Text**, **Button**, and **Heading** as one family of text tools. When asked to write or rework any of them — through a freeform prompt, a layer-control Sparkles button, or a one-tap quick action — the behavior is the same:
- It reads the surrounding section (heading, body, image alt text, nearby copy) and writes content that fits the context.
- It preserves inline formatting and merge tags. Bold spans, links, and `{{ merge_tags }}` come back intact.
- It returns suggestions inline as clickable pills the user can pick from.
The only thing that changes per tool is the expected output: a paragraph for Text, a short label for Button, a punchy line for Heading. Everything else on this page applies to all three.
## How users access it
After dropping or selecting a Text, Button, or Heading content block, the user can either:
- Open the AI Assistant chat and ask for what they want (_"shorten this paragraph and make it friendlier"_, _"suggest a CTA for this section"_, _"write me a heading for this section"_).
- Select the block and click the Sparkles button on the layer control to ask scoped to that element.
- On Text specifically: open the inline quick-action menu and pick a one-tap action (Fix Spelling & Grammar, Summarize Text, Expand Text, Make It Friendly, Make It Formal).
## Common rewrites
The quick-action menu on Text covers the most common rewrites in one click. Buttons and headings have the same intents available via chat:
| Intent | What it does |
| ---------------------- | ------------------------------------------------------------------- |
| Fix Spelling & Grammar | Corrects typos, agreement, punctuation. Preserves voice and length. |
| Expand Text | Adds detail and examples to make a short passage longer. |
| Summarize Text | Compresses a long passage into a tighter summary. |
| Rephrase Text | Same meaning, different words — useful for breaking up repetition. |
| Make It Friendly | Casual, warm tone shift. |
| Make It Formal | Professional, businesslike tone shift. |
## Ask for multiple options
Ask the assistant for a few variations in a single turn — _"give me 5 friendlier alternatives for this paragraph"_, _"give me 5 CTA options for this section"_, _"give me 5 heading options for this section"_ — and it returns each suggestion as a clickable pill in the chat. Click a pill to apply that suggestion to the selected block; the others stay around so the user can compare and pick a different one without re-prompting.
## Example prompts
Freeform chat goes beyond the quick-action menu — anything you can describe, the assistant can try. A few that work well across the three tools:
- _"Shorten this and make it friendlier."_
- _"Match the tone of the heading above."_
- _"Rewrite for a non-technical reader."_
- _"Translate to Spanish, keep the merge tags intact."_
- _"Suggest a CTA for this section — under 4 words."_
- _"Give me 3 heading options that lead with a benefit."_
## Related
- **[Image](./image.md)** — image generation, editing, and alt text.
- **[Custom Tools](./custom-tool.md)** — how the assistant works with embedder-defined custom tools.
- **[Row](./row.md)** — multi-block edits in one turn.
- **[AI Assistant overview](../overview.md)** — what the assistant does and where users find it.
---
## AI Assistant(Assistant)
The AI Assistant is a chat-based assistant built into the builder. Users describe what they want — _"translate this row to Spanish"_, _"generate a Black Friday hero"_, _"shorten this paragraph and make it friendlier"_ — and the assistant streams the changes directly into the design.
The assistant operates at any level of the design tree — full template, row, text, image, and your own custom tools. It detects the language the user typed and uses it for chat replies, even when the user asks it to translate design copy into another language. Design copy follows the requested target language, or the existing design language when no target is specified.
## Where users find it
There are three entry points:
- **AI Assistant panel** — click the Sparkles button in the editor's top toolbar; a dedicated chat panel slides in on the side, with one conversation shared across the design for the current session. Selecting another element keeps the history visible; new prompts target the current selection. [Chat history scope](./setup.md#optional-chat-history-scope) can restore separate element threads.
- **Layer control popover** — when a user selects an element, the layer control surfaces a Sparkles button. Clicking it opens the assistant scoped to that selection.
- **Content tools input** — a prompt input pinned below the content tools in the Content tab. Type a request, add files with **+**, or drop files onto the prompt without leaving the tab. Submitting opens the AI Assistant and starts the turn, scoped to the selected element or the full design when nothing is selected.
An optional **Import from HTML or image** action can appear in the Content input's **+** menu and in the Assistant composer at the full-template level. It is hidden by default: set `features.ai.templateImporter` to `true` for the editor sessions that should offer it. End-users attach an HTML file or screenshot and optionally describe how it should be recreated. See [AI Template Importer → Embedded builder access](/ai/template-importer#embedded-builder-access).
The **+** menu also offers **Add files** when HTML references are enabled, or **Add an image** when only image uploads are enabled. The picker accepts only the enabled file types. Attach up to six image references, reorder them, and refer to their numbers in a prompt. Files and instructions added in the Content tab carry into the Assistant when you submit. Stock search, custom generation, and image edits happen in this conversation; the old Magic Image modal is no longer used. See [Images](./how-it-works/image.md) for configuration, application, and undo behavior.
## How it works
1. The user types a prompt (and optionally selects an element to scope the request).
2. The editor sends the prompt and the relevant slice of the design to Unlayer's AI service.
3. The service streams back text, design operations, and image results when requested.
4. The editor applies design operations as they arrive — the canvas updates live.
5. The user can stop generation at any time, undo the result, or follow up with another prompt.
Template Importer turns use the same Assistant conversation and lifecycle
events, but return one completed design instead of streaming design operations.
## Reliability & uptime
Unlayer's AI service runs a multi-provider routing layer with an automatic fallback chain — if the primary model is rate-limited, overloaded, unavailable, or returns another transient provider error, the request transparently retries against a backup model. Users don't see the retry; the turn just continues. Errors that require user input or configuration changes, such as invalid API keys or invalid request bodies, fail immediately.
## Quick start
Initialize the editor with your project, identify the current end-user, and
enable the AI Assistant. `user.id` is required for the assistant to appear and
for AI requests to succeed.
```javascript
unlayer.init({
id: 'editor-container',
projectId: 1234, // Replace with your numeric Unlayer Project ID
user: {
id: 'user-123', // Required for the AI Assistant
},
features: {
ai: {
enabled: true,
assistant: true,
},
},
});
```
See [Setup](./setup.md) for the full reference. To also offer the Template
Importer in an embed, add `templateImporter: true` to `features.ai` — it is off
by default; see
[AI Template Importer → Embedded builder access](/ai/template-importer#embedded-builder-access).
## What's in this section
- **[How it works](./how-it-works/full-template.md)** — what the assistant does at each scope: full template, row/header/footer, text, image, and custom tools.
- **[Setup](./setup.md)** — enable the assistant in your embed.
- **[Pricing](./pricing.md)** — how AI usage is billed.
- **[Examples](./examples.md)** — live demos and starter snippets.
- **[Events & Callbacks](./events-callbacks.md)** — track every AI turn and forward it to your analytics pipeline.
- **[FAQ & Troubleshooting](./faq.md)** — answers to the most common questions and failure modes.
## Privacy & data
User prompts, relevant design context, image attachments and editing references, and any HTML or image source uploaded through the Template Importer are sent to Unlayer's AI service. The service routes requests to model providers including OpenAI, Anthropic, and Google. An image operation can use a different provider from the surrounding conversation. Imported source bytes are omitted from AI lifecycle callbacks and lifecycle logs, but they still have to be transmitted to perform the import. Inputs are **not used to train models**. Unlayer logs prompts for short-term debugging and abuse prevention; model providers may apply their own retention windows per their published terms.
For data-handling specifics tied to your contract — data residency, retention, zero-retention agreements, DPAs, or the up-to-date subprocessor list — contact your account manager.
See also: [FAQ → Privacy & data](./faq.md#privacy--data) and the per-user opt-out pattern in [Setup → Disabling per init](./setup.md#disabling-per-init).
## Related
- **[End-User AI Credits & Upsell](/ai/credit-upsell)** — show end-users their remaining AI credit balance and route them through your host-managed purchase flow.
---
_**AI can make mistakes.** The AI Assistant can produce inaccurate, incomplete, or misleading content. Always review generated copy, links, prices, claims, and translations before sending or publishing. Check important info._
---
## Pricing
Unlayer measures AI usage in credits. Each workspace has one shared usage
bucket, so every AI feature, project, and end user in that workspace contributes
to the same balance. A request uses credits according to the work performed;
there is no fixed per-request charge.
For current plan allowances and add-on pricing, see
[unlayer.com/pricing](https://unlayer.com/pricing). To forecast monthly usage
from your number of end users, use the
[AI Credit Estimator](./cost-estimator.md).
:::tip One-time welcome credits
Eligible workspaces see a one-time 5,000-credit welcome offer in Billing.
Availability follows the workspace's current plan, subscription status, and AI
feature eligibility; current Free and legacy plans do not qualify. Eligibility
to buy a paid credit pack is separate. The grant does not unlock AI features
that the workspace's plan excludes.
:::
## What is an AI Credit?
An AI Credit is a **cost-based usage unit**, not a large language model (LLM)
token or a fixed number of requests. Tokens are pieces of content processed by
a model. Unlayer calculates the cost of that work using the applicable model
rates, then converts it into credits. Input, output, and cached input can have
different rates, so the same number of tokens does not always use the same
number of credits.
## What affects text-edit cost?
A text edit can process more than the prompt and selected text. It can also
include the Assistant's instructions, surrounding email copy or design data,
[Brand Context](./customization/brand-guidelines.md), and conversation history.
Design context can account for much more input than the short block being
edited; shortening the prompt alone does not bound the cost.
Visible word count and canvas size do not measure the amount of data a model
processes. An image embedded as a data URL, in an image block or inside text,
can add substantial input. Reproducing unchanged image data in generated
content can also add output usage. Custom-tool configuration can affect which
model handles a request, even when editing a built-in text block.
Generated text, design changes, and model reasoning also contribute to usage.
Model routing chooses how to handle the request, and a turn can involve several
model calls, including retries or a switch to another model. Their work
contributes to the total, not just the final visible reply. Creating cached
context and reusing it have different costs; changing the design can require
creating that context again. Repeating a prompt does not guarantee the same
credit charge.
## Plan for variable usage {#typical-credit-usage}
A short request is not a low-cost guarantee. Use these as rough orientation,
not a per-request price or a maximum:
- A short text or block edit can use **hundreds of credits** when it processes
substantial design context or needs more model work. Small, simple requests
can use much less.
- Generating or editing an image usually uses **dozens to hundreds of credits**,
depending on the model, resolution, prompt, and reference images.
- Full-template generation and HTML or website imports usually use **hundreds
to a couple thousand credits**.
The editor shows the credits used after each completed Assistant request. For a
complete billing record, use the server-side
[AI Credits API and webhooks](/server/cloud-api/ai-credits).
Before setting end-user allowances, measure representative prompts on both
small and large designs, with your saved Brand Context and with it explicitly
disabled. Include new conversations and follow-up turns, and repeat each case
to see variation. The Assistant's displayed total is useful for a completed
turn; use the server-side usage record for your billing ledger. See
[host-managed allowances](/ai/credit-upsell) for keeping your own
per-user balance current.
Image turns in the Assistant include both the image operations and the conversation
work. A request to edit several images performs and bills each image edit separately. Image input, image output, and text are priced separately using the
provider's reported usage when available. A clarification can use text credits
without generating an image. Uploading, reordering, previewing, and adding results to the prompt do not
run an image operation. **Undo change** is also local and free. Applying an image
can trigger a separate paid alt-text description when automatic alt text is enabled.
The direct `POST /v3/images/generate` endpoint and standalone Image Editor do not
add the builder Assistant's conversation-model work.
Supported grayscale conversions and single-color replacements in flat logos do
not use an image model or charge image-generation credits. Conversation and
image-description usage still apply. Unsupported replacements keep the original;
an opaque result for a request requiring transparency is rejected without an
image-credit charge.
## Protected edits that make no changes
An unchanged design does not by itself make a turn free. A completed request
can use credits even when the Assistant finds no edit is needed. Advisory
answers and clarification questions can also be useful results without
changing the design. The automatic waiver below applies only to the verified
protected-edit case.
In `designMode: 'live'`, an edit request uses **zero AI credits** when the
server verifies that template permissions prevented the edit, the resulting
design is unchanged, and the request would normally use no more than 200
credits. Provider usage is still recorded internally. If fallback models were
used, the 200-credit ceiling applies to the combined cost of every attempt.
With the whole canvas selected, this rule applies regardless of the request's
language—for example, both “remove the footer” and “remova o rodapé”.
Requests above that ceiling use credits normally. When some edits are allowed,
the Assistant keeps those edits, preserves protected content, and charges for
the completed request. Ordinary answers, clarification questions, errors, and
edits in `designMode: 'edit'` also retain their normal billing behavior. A host
callback rejecting an otherwise valid edit does not waive credits.
## Capped and uncapped workspaces
Console frames AI usage against a positive allowance. For example, with 7,400
credits used from a 10,000-credit allowance, the Billing tile shows **"2,600
left of 10,000"**, while the project Usage page shows **"7,400 / 10,000"**. A
plan or add-on allowance is shown even when enforcement is in shadow mode; an
enforced workspace whose only positive allocation is a claimed bonus is shown
the same way.
Console's allowance display is not an enforcement signal. The server balance
API sets `is_capped` to `true` only when enforcement is enabled, and the editor
balance indicator and threshold/exhausted webhooks use the same enforcement
gate. A shadow workspace can therefore show a real remaining allowance in
Console while returning `is_capped: false`, keeping the editor indicator hidden,
continuing AI after the allowance is used, and emitting no threshold or
exhausted webhooks.
Some older plans are grandfathered. When they have no plan or add-on AI
allowance, Console shows only the credits used after usage begins, with no
remaining balance or exhausted state. A one-time grant can top up a capped
allowance, but it does not create a cap for a grandfathered uncapped workspace.
The **AI Credits** tile carries an **information icon**. Hover or focus it to see
what the number counts and whether an allowance bounds it.
## See the workspace balance
When the editor session has a complete, active, enforced balance, the Assistant
header shows the credits used and remaining in the current monthly window.
Annual subscriptions still use monthly credit windows. Use the refresh action
in the balance popover to include activity from other sessions and AI features.
Because this indicator follows enforcement, it remains hidden for shadow-mode
workspaces even when Console shows a positive allowance.
The balance is optional. White-label embeds without an active usage period,
period dates, or complete balance data do not show an empty placeholder.
### Choose where the credit link goes
For an embedded editor, set `features.ai.creditsUrl` to your own billing, usage,
or help page. It must be an absolute HTTP or HTTPS URL:
```javascript
unlayer.init({
features: {
ai: {
creditsUrl: 'https://app.example.com/settings/ai-credits',
},
},
});
```
This changes the destination of workspace credit links, not metering or
enforcement. In Console, a workspace Billing URL takes priority when one is
available.
For a separate host-managed per-user allowance, use `credits.ai.purchaseUrl`
or the `credits:purchase` callback instead. See
[End-User AI Credits & Upsell](/ai/credit-upsell#keep-the-purchase-inside-the-builder).
## When credits reach zero
This section applies only when enforcement is enabled. Shadow-mode workspaces
are never paused by metered credit usage, even if Console displays a positive
allowance.
The default behavior is `show_error`: AI controls remain visible, but the
editor stops new generations and explains that the workspace is out of credits.
You can instead hide AI controls in embedded editors by setting the project's
`exhaustion_behavior` to `disable`:
```http
PUT /v3/projects/:id/ai-credits/settings
Authorization: Bearer unlayer_sk_...
Content-Type: application/json
{
"exhaustion_behavior": "disable"
}
```
Use `show_error` to restore the default. Read the current value with
`GET /v3/projects/:id/ai-credits/settings`. See
[AI Credits API and webhooks](/server/cloud-api/ai-credits#update-settings) for
the full settings contract.
Recurring plan and credit-pack capacity resets at its next monthly boundary.
One-time welcome credits do not refill. Eligible current plans with an active
paid subscription can add capacity from Console → **Billing** → **Add-ons**;
trial or legacy workspaces may need to change plans before self-service packs
are available.
### Customize the exhaustion message
Use the normal [translation override](/builder/localization) mechanism. For an
embedded end user who cannot manage workspace billing, customize the Assistant
title, the feature-specific message, and the generic fallback:
```javascript
unlayer.init({
locale: 'en-US',
translations: {
'en-US': {
'labels.ai.assistant.credits_exhausted.title':
'AI credits are currently unavailable',
'labels.usage_limit.errors.credits_exhausted_contact_owner':
'Your {feature} credits are used up. Contact your account owner to continue.',
'labels.usage_limit.errors.credits_exhausted_contact_owner_generic':
'Your credits are used up. Contact your account owner to continue.',
},
},
});
```
Keep `{feature}` in the message if you want the editor to insert the localized
feature name, such as “AI generation.” The generic fallback is used when the
feature is missing or unrecognized; it does not receive a `{feature}` value.
These keys apply to workspace exhaustion. The separate host-managed per-user
notice uses `labels.credits.*`; see
[credit notice translations](/ai/credit-upsell#customize-credit-notice-text).
## Reset and expiration
Plan and recurring add-on credits are recurring allowances. Unused credits do
not accumulate when a new allowance window starts. The balance API returns
`reset_date` while it can resolve an active future billing window, and
`null` otherwise. Use the returned value instead of calculating it from the
subscription term.
A future `reset_date` is not a promise of renewal: when the subscription is
scheduled to end with that window, it marks expiration instead. See the
[balance response](/server/cloud-api/ai-credits#get-credit-balance).
Some eligible workspaces are offered a one-time **5,000-credit welcome bonus**
in Billing. It is not granted on first AI use; someone with billing access must
select **Claim now**. The card shows the exact expiration date before the claim.
The bonus normally expires at the next monthly credit reset, so it does not
carry into a new window.
Billing offers the welcome bonus only when the workspace's current plan,
subscription status, and AI feature eligibility qualify. Current Free and
legacy plans do not qualify. Eligibility to buy a paid credit pack is separate.
The bonus shares the workspace credit bucket and does not unlock excluded AI
features.
## Automatic top-ups
:::info Rolling out
Automatic top-ups are being rolled out. Until they reach your workspace, the
card described here does not appear under the credit packs and the credit
packs above remain the way to add credits.
:::
Workspaces on a current paid plan can let Unlayer buy more of a credit pack
automatically when that balance runs low, up to a spending limit you set for
each monthly credit window. Every credit pack with a top-up gets the same
control — AI Credits, Export Credits, Inbox Previews Credits and Bandwidth
Credits — and the card lists each add-on your plan can use and whose cap is
enforced on the workspace. Turn it on from **Console → Billing → Usage &
add-ons**, under the credit packs.
One master switch turns automatic top-ups on for the workspace. Under it,
every add-on that can be topped up has a row of its own:
- **The add-on's switch** — an add-on is bought automatically only while its
own switch is on. The first time you open the card, every add-on it offers
is pre-selected, and saving records your decision for each one. An add-on
that appears on the card later — because it became available on your plan or
its cap became enforced — starts switched off until you turn it on, so
nothing is ever bought that you did not see and accept.
- **Budget per period** — the most automatic top-ups may spend on that add-on
in one monthly credit window, from $5 to $1,000 in $5 steps ($100 to start).
It is a hard stop: once the budget is reached nothing more is bought for that
add-on until the window resets, and your billing contact is emailed with a
projection of how far the remaining budget reaches so you can raise it in
time.
The footer of the card shows what was spent this period and the most the
budgets you have set could charge.
How much each top-up buys is not a setting; **How it works** on the card spells
it out. Once an hour, Unlayer checks how fast the workspace is using each
add-on. When an add-on would run out within a day at that pace, it buys enough
to last about three days of usage, in $5 steps, never sized past the end of the
current period and never past that add-on's budget.
Purchases are sized to your usage, not sold as fixed packs. Each one buys
enough of the pack, in $5 steps at the same rate as the recurring pack, to
cover about three days at the observed pace, and never sized past the end of
the current period. Heavy usage therefore produces several small charges through
the month rather than one large one. When the period resets, the most that goes
unused is a few days' worth of usage, or at most one $5 step if a pack runs out
near the end of the period. **Unused credits expire when your period resets**;
nothing carries over.
A few things to know:
- Each top-up is a one-off charge to the payment method on file and appears as
its own invoice, listed under the pack's name (for example **AI Credits**)
with the number of $5 steps bought. When more than one pack is topped up in
the same run, each pack is charged on its own invoice.
- Automatic top-ups only run for a pack whose cap is actually enforced on the
workspace. They are not offered on Free, trialing, cancelled, or legacy
plans, and require a stored payment method.
- Evaluation is hourly and driven by activity. A workspace that is not using a
pack is not evaluated for it and is never charged. A workspace that has run
out is evaluated as long as someone keeps trying, so the first request after
a period reset on a plan with no included credits may be refused until the
next hourly run buys more.
- A pack that has run out is always bought at least one $5 step while its
switch is on and budget remains, even late in the period when part of that
step will expire unused. The only times nothing is bought are the final
hours of a period, and when the balance on hand already lasts to the reset
at the observed pace.
- On plans that include none of a pack's credits, the budget that pack spends
against is effectively the workspace's monthly spend on it.
- Purchased credits appear in the balance and usage APIs like any other credit,
and in the Console usage page as **purchased credits** with their expiry date.
- While automatic top-ups are buying a pack for you, its usage alerts (for
example "Your AI credits are running low") are not sent, because every
top-up would set them off again. You get the top-up emails instead: each
purchase, 80% of the budget used, and the budget reached. Once the budget is
reached or automatic top-ups are off, the usage alerts return.
- If a charge is declined, nothing is added, the charge is not retried, and
automatic top-ups are switched off for the workspace until someone with
billing access updates the payment method and turns them back on. Your
billing contact is emailed.
- Turning automatic top-ups off — for the workspace or for one pack — takes
effect immediately. Credits already bought stay until their expiry.
- Every purchase is listed under **Recent top-ups** on the same Billing page,
with the date, the add-on, what was added and what was charged. The invoice
itself is on the Invoices tab.
Automatic top-ups and credit packs can be combined: packs raise the recurring
allowance every window, and top-ups cover bursts beyond it.
## Development and staging
There is no separate unmetered development tier. A dev or staging project uses
the shared allowance of its workspace. To measure a workflow before launch,
run it in a test project and inspect the request result or the usage API.
Grandfathered uncapped workspaces continue to meter that usage without pausing
requests or creating overage charges.
If you resell AI, keep each end user's allowance and reset schedule in your own
backend. The builder can display that state, but it does not replace backend
enforcement. See [End-User AI Credits & Upsell](/ai/credit-upsell).
## Disable all AI features
```javascript
unlayer.init({
features: {
ai: false,
},
});
```
---
## Setup
The AI Assistant appears in the editor's mode switcher when these requirements
are met:
- **Plan** — your project must be on a paid plan that includes the AI Assistant. Plans are managed in [Console](https://console.unlayer.com). If the project isn't on an eligible plan, the assistant stays hidden regardless of the feature flags.
- **Project** — pass the numeric Unlayer Project ID as `projectId`.
- **Feature flags** — neither `features.ai.enabled` nor `features.ai.assistant` can be `false`.
- **End-user identification** — the init must identify the current end-user by passing a `user` object with an `id`. Without it, the assistant stays hidden and AI requests are rejected by the server. See [End-User Identification](/builder/end-user-identification).
:::warning End-user id required
Without `user.id`, the AI Assistant doesn't appear at all, and end users see no
error. Pass a stable id for the signed-in end user on every `unlayer.init()`
call.
:::
## Minimum config
Use one complete initialization that includes the project, end-user, and AI
Assistant flags:
```javascript
unlayer.init({
id: 'editor-container',
projectId: 1234, // Replace with your numeric Unlayer Project ID
user: {
id: 'user-123', // Required for the AI Assistant
},
features: {
ai: {
enabled: true,
assistant: true,
},
},
});
```
Don't have a Project ID yet? Sign in to the [Developer Console](https://console.unlayer.com/), create a project, and copy the ID from **Project > Settings**. The full walkthrough — adding the embed script, creating the container, and finding the Project ID — is on the [Installation](/builder/installation#where-to-get-the-project-id) page.
## Verifying it's enabled
When these requirements are met, the **AI Assistant** becomes available from the editor's mode switcher; selecting it opens a dedicated chat panel on the side of the canvas.
If the assistant doesn't appear:
- Confirm the init passes a `user` object with an `id`. The assistant is hidden when no end user is identified. When that's the only thing missing, recent editor versions log this warning in the browser console:
```text
[unlayer] AI Assistant is hidden because unlayer.init() was called without `user.id`. Pass `user: { id }` to identify the end user. See https://docs.unlayer.com/builder/end-user-identification
```
See [End-User Identification](/builder/end-user-identification).
- Check that the project's plan includes the AI Assistant. You can see the plan in [Console](https://console.unlayer.com) or contact support.
- Confirm neither `features.ai.enabled` nor `features.ai.assistant` is
`false`.
## Testing in development
Credits are pooled at the **workspace** level, so dev, staging, and production
projects in the same workspace share one monthly usage bucket. There is no
separate unmetered dev tier. If Billing offers your workspace a one-time
5,000-credit welcome bonus, someone with billing access must claim it; the card
shows its expiration date before the claim. The offer appears only when the
current plan, subscription status, and AI feature eligibility qualify; current
Free and legacy plans do not qualify. Eligibility to buy a paid credit pack is
separate, and the grant does not unlock AI features that the plan excludes.
Grandfathered uncapped workspaces keep metering AI without pausing requests or
creating overage charges. See [Pricing](./pricing.md).
## Disabling per init
Set `features.ai.assistant: false` on a specific `unlayer.init` call to hide the assistant in that editor instance only — useful for embedding the same project in multiple surfaces and wanting the assistant off in some of them.
```javascript
unlayer.init({
features: {
ai: {
enabled: true,
assistant: false,
},
},
});
```
This applies to everyone who loads that editor. To allow the assistant for some end-users and not others, sign the permission on your own server and pass it as `user.featurePolicyToken` — see [Restricting Features Per End-User](/builder/latest/security#restricting-features-per-end-user).
## Optional: Chat history scope
The Assistant shares one conversation across the current design by default. Selecting another
button, heading, image, or row keeps the history visible, and the next prompt targets the current
selection. Earlier messages remain available as context. **New chat** clears the conversation;
loading a different design or reloading the editor also clears it. History is kept only for the
current editor session.
To restore a separate conversation for each element, set the optional `chatHistoryScope`:
```javascript
unlayer.init({
projectId: 1234,
user: { id: 'user-123' },
features: {
ai: { chatHistoryScope: 'element' }, // 'design' is the default
},
});
```
This setting changes conversation history only. It does not grant AI access or change which
selected element an edit targets. Stopping a running turn still stops the original request even
if the selection changes; an image's **Undo change** action still restores its original target.
## Optional: Image actions
Image generation and editing are available with AI Assistant access. The `features.ai.image` object and every option inside it are optional; existing initialization code continues to work. To keep text/design assistance while disabling image actions:
```javascript
unlayer.init({
projectId: 1234,
user: { id: 'user-123' },
features: {
ai: { enabled: true, assistant: true, image: { enabled: false } },
},
});
```
Uploads, generation, editing, online search, automatic alt text, and design image targeting each have their own controls. Online search also requires stock-image access. See [Configure image actions](./how-it-works/image.md#configure-image-actions) for the full configuration and how the attachment menu interacts with template import.
## Optional: Template Importer
`features.ai.templateImporter` adds an **Import from HTML or image** action to
the full-template Assistant composer. It defaults to `false`, so it is off in
the minimum config above, and it also needs `features.ai.fullTemplateGeneration`
not to be `false`. Set it per `unlayer.init` call for the sessions that should
offer imports. See
[AI Template Importer → Embedded builder access](/ai/template-importer#embedded-builder-access).
## Related
- **[FAQ & Troubleshooting](./faq.md)** — common questions about visibility, plans, opt-out, and dev credits.
- **[AI Template Importer](/ai/template-importer)** — offering HTML and screenshot imports inside the embedded Assistant.
---
## End-User Credits
Use the `credits` configuration to show the current end user's host-managed
allowance inside the builder. The builder can warn when the allowance is low,
block the relevant action when it is exhausted, and open your purchase flow
without sending the end user away.
:::info Requirements
Use a current host script and a builder version that supports `credits`,
`credits:purchase`, and `setCredits`. See [Version compatibility](#version-compatibility)
before using a version-locked builder. AI feature access still follows your
project's plan; see [AI Assistant setup](/ai/assistant/setup).
:::
This is a UI and client-side preflight contract. Your application owns the
end-user ledger, pricing, resets, purchases, and backend enforcement. Unlayer
continues to meter and enforce the workspace's total allowance separately. A
value supplied here cannot increase the workspace's server-side entitlement.
It also cannot secure a generation endpoint by itself: treat the browser state
as a soft UI gate and enforce the same end-user allowance in your backend.
## Configure an end-user allowance
Pass a complete snapshot for the current end user's AI allowance:
```javascript
unlayer.init({
id: 'editor',
projectId: 1234,
user: { id: 'customer-42' },
credits: {
ai: {
limit: 100,
used: 80,
disabled: false,
lowBalanceThresholdPercentage: 80,
unitLabel: 'credits',
purchaseUrl: 'https://app.example.com/billing/ai',
},
},
});
```
Use the single `ai` allowance across AI Assistant, Image Editor AI editing,
and AI Template Importer. The display hooks run inside the builder; a direct
`POST /v3/templates/import` call does not receive browser-side `unlayer.init()`
configuration. Enforce the same end-user allowance in your backend before
calling the import API, then refresh any open builder with `setCredits`.
| Field | Type | Description |
| ------------------------------- | ---------------- | --------------------------------------------------------------------------------------------- |
| `limit` | `number \| null` | Total host allowance. Use `null` for an explicitly uncapped end user. |
| `used` | `number` | Amount of the host allowance already consumed. |
| `disabled` | `boolean` | Optional host override that blocks the resource regardless of the numeric balance. |
| `lowBalanceThresholdPercentage` | `number` | Optional consumed percentage for the low-balance notice, from `0` to `100`. Defaults to `80`. |
| `unitLabel` | `string` | Optional white-label display unit, such as `credits` or `messages`. Defaults to `credits`. |
| `purchaseUrl` | `string` | Optional absolute HTTP(S) link-out fallback when no purchase callback is registered. |
`limit` is the total allowance, not the remaining balance. For example,
`limit: 100` and `used: 80` means 20 remain.
When an AI Assistant conversation is empty, an exhausted allowance displays a
full blocking state. If the allowance becomes exhausted after the end user has
started a conversation, the builder keeps the conversation visible, displays
the exhausted notice above it, and disables further prompts. A successful
purchase result or permissible `setCredits` update removes the notice and
re-enables the prompt without clearing the conversation.
The same allowance applies to the Image Editor. `setCredits` updates it while
open; blocked AI credits leave Crop, Resize, Filter, and other non-AI tools
available.
Omit a resource when you do not maintain an end-user allowance for it. The
builder then falls back to Unlayer's server-side workspace enforcement; it does
not grant unlimited access. If a resource is present but its required fields
are missing or invalid, the builder fails closed and blocks it until you send a
valid snapshot.
When host-managed AI credits are present, that end-user snapshot is the
builder's display source of truth and the workspace balance meter is hidden.
The workspace balance is shown as the fallback when host-managed credits are
omitted. Unlayer's backend still enforces the workspace balance in both cases.
## Keep the purchase inside the builder
Register `credits:purchase` to open your own checkout modal or purchase UI.
The recommended form returns a result, so an asynchronous checkout can remain
open for as long as payment requires:
```javascript
unlayer.registerCallback('credits:purchase', async function (request) {
try {
const result = await openCreditCheckout({
idempotencyKey: request.requestId,
resource: request.resource,
reason: request.reason,
});
if (!result.purchased) {
return { status: 'cancelled' };
}
const freshCredits = await getEndUserCredits(request.resource);
return {
status: 'success',
credits: freshCredits,
};
} catch (error) {
return {
status: 'error',
message: 'We could not complete the purchase. Please try again.',
};
}
});
```
The request contains:
- `requestId`: a unique purchase-attempt ID suitable for use as an
idempotency key.
- `resource`: `ai`.
- `reason`: `low_balance`, `exhausted`, or `disabled`.
- `credits`: the snapshot currently rendered by the builder.
Complete the request exactly once. Either return (or resolve with) one of these
results, as above, or use the callback form and pass the result to `done`:
```javascript
unlayer.registerCallback('credits:purchase', function (request, done) {
openCreditCheckout({ idempotencyKey: request.requestId })
.then((result) => {
done(
result.purchased
? { status: 'success', credits: result.credits }
: { status: 'cancelled' },
);
})
.catch(() => done({ status: 'error' }));
});
```
Do not both return a result and call `done`. The first completion wins.
- `{ status: 'success', credits }` replaces the current snapshot and resumes
the resource when the new state permits it.
- `{ status: 'cancelled' }` closes the attempt quietly and leaves the current
state unchanged.
- `{ status: 'error', message? }` shows a clear error and leaves the end user
blocked.
The builder treats a thrown handler, a rejected handler promise, or a malformed
success snapshot as an error. There is deliberately no client-side payment
timeout: bank authentication and hosted checkout can take several minutes, and
automatically enabling a retry could charge the same end user twice. The CTA
remains busy until the handler completes. Use `requestId` as an idempotency key
and ensure every handler path eventually completes. The pending operation
belongs to the editor session rather than the currently visible panel, so
closing and reopening the AI UI does not enable a duplicate purchase while
checkout is still running.
Persist payment and allowance changes in your backend, not in the callback.
After a reload or reconnect, initialize the builder from that durable state. If
your application refreshes the displayed snapshot with `setCredits` while a
purchase is pending, the original purchase remains active and the CTA stays
disabled. Complete that handler by returning, resolving, or calling `done`;
only the completion associated with its matching `requestId` ends the pending
purchase.
When both a handler and `purchaseUrl` are configured, the handler takes
precedence. If only `purchaseUrl` is present, the CTA opens it in a new tab. If
neither is configured, the status remains visible without a purchase CTA.
Non-HTTP(S), relative, and malformed purchase URLs are ignored.
## Customize credit notice text
The host-managed notice uses the following
[translation override](/builder/localization) keys. These are separate from
the [workspace exhaustion messages](/ai/assistant/pricing#customize-the-exhaustion-message).
| Key | Used for |
| -------------------------------------- | --------------------------------------------------------------------- |
| `labels.credits.default_unit` | Default display unit when no custom `unitLabel` is supplied. |
| `labels.credits.low_balance` | Low-balance message; receives `{remaining}` and `{unitLabel}`. |
| `labels.credits.exhausted` | Exhausted-allowance message; receives `{unitLabel}`. |
| `labels.credits.disabled` | Host-disabled message; receives `{unitLabel}`. |
| `labels.credits.invalid_configuration` | Invalid or incomplete allowance snapshot message. |
| `labels.credits.exhausted_title` | Exhausted blocking-state title; receives `{unitLabel}`. |
| `labels.credits.unavailable_title` | Disabled or invalid blocking-state title; receives `{unitLabel}`. |
| `labels.credits.purchase_action` | Purchase button label. |
| `labels.credits.purchase_failed` | Fallback purchase error when the callback supplies no custom message. |
For example, add these overrides to the same `unlayer.init()` call as your
`credits` configuration:
```javascript
unlayer.init({
locale: 'en-US',
translations: {
'en-US': {
'labels.credits.default_unit': 'AI credits',
'labels.credits.low_balance': '{remaining} {unitLabel} left.',
'labels.credits.exhausted': 'Add more {unitLabel} to keep creating.',
'labels.credits.purchase_action': 'Buy more',
},
},
});
```
Keep the balance dynamic with the `{remaining}` placeholder instead of writing
a numeric balance into the translated message. Translation overrides, including
`unlayer.setTranslations`, change wording; they do not update `limit`, `used`,
or the numeric allowance. Use `setCredits` for balance updates.
Keep `{unitLabel}` and `{remaining}` where you want those values inserted.
To use the translated default unit, omit `credits.ai.unitLabel`. If you supply
a custom `unitLabel`, localize that string in your application. Likewise, a
custom `message` returned by `credits:purchase` is displayed as supplied;
localize it before returning it.
## Refresh credits at runtime
Replace one resource's complete snapshot after a purchase, plan change, reset,
or any other host-side update:
```javascript
unlayer.setCredits('ai', {
limit: 200,
used: 80,
disabled: false,
lowBalanceThresholdPercentage: 80,
unitLabel: 'credits',
purchaseUrl: 'https://app.example.com/billing/ai',
});
```
`setCredits` replaces the complete snapshot; it does not merge fields from the
previous one. Include every optional display or purchase setting you still want
to use.
The builder does not increment `used` itself because it cannot know how your
application prices each operation. Refresh the snapshot from your backend as
usage changes, including after your backend records each AI operation. For
example, `limit: 200` and `used: 80` means 120 remain; a later snapshot
with `used: 95` means 105 remain.
Changing the translated label alone cannot make that numeric update. Do not
put raw provider token counts, model names, or costs into this display contract.
## Worked example: end-user billing
Use the [AI Credits API and webhooks](/server/cloud-api/ai-credits) as the usage
data source while keeping end-user billing and allowances in your application.
The complete pattern, including these builder hooks, is:
1. Identify the end user with `unlayer.init({ user })`.
2. Verify signed `ai.credits.usage_recorded` webhooks, then use
`X-Unlayer-Delivery-Id` for ordinary retry deduplication and update your
backend ledger for a fast response. The header is unsigned and not
replay-proof; see [signature and duplicate handling](/server/cloud-api/ai-credits#handling-duplicates).
3. Reconcile completed UTC days from the
[AI credit usage breakdown](/server/cloud-api/ai-credits#get-usage-breakdown).
4. Apply each end user's allowance and reset dates in your backend. Unlayer's
native reset is workspace-wide; custom per-user cycles belong to your
application.
5. Pass the current snapshot through `credits`. Send an exhausted or disabled
snapshot when the user reaches your limit, then refresh it with `setCredits`
after usage, a reset, or a purchase.
Unlayer does not call your backend to approve each Assistant prompt. The
`credits` snapshot is a UI gate, not a tamper-proof per-user limit. Keep the
commercial ledger in your backend; Unlayer's workspace allowance is the native
server-side enforcement boundary.
The usage endpoint accepts `start`, `end`, and `end_user_id`, so your daily
reconciliation can match each user's commercial cycle. Reconcile settled days
rather than repeatedly replacing the current UTC day's provisional total.
## Version compatibility
The credit upsell contract is additive:
| Host script | Builder version | Behavior |
| ----------- | ---------------------------- | -------------------------------------------------------------------------------------------------------------- |
| Current | Current | `credits`, `credits:purchase`, and `setCredits` are available. |
| Current | Older version-locked builder | The older builder ignores the extra init field and message. Its existing workspace enforcement remains active. |
| Older | Current | No host snapshot is supplied, so the builder falls back to workspace enforcement. |
Do not assume `setCredits` is available when intentionally loading an older,
version-locked builder. Upgrade both the host script and builder version before
depending on the in-builder purchase flow.
---
## Unlayer MCP
Unlayer MCP connects AI assistants and coding agents (Claude, Claude Code, Cursor, Codex, VS Code, and other MCP clients) to Unlayer. With it, an agent can:
- **Build email, page, and document templates as code** with [Unlayer Elements](/elements), returning `@unlayer/react-elements` source you can keep in your repo. Documents (invoices, reports, proposals) render to print-ready HTML for PDF.
- **Generate or refine designs from a prompt** with the AI Assistant.
- **Turn existing HTML** into an editable Unlayer design.
- **Render and export** designs to HTML, PDF, or PNG, and check templates for common issues.
- **Answer Unlayer questions** from the current docs.
Every design opens in the Unlayer visual builder, so teammates can edit what an agent created.
Unlayer MCP is a hosted **Streamable HTTP** server, listed in the [official MCP Registry](https://registry.modelcontextprotocol.io/v0.1/servers?search=com.unlayer/mcp) as `com.unlayer/mcp`:
```
https://api.unlayer.com/mcp
```
The **Model Context Protocol** (MCP) is an open standard for connecting AI clients to external tools and data sources.
## Connect to Unlayer MCP
### Browser sign-in with OAuth (recommended)
Use this path with any MCP client that supports OAuth. The client discovers Unlayer's authorization server, opens a browser, and manages access-token refreshes for you.
1. Add a custom MCP server in your client. Name it **Unlayer MCP** and enter:
```
https://api.unlayer.com/mcp
```
2. Select **Connect** or **Sign in**. Your browser opens the Unlayer authorization flow.
3. Sign in, choose the project the client can access, and approve the requested permissions. Don't have an Unlayer account? **[Sign up free](https://accounts.unlayer.com/signup/console)**.
4. Return to your client. The 14 Unlayer tools are ready to use.
The flow uses OAuth 2.1 with PKCE (S256), Dynamic Client Registration, authorization codes, and rotating refresh tokens. You don't need to create or paste a token.
In Claude Desktop, open **Settings → Connectors → Add custom connector**, enter the URL above, save, and select **Connect**. Other OAuth-capable clients use the same server URL and browser flow.
### Manual bearer token setup
If your client doesn't offer browser sign-in, configure a bearer token manually:
1. **[Open Console](https://console.unlayer.com/home)** and choose the project you want to use. Don't have an account? **[Sign up free](https://accounts.unlayer.com/signup/console)**.
2. Create either an **[API Key](/server/authentication#getting-an-api-key-unlayer_sk_)** (`unlayer_sk_*`, scoped to one project) or a **[Personal Access Token](/server/authentication#getting-a-personal-access-token-unlayer_pat_)** (`unlayer_pat_*`, works across your projects).
3. Add the server URL and token using your client's configuration format. For clients such as Cursor that use `mcpServers` JSON:
```json
{
"mcpServers": {
"unlayer": {
"url": "https://api.unlayer.com/mcp",
"headers": {
"Authorization": "Bearer "
}
}
}
}
```
4. Restart or reconnect the client. It discovers the available tools automatically with `tools/list`.
:::tip Which token, and do I need a projectId?
An **API Key** (`unlayer_sk_*`) and an **OAuth** connection are bound to one project, so both can omit `projectId`. With a **Personal Access Token** (`unlayer_pat_*`), call `list_workspaces` first, then pass the project ID as a string to each project-scoped tool.
:::
## Authentication
MCP POST requests must carry a `Bearer` token in the `Authorization` header. Use an **API Key** (`unlayer_sk_*`) for CI and single-project automation, a **Personal Access Token** (`unlayer_pat_*`) for developer tools that span projects, or **OAuth 2.1** for interactive clients such as Claude and ChatGPT. OAuth uses PKCE and Dynamic Client Registration; the client token is accepted only by the MCP resource and is never forwarded to the Cloud API.
OAuth connections are bound to the project selected during consent. Clients can request these permissions:
| Scope | Permission |
| ---------------- | ------------------------------------------------ |
| `templates:read` | List and read templates in the selected project. |
| `designs:write` | Generate, import, and edit temporary designs. |
| `render:execute` | Render designs to HTML, PDF, or images. |
See **[Authentication](/server/authentication)** for the full token and OAuth details.
## Testing your connection
Send a JSON-RPC request to `POST /mcp`. With a PAT, call `list_workspaces` first to find a project ID. Replace `` below with that ID. With an API Key or project-bound OAuth token, omit `projectId`.
```bash
curl https://api.unlayer.com/mcp \
-H "Authorization: Bearer " \
-H "Content-Type: application/json" \
-H "Accept: application/json, text/event-stream" \
-d '{
"jsonrpc": "2.0",
"id": 1,
"method": "tools/call",
"params": {
"name": "list_templates",
"arguments": { "projectId": "", "limit": 2 }
}
}'
```
A successful call returns your templates; an invalid token returns an authentication error. Depending on the token shape, that may be an HTTP `401` response or an MCP tool result with `isError: true`.
## Available tools
The server includes **14 tools**, grouped by what they do:
### Templates
| Tool | What it does |
| ------------------- | ----------------------------------------------------------------------------------------------------------- |
| `diagnose_template` | Check for common design issues, missing alt text, low contrast, oversized images, and malformed merge tags. |
| `get_template` | Fetch one template by ID, including its design JSON. |
| `list_templates` | List templates in a project (cursor-paginated). |
### AI generation
| Tool | What it does |
| ----------------------- | ------------------------------------------------------------------------- |
| `ai_generate_design` | Generate a design or refine an inline/saved design with the AI Assistant. |
| `import_html_to_design` | Turn an existing HTML email or page into an editable Unlayer design. |
### Render & export
| Tool | What it does |
| ---------------------- | ------------------------------------------------------------- |
| `export_design` | Export a saved template to HTML, PNG, or PDF. |
| `render_email` | Render an email design (HTML output tuned for email clients). |
| `render_preview_image` | Render a design to a PNG preview image (S3-hosted URL). |
### Unlayer Elements
| Tool | What it does |
| --------------------- | -------------------------------------------------------------------------------------------------------------- |
| `get_elements_schema` | Get the supported Unlayer Elements component and property schema. |
| `render_elements` | Render an Elements tree to source code, HTML, and design JSON, with an editor link and preview when available. |
### Workspace & account
| Tool | What it does |
| ---------------------- | -------------------------------------------------------------------------------------------------------------- |
| `get_my_subscription` | Look up the caller's plan, customer-facing features, and usage limits. |
| `list_recent_releases` | Get a link to Unlayer's official changelog — point users there for what's new and what changed. |
| `list_workspaces` | List accessible workspaces and projects. OAuth returns the consented project; API keys cannot list workspaces. |
### Discovery
| Tool | What it does |
| ---------------------- | ------------------------------------------------------------------------------------------------- |
| `search_documentation` | Full-text search over docs.unlayer.com — useful for grounding an AI client's answers in our docs. |
`tools/list` describes each tool and its typed inputs. Tool results contain JSON in text content. `diagnose_template` checks common issues; it is not a full accessibility audit.
## Which tool for which job
The server sends the same guidance to MCP clients in its instructions, so agents pick the right tool:
| The user wants… | Use |
| ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Templates as code: emails for their app (welcome, receipt, password reset), PDF documents (invoices, reports, proposals), templates kept in a repo, React/Next.js | `get_elements_schema`, then `render_elements` with an `Email`, `Page`, or `Document` root. In the project, install `@unlayer/react-elements`: `renderToHtml()` gives send-ready or print-ready HTML and `renderToJson()` gives design JSON that opens in the builder. |
| A design from a prompt, with no code involved | `ai_generate_design` (`displayMode: "document"` for documents) |
| Existing HTML (an email or page) made editable | `import_html_to_design` |
| A saved template exported to HTML, PNG, or PDF | `export_design` |
| Help embedding the Unlayer builder in their app | `search_documentation`, plus the [Unlayer Skills](/ai/skills) for their coding agent (`npx skills add unlayer/unlayer-skills`) |
## Example: generate a design and preview it
A typical agent flow chains a few tools. Here's "make me a product-launch email and show me what it looks like".
**1. Establish the project context.** OAuth uses the project selected during consent, and an API Key embeds its project, so both can skip this step. With a PAT, call `list_workspaces` with no arguments to discover the `projectId` required by project-scoped tools:
```json
{
"data": [
{
"id": 1,
"name": "Acme",
"projects": [{ "id": 12345, "name": "Marketing" }]
}
]
}
```
With a PAT, include `"projectId": "12345"` in each project-scoped call below, using your actual project ID.
**2. Generate the design.** Call `ai_generate_design` with a prompt. The result opens in a temporary editor session without creating a project template:
```json
{
"prompt": "Product launch newsletter for Nova Pro, dark theme",
"displayMode": "email"
}
```
It returns an editor URL and design JSON. `previewImageUrl` is included when preview rendering succeeds. The examples below abbreviate the design as `{ "body": {} }`; use the full returned design in actual calls.
```json
{
"editorUrl": "https://api.unlayer.com/editor-sessions//edit",
"previewImageUrl": "https://s3.../preview.png",
"displayMode": "email",
"design": { "body": {} }
}
```
Show `previewImageUrl` when present and link to `editorUrl` to open the design.
**3. Refine without saving.** Pass the returned `design` and `displayMode` back into `ai_generate_design` with the next prompt. The refinement starts from that exact design and opens another temporary editor session:
```json
{
"prompt": "Make the call-to-action button red",
"design": { "body": {} },
"displayMode": "email"
}
```
Use `templateId` instead of `design` when the starting point is already saved as a project template. Do not pass both.
**4. Preview.** Pass the current `design` straight into `render_preview_image` (no save needed) to regenerate the PNG after a change:
```json
{
"design": { "body": {} },
"displayMode": "email"
}
```
It returns the new image URL:
```json
{ "data": { "url": "https://s3.../preview.png" } }
```
:::note Editor sessions are temporary
Generation, import, rendering, and export tools do not change project templates. **Save** updates the temporary editor session. Use **Download design** or **Download HTML** before it expires to keep a copy.
:::
## Limits and security
- **Origins** — browser requests must use an allowed origin. Non-browser clients can omit `Origin`.
- **Requests** — 1 MiB body limit, per-credential rate limits, and a shared concurrency limit per server instance.
- **Timeouts** — upstream calls have a 240-second timeout by default.
- **Large results** — text beyond 140,000 characters is replaced with a truncation notice.
- **Header redaction** — `Authorization`, `Cookie`, and `X-Unlayer-Project-Id` are redacted from server logs.
## Related
- **[Cloud API](/server/cloud-api/reference)** — REST endpoints for projects, templates, generation, and rendering.
- **[Skills](/ai/skills)** — packaged context for AI coding agents that work alongside MCP.
- **[SDK](/sdk)** — typed access to supported Cloud API operations from server-side code.
- **[CLI](/cli)** — terminal tool for managing templates and projects.
- [Model Context Protocol specification](https://modelcontextprotocol.io/) — upstream protocol docs.
---
## How Skills Work
This page explains the technical architecture behind Unlayer Skills — how they're structured, how AI tools discover them, and how the routing system works.
## Skill Structure
Each skill is a self-contained Markdown file (`SKILL.md`) inside its own folder:
```
unlayer-skills/
├── unlayer/ # Router skill
│ └── SKILL.md
├── unlayer-integration/ # Framework setup
│ └── SKILL.md
├── unlayer-image-editor/ # Standalone Image Editor
│ ├── agents/
│ │ └── openai.yaml
│ ├── SKILL.md
│ └── references/
│ ├── configuration.md
│ ├── javascript.md
│ └── react.md
├── unlayer-elements/ # Code-first content creation
│ ├── SKILL.md
│ └── references/
│ ├── component-reference.md
│ └── patterns.md
├── unlayer-custom-tools/ # Custom tool building
│ └── SKILL.md
├── unlayer-export/ # Export and design management
│ ├── SKILL.md
│ └── references/
│ └── design-json.md # TypeScript types for design JSON
└── unlayer-config/ # Editor configuration
├── SKILL.md
└── references/
├── feature-flags.md
├── file-storage.md
└── security.md
```
Each `SKILL.md` file contains:
- **Frontmatter** with the skill name and description
- **Overview** of what the skill covers
- **Complete code examples** that AI can use as templates
- **Reference tables** for API options, widgets, and configuration
- **Common mistakes** and troubleshooting guides
- **Links** to official Unlayer documentation
## How Routing Works
The `unlayer` skill acts as a router. When you ask a question, your AI assistant reads the router skill first, which contains a mapping table:
| User Question | Routed To |
| -------------------------------------- | ---------------------- |
| "Add Unlayer to my React app" | `unlayer-integration` |
| "Embed the standalone Image Editor" | `unlayer-image-editor` |
| "Build an email with React components" | `unlayer-elements` |
| "Create a custom drag-and-drop tool" | `unlayer-custom-tools` |
| "Export HTML" / "Save the design" | `unlayer-export` |
| "Set up merge tags" / "Configure HMAC" | `unlayer-config` |
The AI assistant then reads the appropriate sub-skill for detailed guidance. For complex tasks that span multiple skills, the router recommends a sequence:
1. `unlayer-integration` — add the editor
2. `unlayer-config` — customize behavior
3. `unlayer-export` — save and export
4. `unlayer-custom-tools` — build custom blocks
## How AI Tools Discover Skills
When you run `npx skills add unlayer/unlayer-skills`, the CLI places skill files where your AI tool expects them:
| Tool | Location |
| -------------- | ------------------- |
| Cursor | `.agents/skills/` |
| Claude Code | `.claude/skills/` |
| GitHub Copilot | `.agents/skills/` |
| Windsurf | `.windsurf/skills/` |
| Codex | `.agents/skills/` |
Your AI tool automatically reads files from its expected location before generating responses. No additional configuration is needed.
## Keeping Skills Current
Skills include a version check mechanism. The router skill's `SKILL.md` reads its own file modification time and prompts the AI to suggest an update if the file is more than 30 days old:
```bash
npx skills update
```
This pulls the latest skill files from the [GitHub repository](https://github.com/unlayer/unlayer-skills), ensuring your AI assistant always has current API information.
## Example Prompts
Here are some prompts you can try after installing the skills:
**Integration:**
- _"How do I add Unlayer to my React app?"_
- _"Set up the Unlayer editor in my Angular project"_
**Image Editor:**
- _"Embed the standalone Image Editor in my React app"_
- _"Configure the Image Editor tools and enable the AI Assistant"_
**Elements:**
- _"Build a welcome email with Hyper Elements"_
- _"Render a Hyper Elements template to HTML"_
**Custom Tools:**
- _"Create a custom product card tool with an image, title, price, and buy button"_
- _"How do I create a custom property editor with a range slider?"_
**Export:**
- _"Export my design as HTML and save the design JSON"_
- _"Set up auto-save that triggers when the design changes"_
**Configuration:**
- _"Set up merge tags for my email templates"_
- _"Configure HMAC security for user identification"_
---
## What Are Skills?
Skills are structured knowledge files that give AI coding assistants expert-level understanding of a specific SDK or tool. Instead of relying on training data that may be outdated or incomplete, your AI reads the skill files directly — getting accurate API signatures, working code examples, and best practices.
## The Problem
AI coding assistants are trained on public data, but that data has limitations:
- **Outdated APIs** — training data may reference deprecated methods or old package versions
- **Missing context** — the AI doesn't know your project's specific Unlayer configuration
- **Hallucinated patterns** — without precise knowledge, AI may generate plausible-looking but broken code
- **Generic advice** — responses lack Unlayer-specific best practices like email-safe HTML or proper design JSON handling
## The Solution
Unlayer Skills solve this by providing your AI assistant with authoritative, version-current documentation as context. When you install the skills into your project, your AI coding tool reads them automatically before generating responses.
The result: instead of guessing, your AI assistant produces code that follows Unlayer's actual API, uses the correct package versions, and applies proven patterns for common tasks like save/load, export, and custom tools.
## Available Skills
Unlayer provides a router and domain-specific sub-skills:
- **`unlayer`** (Router) — the main entry point that automatically delegates your question to the right sub-skill
- **`unlayer-integration`** — framework setup for React, Vue, Angular, and plain JavaScript, including component mounting, editor access patterns, and multiple instances
- **`unlayer-image-editor`** — embedding and configuring the standalone Image Editor through JavaScript or the official React component
- **`unlayer-elements`** — building emails, pages, and documents in code with React components, without embedding the visual editor
- **`unlayer-custom-tools`** — building custom drag-and-drop content blocks with renderers, exporters, property editors, and validators
- **`unlayer-export`** — exporting HTML, PDF, images, and ZIP; saving and loading design JSON; auto-save patterns; Cloud API
- **`unlayer-config`** — feature flags, appearance, merge tags, HMAC security, file storage, localization, and validation
## Supported AI Tools
Skills work with any AI coding assistant that supports custom context files, including:
- [Cursor](./../getting-started/using-with-cursor)
- [Claude Code](./../getting-started/using-with-claude-code)
- [Codex](./../getting-started/using-with-codex)
- GitHub Copilot, Windsurf, and [others](./../getting-started/using-with-other-tools)
## Resources
- [GitHub Repository](https://github.com/unlayer/unlayer-skills) — full source for all skills
- [How Skills Work](./how-skills-work) — the technical details
---
## Install Skill
Install Unlayer Skills into your project so your AI coding assistant can provide expert-level Unlayer guidance.
## Installation
Run the following command in your project directory:
```bash
npx skills add unlayer/unlayer-skills
```
The CLI automatically detects your AI tool and installs the skill files in the correct location.
## What Gets Installed
The command installs these skill folders into your project:
| Folder | Skill | Description |
| ----------------------- | ------------- | --------------------------------------------- |
| `unlayer/` | Router | Delegates questions to the right sub-skill |
| `unlayer-integration/` | Integration | React, Vue, Angular, and plain JS setup |
| `unlayer-image-editor/` | Image Editor | Standalone JavaScript and React integrations |
| `unlayer-elements/` | Elements | Code-first emails, pages, and documents |
| `unlayer-custom-tools/` | Custom Tools | Building custom drag-and-drop blocks |
| `unlayer-export/` | Export | HTML, PDF, image export and design management |
| `unlayer-config/` | Configuration | Features, appearance, security, and more |
## Update Skills
Pull the latest version of all installed skills:
```bash
npx skills update
```
:::tip Keep Skills Updated
Skills are updated when Unlayer releases new features or API changes. Run `npx skills update` periodically to ensure your AI assistant has the most current information.
:::
## Try It Out
After installing, open your AI assistant's chat and try a prompt:
```
How do I add Unlayer to my React app?
```
Your AI assistant should respond with a complete, working integration — including proper ref handling, ready-event listeners, and save/load patterns.
## Tool-Specific Guides
For detailed instructions on configuring specific AI tools:
- [Using with Cursor](./using-with-cursor)
- [Using with Claude Code](./using-with-claude-code)
- [Using with Codex](./using-with-codex)
- [Using with Other Tools](./using-with-other-tools) (GitHub Copilot, Windsurf, and more)
---
## Using with Claude Code
[Claude Code](https://code.claude.com/docs/en/skills) is Anthropic's agentic coding tool that runs in your terminal. It reads skill files from `.claude/skills/`, and the `skills` CLI installs there directly when it detects Claude Code — no extra setup needed.
## Install
```bash
npx skills add unlayer/unlayer-skills --agent claude-code
```
Skills are installed to `.claude/skills/` in your project directory.
## Verify
Check that the skills are available:
```bash
ls .claude/skills/unlayer*
```
You should see folders: `unlayer/`, `unlayer-integration/`, `unlayer-image-editor/`, `unlayer-elements/`, `unlayer-custom-tools/`, `unlayer-export/`, and `unlayer-config/`.
## How It Works in Claude Code
Claude Code reads skill files as additional context before responding to your prompts. The skills provide Claude with:
- Accurate API signatures for `unlayer.init()`, `exportHtml()`, `loadDesign()`, and all other methods
- Working code examples for React, Vue, Angular, and plain JavaScript
- Email-safe HTML patterns for custom tool exporters
- Correct configuration options for merge tags, HMAC security, file storage, and more
## Example Prompts
Try these in your Claude Code session:
| Prompt | What You'll Get |
| --------------------------------------------------- | ---------------------------------------------------------------- |
| _"Add the Unlayer email editor to my React app"_ | Complete component with save/load pattern |
| _"Embed the standalone Image Editor in React"_ | Image Editor component with save and error handling |
| _"Build a welcome email with Hyper Elements"_ | Code-first React template with HTML rendering |
| _"Build a custom testimonial block for the editor"_ | registerTool with renderer, email exporter, and property editors |
| _"Export the design as HTML and save to my API"_ | exportHtml with proper design JSON handling |
| _"Set up custom image uploads to S3"_ | registerCallback with FormData upload pattern |
| _"Configure display conditions for VIP users"_ | setDisplayConditions with template engine syntax |
## Update
```bash
npx skills update
```
---
## Using with Codex
[Codex](https://developers.openai.com/codex/skills) is OpenAI's cloud-based coding agent. It reads skill files from the `.agents/skills/` directory in your project.
## Install
```bash
npx skills add unlayer/unlayer-skills --agent codex
```
Skills are installed to `.agents/skills/` in your project directory.
## Verify
Confirm the skill files are in place:
```bash
ls .agents/skills/unlayer*
```
You should see folders: `unlayer/`, `unlayer-integration/`, `unlayer-image-editor/`, `unlayer-elements/`, `unlayer-custom-tools/`, `unlayer-export/`, and `unlayer-config/`.
## How It Works in Codex
Codex reads `.agents/skills/` files and uses them as context when executing tasks. The skills provide Codex with:
- Accurate API signatures for `unlayer.init()`, `exportHtml()`, `loadDesign()`, and all other methods
- Working code examples for React, Vue, Angular, and plain JavaScript
- Email-safe HTML patterns for custom tool exporters
- Correct configuration options for merge tags, HMAC security, file storage, and more
## Example Prompts
Try these in your Codex session:
| Prompt | What You'll Get |
| --------------------------------------------------- | --------------------------------------------------------------- |
| _"Add the Unlayer email editor to my React app"_ | Complete component with save/load pattern |
| _"Embed the standalone Image Editor in React"_ | Image Editor component with save and error handling |
| _"Build a welcome email with Hyper Elements"_ | Code-first React template with HTML rendering |
| _"Create a custom product card tool"_ | Full registerTool call with renderer, exporters, and properties |
| _"Export the design as HTML and save to my API"_ | exportHtml with proper design JSON handling |
| _"Set up custom image uploads to S3"_ | registerCallback with FormData upload pattern |
| _"Configure HMAC security for user identification"_ | Server-side signature generation + client-side init |
## Update
```bash
npx skills update
```
---
## Using with Cursor
[Cursor](https://cursor.com/docs/skills) reads skill files automatically from the `.agents/skills/` directory in your project. Once installed, every AI chat and Cmd+K action has access to Unlayer expertise.
## Install
```bash
npx skills add unlayer/unlayer-skills --agent cursor
```
Skills are installed to `.agents/skills/` in your project directory.
## Verify
Confirm the skill files are in place:
```bash
ls .agents/skills/unlayer*
```
You should see folders: `unlayer/`, `unlayer-integration/`, `unlayer-image-editor/`, `unlayer-elements/`, `unlayer-custom-tools/`, `unlayer-export/`, and `unlayer-config/`.
## How It Works in Cursor
Cursor automatically reads `.agents/skills/` files and includes them as context when you:
- **Chat** (Cmd+L) — ask questions like _"How do I add Unlayer to my React app?"_
- **Inline edit** (Cmd+K) — generate or modify code with Unlayer-aware suggestions
- **Agent mode** — let the AI handle multi-step Unlayer integration tasks
The router skill (`unlayer/SKILL.md`) identifies the topic and delegates to the appropriate sub-skill, so you get focused, accurate answers regardless of how you phrase your question.
## Example Prompts
Try these in Cursor's chat:
| Prompt | What You'll Get |
| ---------------------------------------------- | --------------------------------------------------------------- |
| _"Add Unlayer email editor to my React app"_ | Complete component with ref handling, ready event, save/load |
| _"Embed the standalone Image Editor in React"_ | Image Editor component with save and error handling |
| _"Build a welcome email with Hyper Elements"_ | Code-first React template with HTML rendering |
| _"Create a custom product card tool"_ | Full registerTool call with renderer, exporters, and properties |
| _"Set up auto-save for the editor"_ | Debounced design:updated listener with exportHtml |
| _"Configure HMAC security"_ | Server-side signature generation + client-side init |
| _"Add merge tags for my email templates"_ | setMergeTags call with nested groups and loops |
## Update
```bash
npx skills update
```
---
## Using with Other Tools
Unlayer Skills work with any AI coding assistant that supports custom context files. This page covers setup for GitHub Copilot, Windsurf, and manual installation for other tools.
## GitHub Copilot
```bash
npx skills add unlayer/unlayer-skills --agent copilot
```
Skills are installed to `.agents/skills/` in your project directory. GitHub Copilot uses these files as additional context when generating responses.
**Verify:**
```bash
ls .agents/skills/unlayer*
```
## Windsurf
```bash
npx skills add unlayer/unlayer-skills --agent windsurf
```
Skills are installed to `.windsurf/skills/` in your project directory. Windsurf picks them up automatically as context for your AI conversations.
**Verify:**
```bash
ls .windsurf/skills/unlayer*
```
## Manual Installation
The skills are plain Markdown files hosted on GitHub. You can add them to any AI tool that supports custom instructions or context files:
1. Clone or download the repository:
```bash
git clone https://github.com/unlayer/unlayer-skills.git
```
2. Copy the skill folders into your project's skills directory (use the location your AI tool expects — see the table in [How Skills Work](../concepts/how-skills-work#how-ai-tools-discover-skills)):
```bash
mkdir -p .agents/skills
cp -r unlayer-skills/unlayer* .agents/skills/
```
The skill folders are: `unlayer/`, `unlayer-integration/`, `unlayer-image-editor/`, `unlayer-elements/`, `unlayer-custom-tools/`, `unlayer-export/`, and `unlayer-config/`. Each contains a self-contained `SKILL.md` file.
## Update
For all tools, pull the latest skills with:
```bash
npx skills update
```
---
## Skills
Unlayer provides official Skills for AI coding assistants like Cursor, Claude Code, Codex and others. Once installed, your AI assistant gains expert-level knowledge of the Unlayer SDK — giving you accurate, up-to-date answers instead of hallucinated or outdated patterns.
## Quick Install
```bash
npx skills add unlayer/unlayer-skills
```
This installs the skills into your project so your AI coding tool can read them automatically. See [Install Skill](/ai/skills/getting-started/install-skill) for detailed setup instructions.
## What's Included
| Skill | Description |
| ---------------------- | ------------------------------------------------------------------------ |
| `unlayer` | Router — automatically delegates to the right sub-skill |
| `unlayer-integration` | Add Unlayer to React, Vue, Angular, or plain JavaScript |
| `unlayer-image-editor` | Embed and configure the standalone Image Editor with JavaScript or React |
| `unlayer-elements` | Build emails, pages, and documents in code with React components |
| `unlayer-custom-tools` | Build custom drag-and-drop tools and property editors |
| `unlayer-export` | Export HTML, PDF, images, or save/load designs |
| `unlayer-config` | Configure features, appearance, merge tags, security, and file storage |
## Next Steps
- [What Are Skills?](/ai/skills/concepts/what-are-skills) — understand what skills are and why they matter
- [Install Skill](/ai/skills/getting-started/install-skill) — get set up in under a minute
- [GitHub Repository](https://github.com/unlayer/unlayer-skills) — view the source and contribute
---
## AI Template Importer
The AI Template Importer turns an existing design into an editable Unlayer template in one click. Bring an HTML email or a screenshot of the page you want to recreate, and the importer rebuilds the layout — rows, columns, text, buttons, images, colors, and links — as a fully editable template, ready to refine in the builder.
It's available in the [Unlayer Console](https://console.unlayer.com), inside any project's **Templates** area. Partners can also offer it inside the embedded builder as an opt-in action in the **AI Assistant**.
:::success Included in your AI credits
The AI Template Importer is part of your plan's AI features and uses your existing AI credit allowance — the same pool that powers the AI Assistant and other AI tools. No separate add-on required.
:::
## What you can import
The importer accepts two kinds of input and produces a complete, editable template:
- **HTML email.** Bring an existing email — exported from another tool, hand-coded, or pulled from your inbox. The importer reads the layout, preserves your copy, links, fonts, and colors, and quietly skips elements like tracking pixels and "View in browser" links that don't belong in your editable template.
- **Screenshot or image.** Have a design in mind but no source HTML? Upload a screenshot of any email or page you'd like to recreate. The importer reads the visual layout and rebuilds it from scratch so you can take it from there.
Once imported, the template behaves like any other — rearrange rows, edit copy, swap images, and adjust styles directly in the builder.
## Embedded builder access
Embedded access is disabled by default. Set `features.ai.templateImporter` to `true` when initializing the editor to add **Import from HTML or image** to the full-template AI Assistant conversation:
:::note Editor version
The embedded action requires an editor release that includes
`features.ai.templateImporter`. An embed pinned to an earlier editor version
will ignore this option and will not show the action. Use the `latest` channel
while evaluating the feature, or pin a release published with Template
Importer support. This does not affect imports started from the Console.
:::
```javascript
unlayer.init({
features: {
ai: {
enabled: true,
assistant: true,
fullTemplateGeneration: true,
templateImporter: true,
},
},
});
```
The action also follows the AI Assistant and full-template generation requirements. `features.ai.fullTemplateGeneration` defaults to `true` and is shown explicitly above because the importer depends on it. Setting it to `false` hides the importer even when `features.ai.templateImporter` is `true`. Registering `ai:assistant:generate` also hides the importer because that host-owned, single-result generation contract does not support imports. With an empty reference draft, end-users can open the **+** menu and choose **Import from HTML or image**. Dropping HTML/HTM over the Assistant instead stages it as a reference; submitting one HTML file without instructions or image attachments starts an import, with replacement confirmation when the canvas already has content. Dropped images attach to the chat when image uploads are enabled; use the import menu to reconstruct a template from a screenshot. If image uploads are disabled, a dropped image stages an import instead.
The importer is available only while **Full Template** is the active Assistant target. Selecting an individual row or content tool hides the import action and clears any selected file or import currently in progress. Returning to **Full Template** restores the action without restoring the discarded import. HTML reference cards in the normal conversation draft are preserved while the target changes and become available again at the full-template level.
Imports run on the model the end-user picked in the Assistant's model selector, or on `features.ai.model` when the init config pins one; otherwise the service uses its importer default.
The flag is an editor UI control, not an Unlayer-managed end-user entitlement or quota. Set it independently for each editor session using your own plan, role, onboarding, or allowance logic. For example:
```javascript
// Fetch this server-authoritative decision before initializing the editor.
const canImportTemplates = currentUser.features.canImportTemplates;
unlayer.init({
features: {
ai: {
fullTemplateGeneration: true,
templateImporter: canImportTemplates,
},
},
});
```
Your application is responsible for storing and enforcing any per-user allowance in its backend before it enables the importer. The [AI Assistant lifecycle callbacks](/ai/assistant/events-callbacks) can identify HTML and image import activity for analytics and reconciliation, but they fire after the editor accepts the action and cannot block a request. Unlayer's normal workspace AI-credit requirements still apply.
The uploaded HTML or image is sent to Unlayer's AI service and the selected
model provider so the design can be reconstructed. Source bytes are omitted
from lifecycle callback payloads and lifecycle logs; optional text instructions
are included in the request callback. See [AI Assistant privacy and data](/ai/assistant#privacy--data) for the broader data-handling policy.
## How to import from the Console
1. In the console, open the **Templates** tab for your project (available for **Emails**, **Pages**, and **Documents**).
2. Click **AI Template Importer** in the top-right corner.
3. Choose your source file (or drag it into the standalone importer). In the embedded Assistant, choose **Import from HTML or image** for a direct conversion, or use **Add files** to provide HTML and photos as conversational references:
- **HTML files:** `.html`, `.htm`
- **Images:** `.png`, `.jpg`, `.jpeg`, `.webp`, `.gif`. GIF imports use the first frame; it must fit the 5 MB limit after PNG conversion and contain at most 25 megapixels.
- **Max file size:** 5 MB
4. Give your template a name and, if you'd like, choose a folder to save it in.
5. Click **Import** and let the importer work — you'll see progress updates as it goes. A typical import takes under a minute; longer or more detailed designs may take a bit more time.
When it's done, you'll land directly in the editor with your new template open, ready to edit, polish, and use.
## Importing inside the embedded builder
1. Open the AI Assistant at the full-template level.
2. With no reference attachments staged, open the **+** menu and select **Import from HTML or image**.
3. Choose a supported HTML or image file up to 5 MB. The file appears as a **Design import** attachment in the prompt composer, labeled with its source type and size.
4. Optionally describe how the Assistant should recreate or adapt the source, then send the attachment. If the canvas already contains content, confirm the replacement in the conversation.
5. The Assistant reports progress in the chat and lets the end-user stop or retry the import. A successful import replaces the canvas in one undoable change.
Choosing **Cancel** at the replacement confirmation keeps the current design and records that no import was started. This pre-request choice does not emit any [AI Assistant lifecycle callback](/ai/assistant/events-callbacks); callback guarantees, including `ai:assistant:on:cancel`, begin only after the end-user clicks **Replace design** and `ai:assistant:on:request` fires.
## Combine HTML with photos or use it as inspiration
With the embedded importer enabled, **+ → Add files** accepts HTML and image references together. You can also drop them anywhere over the Assistant panel. Add a prompt such as “Keep my current copy, borrow the colors from this HTML, and use image #1 as the hero.” For a complete rebuild, say “Recreate this HTML using the attached photos.”
This runs as a normal Assistant conversation and uses its existing undo history and credits. It does not automatically start the separate importer or replace the design just because an HTML file was attached. A single HTML attachment submitted without instructions or images starts an import instead, with replacement confirmation when the canvas already has content. Use the explicit import action above when the source should be converted directly.
The reference draft accepts up to three non-empty HTML files totaling 5 MB, plus up to six images totaling 10 MB. Normal image upload limits and configuration still apply. See [image attachments and storage](/ai/assistant/how-it-works/image#drop-files-into-the-assistant) for details.
## Credits & limits
Each import uses the workspace's **AI credit allowance**, shared by every
project and AI feature in that workspace. You don't need separate importer
credits.
### What an import costs
Because the importer builds a complete template, an HTML or image import
usually uses **hundreds to a couple thousand credits**. The exact amount
depends on:
- **How large the source is.** Longer emails and denser screenshots take more work to rebuild.
- **Whether you import HTML or an image.** Image imports tend to cost a bit more, since the importer reads the design visually.
For your plan's included credits, available credit packs, and pricing details, see the [pricing page](https://unlayer.com/pricing).
### If you run out of credits
If the workspace has used its AI credits for the current monthly window, the
importer will let you know before running. From there you can:
- **Wait for your credits to reset** at the start of your next billing period.
- **Add a credit pack** anytime from _Console → Billing → Add-ons_ to keep going right away.
- **Upgrade your plan** for a larger built-in allowance.
If your plan doesn't include AI features at all, the **AI Template Importer** button won't appear — upgrade your plan to enable AI tools.
### Where to see your usage
All AI activity — imports, the AI Assistant, and other AI features — shows up together in your project's **Usage Insights** view in the console as a single AI credits total, so you always know where you stand against your allowance. This workspace-level accounting is separate from any importer allowance maintained by your application.
## Help us make it better
After each import from the Console, you'll have a chance to rate how the result turned out. Ratings are not currently shown for imports started inside the embedded builder. Console ratings and comments go straight to our team and directly shape how the importer improves over time — it's the fastest way to flag a layout that didn't quite work, a color that came out off, or something missing entirely.
For broader feedback or recurring quality issues across many templates, reach out to your account manager or [Unlayer support](https://unlayer.com/support).
## Tips & things to know
A few things that help you get the best results:
- **Imports always create a full template.** If you'd like to edit just one section of an existing design, the **AI Assistant** inside the builder is a better fit.
- **5 MB file limit.** If your HTML or screenshot is too large, try compressing the image or removing unused sections from the HTML.
- **Embedded images are re-hosted.** Some HTML files carry their images inside the file as base64 data, for example pages saved with a single-file page saver or exported that way by a site builder. The importer extracts PNG, JPEG, GIF and WEBP images, stores each one as a regular hosted image, and links it from the new template, so it displays in email clients that block embedded images. Images are stored where your other editor image uploads go: your project's custom file storage when one is configured, otherwise Unlayer's storage. Embedded SVG images are not carried over.
- **Embedded fonts are not carried over.** Fonts stored inside the HTML file are removed before the AI reads the page, so they don't use up AI credits. The importer still sees the font names in the page's styles. To display a custom font in the new template, add it to your [Project Fonts](/builder/font-management/custom-fonts).
- **Very long pages may be too large to import.** Even within the file limit, a page with a lot of text or markup can exceed what the importer can read in one pass. You'll see "This HTML is too large to import". Remove sections you don't need, or import a screenshot of the design instead.
- **Image imports use placeholders.** Since screenshots don't carry the original image files, the importer fills image spots with placeholders — you can swap in your real images right in the editor.
- **Expect small adjustments.** Especially with screenshot imports, the importer gets you most of the way there, but final polish — exact colors, spacing, fonts — is best done with a quick pass in the builder.
- **One file at a time.** Import templates one at a time. For a larger library, run the importer for each file in turn.
If an import doesn't come out the way you expected, try importing again or with a slightly different source file. Console users can also leave a rating so we can keep improving.
## Related
- **[Pricing](https://unlayer.com/pricing)** — plans, included AI credits, and credit packs.
- **[Templates](/builder/latest/templates/)** — organizing, sharing, and managing your templates.
- **[AI Assistant events and callbacks](/ai/assistant/events-callbacks)** — observe importer requests and forward activity to your application.
---
## Enterprise SSO
Enterprise SSO lets your team sign in to the Unlayer Console through your
company identity provider, such as Okta, Microsoft Entra ID, or another SAML or
OIDC provider. Contact Unlayer to arrange Enterprise SSO for your workspace.
SSO authenticates your Console team. Your application remains responsible for
end users inside your embedded editor; see [End-User Identification](/builder/end-user-identification)
and [Security Settings](/builder/security).
## Set up your workspace
Your Unlayer contact helps configure the connection and verify your company's
email domains. Start with SSO optional so existing password and Google sign-in
remain available. A workspace owner or admin must successfully test SSO with
the saved configuration before SSO can be required.
Each verified domain routes to one connection. Connections authenticate users;
they do not isolate data within a workspace. Use separate workspaces when
separate customer populations must not share data or access.
## Sign in
1. Open the Unlayer sign-in page and choose **Sign in with Enterprise SSO**.
2. Enter your work email address.
3. Complete authentication with your company's identity provider.
Successful SSO can verify the matching email on an existing passwordless Unlayer account. An unverified account with an existing password or Google sign-in cannot be automatically linked, even when invited or when SSO is required. Contact Unlayer support for secure account recovery; simply verifying the email does not establish who created the earlier credentials. Previously verified accounts keep their existing sign-in methods, subject to the workspace SSO policy.
Your verified email domain selects the company connection. If an existing
Unlayer account with that email is outside the workspace, an administrator
must invite the account before it can be linked. Contact your administrator
if Unlayer reports conflicting accounts or a suspended membership.
## Choose optional or required SSO
With **optional SSO**, members can continue using their existing sign-in methods.
With **required SSO**, governed members must authenticate through their company's
connection to access the workspace. A personal email address outside the
configured domains is not automatically governed unless its account is linked
to that SSO organization.
Enabling required SSO signs governed users out of Unlayer, including sessions
used for other workspaces, and revokes their OAuth refresh tokens for this workspace. Existing sessions and delegated credentials must satisfy the
workspace's current SSO policy when accessing protected resources.
Passwords are retained so an administrator can roll the policy back to optional.
Changing authentication settings requires saving them with SSO optional and
completing another owner/admin SSO test before requiring it again. A verified
domain cannot be removed or made unverified while a linked member or an
authenticated pending invitee still uses it for their Unlayer login or
identity-provider profile. Update those accounts, cancel their pending
invitations, or remove their workspace access first. Disabling the connection remains available
for recovery.
## Add and remove members
Workspace admins manage membership from **Team**. Invite members before their
first SSO login. An invited person can authenticate through SSO even when JIT is
disabled, then must accept the invitation before receiving workspace and project
access. The invitation's project selection and role are preserved; a pending
invitation does not grant access automatically, even with JIT enabled.
After signing in, invitees can open `/invites` in Console to view and accept
pending invitations, or follow the link in their invitation email.
Alternatively, arrange optional automatic membership creation on first
login (just-in-time provisioning, or JIT). JIT-created users receive an Embed
workspace membership with the member role. Without project-specific assignments,
that membership can access all Embed projects in the workspace. Use invitations
with selected projects when access must be restricted from the start; admins can
also manage roles and project assignments afterward.
Workspaces without an active SSO connection retain their existing Console access:
workspace membership allows opening sibling Embed projects, even when the person
has other project assignments. Enabling SSO makes those assignments restrictive
for ordinary members. Disabling SSO restores the existing Console behavior.
API, MCP, and Email Sending keep their separate project-access checks.
When someone leaves your company, disable their identity-provider account and
remove their workspace access in Unlayer. **Disabling the identity-provider
account alone does not revoke an existing Unlayer session.** This release does
not include automatic directory provisioning or offboarding through SCIM.
Removing an SSO workspace member signs that user out of Unlayer and revokes
their credentials scoped to that workspace,
removes workspace/project memberships, and records an explicit access block.
While SSO is active, an owner or admin must use **Restore SSO access** before
the member can sign in again. Restoring SSO access allows the person to join again; it does not recreate deleted
roles, project assignments, or tokens. JIT never clears an access block. If SSO is disabled,
accepting a fresh invitation restores membership and clears the old block for that
SSO connection, so re-enabling SSO preserves the restored access.
Workspace owners cannot be removed; transfer ownership first.
For members restricted to specific projects, removing their final project assignment
also removes their workspace access and requires a workspace owner or admin.
Concurrent removals do not turn restricted access into access to every project.
This applies to both SSO and non-SSO workspaces; non-SSO removal preserves sessions
for other workspaces.
## API access
Personal access tokens cannot prove an SSO login. For a user governed by required
SSO, that workspace is hidden from PAT discovery and cannot be accessed with a PAT. The token itself
is retained when required SSO is activated, so changing back to optional can
restore its use. Explicitly removing a member revokes their scoped credentials.
OAuth and MCP connections for a protected workspace must be authorized after
signing in through its SSO connection. Project API keys are machine credentials and are unaffected by the
interactive SSO policy. See [Server authentication](/server/authentication).
## Troubleshooting
- **Connection not found:** check the work email and verified domain with your administrator.
- **Workspace access unavailable:** sign in through the workspace's SSO connection.
- **SSO access suspended:** ask an owner or admin to review and explicitly restore your access.
- **Identity provider unavailable:** contact your IT administrator. Your Unlayer contact can explicitly change the workspace policy back to optional if needed.
## Existing members and connection replacement
Existing workspace members can authenticate through required SSO even if they do
not have Embed access. Signing in does not grant that access when JIT is off.
A pending invitation also waits for explicit acceptance, including when JIT is on;
acceptance adds its products and project role while preserving existing access.
To replace a WorkOS organization, contact your Unlayer administrator. Disable the
old connection, then use **Replace connection** in Admin with the new WorkOS
organization ID. Configure the same domains in the new WorkOS organization first.
The replacement transfers all domains and suspension records atomically. Old
identities and suspension history remain on the disabled connection; old profiles
are not reassigned to the new organization. Removed users remain suspended.
Activate the replacement with regular sign-in allowed, test an owner or admin login,
then require SSO. Replacement does not restore removed access automatically.
### Existing workspace administrators
Enabling SSO does not remove a workspace administrator's existing access to projects in Console.
Project-specific invitations still grant access only to the assigned projects for ordinary workspace
members. Administrators must complete SSO when their workspace requires it, just like other governed
members. Existing API and MCP project restrictions continue to apply.
### Session revocation timing
Session validation is cached for up to 60 seconds. After enabling required SSO
or removing an SSO member, existing sessions may take up to 60 seconds to
recognize the sign-out. Workspace access checks still enforce the current SSO
policy and membership. Issuing new OAuth authorization grants checks the session
directly without using this cache.
---
## Custom Backend
By default, Unlayer stores collaboration threads and comments for you. You can store them in your own database instead — to own and retain the data, for data residency, compliance, or integration reasons. Just register your own storage and the builder uses it in place of Unlayer's cloud, whether you use Unlayer's cloud or run on-premise.
- **Providers** load threads and comments (reads).
- **Callbacks** persist changes (writes).
When you register the `collaborationThreads` provider, the builder calls it instead of Unlayer's cloud storage — likewise for the write callbacks. This works with both Unlayer's cloud and on-premise setups.
```javascript
unlayer.init({
id: 'editor',
projectId: 1234,
designId: 'design-5678',
user: { id: 76, name: 'Jane Doe' },
features: { collaboration: true },
});
```
:::info
When you use Unlayer's cloud, providers and callbacks **override** the cloud storage when present, and the builder falls back to the cloud when they're absent. In an **on-premise** setup (with no Unlayer cloud), they're **required** — the Comments button stays hidden until you register the `collaborationThreads` provider.
:::
---
## Providers
Register each provider with `unlayer.registerProvider(name, handler)`. The handler receives `params` and a `done` function to call with your result.
| Provider | Params | Expected result |
| ----------------------------- | ------------------------- | ------------------------------------ |
| `collaborationThreads` | `{ projectId, designId }` | `{ success: true, data: Thread[] }` |
| `collaborationThreadComments` | `{ threadId }` | `{ success: true, data: Comment[] }` |
```javascript
unlayer.registerProvider('collaborationThreads', async (params, done) => {
// params = { projectId, designId }
const threads = await fetchThreadsFromYourBackend(params);
done({ success: true, data: threads });
});
unlayer.registerProvider(
'collaborationThreadComments',
async (params, done) => {
// params = { threadId }
const comments = await fetchCommentsFromYourBackend(params.threadId);
done({ success: true, data: comments });
},
);
```
To make the builder re-fetch threads — for example after your backend receives new comments from another user — call:
```javascript
unlayer.reloadProvider('collaborationThreads');
```
---
## Callbacks
Register each callback with `unlayer.registerCallback(name, handler)`. The builder calls them when the user makes a change; your handler persists it and calls `done` with the saved entity. On failure, call `done({ success: false, error })` and the builder will discard the change.
| Callback | Payload | Expected result |
| -------------------------------- | -------------------------------------------------------------------- | ----------------------------------------------------------------------------------- |
| `collaboration:thread:added` | `{ thread }` — includes `designId`, `itemId`, `type`, `text`, `user` | `{ success: true, thread }` — with server-assigned `id`, `firstComment`, timestamps |
| `collaboration:thread:modified` | `{ threadId, data }` — e.g. `{ status: 'resolved' }` | `{ success: true, thread }` |
| `collaboration:thread:removed` | `{ threadId }` | `{ success: true }` |
| `collaboration:comment:added` | `{ comment }` — includes `threadId`, `text`, `user` | `{ success: true, comment }` — with server-assigned `id` and timestamps |
| `collaboration:comment:modified` | `{ commentId, data, threadId }` | `{ success: true, comment }` |
| `collaboration:comment:removed` | `{ commentId, threadId }` | `{ success: true }` |
**Example: creating a thread**
```javascript
unlayer.registerCallback(
'collaboration:thread:added',
async ({ thread }, done) => {
if (!thread?.text || !thread.user?.id) {
done({ success: false, error: new Error('Invalid thread') });
return;
}
// Persist the thread and its first comment, assign IDs and timestamps
const savedThread = await saveThreadToYourBackend(thread);
done({ success: true, thread: savedThread });
},
);
```
When creating a thread, your backend should also create its **first comment** from the thread's `text` and `user`, and return the thread with `firstComment`, `commentCount`, `status: 'open'`, and `createdAt` / `updatedAt` set.
---
## Data model
### Thread
| Field | Type | Description |
| ------------------------- | ------------------------------------------------ | --------------------------------------------------------- |
| `id` | `string \| number` | Unique thread ID (assigned by your backend). |
| `projectId` | `string \| number` | The project the design belongs to. |
| `designId` | `string` | The design the thread is on. |
| `itemId` | `string` | The ID of the design component the thread is anchored to. |
| `user` | `User` | The user who started the thread. |
| `type` | `'feedback' \| 'idea' \| 'question' \| 'urgent'` | Thread category. |
| `status` | `'open' \| 'resolved'` | Thread state. |
| `commentCount` | `number` | Total comments, including the first. |
| `firstComment` | `Comment` | The comment that started the thread. |
| `createdAt` / `updatedAt` | `string` | ISO 8601 timestamps. |
### Comment
| Field | Type | Description |
| ------------------------- | ------------------ | --------------------------------------------- |
| `id` | `string \| number` | Unique comment ID (assigned by your backend). |
| `threadId` | Thread `id` | The thread this comment belongs to. |
| `user` | `User` | The comment author. |
| `text` | `string` | The comment body (plain text). |
| `createdAt` / `updatedAt` | `string` | ISO 8601 timestamps. |
### User
| Field | Type | Description |
| -------- | -------- | ----------------------------------------- |
| `id` | `string` | Stable unique user ID. |
| `name` | `string` | Display name. |
| `avatar` | `string` | Image URL; initials are shown when empty. |
---
## Tips
- Sort threads by `updatedAt` descending and comments by `createdAt` so the panel shows the latest activity first.
- Bump the thread's `updatedAt` when a reply is added so it surfaces at the top of the list.
- When the last comment of a thread is removed, remove the thread as well.
- Enforce ownership server-side: only allow users to modify or remove their own threads and comments.
---
## Team Collaboration
Team Collaboration turns the builder into a **shared review workspace**. Instead of pushing design feedback into email chains, screenshots, and chat threads, your users discuss a design right on the design itself: anyone on the team can start a conversation anchored to the exact component it's about — a row, an image, a text block — and teammates reply in threads, flag items as feedback, ideas, questions, or urgent, and resolve discussions as the work gets done.
The entire review cycle — comment, discuss, prioritize, resolve — happens inside your application, with full context and a clear record of what's open and what's settled.
---
## How it works
When collaboration is enabled, a **Comments** button appears in the builder's action bar, with a badge showing the number of open threads. Clicking it puts the builder into **Collaboration Mode**:
- A **Comments panel** lists every thread on the current design.
- Selecting any component opens a popover where users can read its thread or start a new one.
- Threads can be replied to, categorized, resolved, and filtered.
There are two ways into a conversation: the **Comments** button in the top action bar (which also carries the open-thread badge), and the **comment** button on a selected component's toolbar.
See [Using Comments](./using-comments.md) for the full walkthrough of the user experience.
---
## Key concepts
| Concept | Description |
| ----------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| **Thread** | A conversation anchored to one design component (`itemId`). Each thread belongs to a design (`designId`) and has a type and a status. |
| **Comment** | A single message inside a thread. The first comment starts the thread; later comments are replies. |
| **Type** | Each thread is categorized as `feedback`, `idea`, `question`, or `urgent`, each with its own icon. |
| **Status** | Threads are `open` or `resolved`. Resolving a thread hides it from the default list; it can be reopened later. |
| **User** | The author of each comment — the `user` you pass to `unlayer.init()`, with their name and avatar. |
---
## Where comments are stored
By default, threads and comments are stored in Unlayer's cloud database and scoped to your project and design — no backend work required.
If you'd rather own and retain the data yourself, you can store threads and comments in your own database by registering providers and callbacks. See [Custom Backend](./custom-backend.md).
---
## Next steps
- [Setup](./setup.md) — enable the feature and configure `unlayer.init()`.
- [Using Comments](./using-comments.md) — what your users see and can do.
- [Custom Backend](./custom-backend.md) — store threads and comments in your own database.
---
## Setup(Collaboration)
Team Collaboration is configured entirely through `unlayer.init()`. The Comments button appears in the action bar only when all of the requirements below are met.
---
## Requirements
| Requirement | How |
| ---------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
| Plan with Team Collaboration | Your project's plan must include the Team Collaboration feature. See [pricing](https://unlayer.com/pricing). |
| Feature flag | Pass `features: { collaboration: true }` — the feature is off by default. |
| Project ID | Pass your `projectId` so threads are scoped to your project. |
| Design ID | Pass a `designId` that is stable and unique per design. Threads are attached to it — without it, the feature stays hidden. |
| User identity | Pass a `user` with a stable `id`. Users can browse threads anonymously, but creating comments requires an identified user. |
---
## Example
```javascript
unlayer.init({
id: 'editor',
projectId: 1234,
designId: 'design-5678', // your unique, stable ID for this design
user: {
id: 76,
name: 'Jane Doe',
email: 'jane.doe@acme.com',
avatar: 'https://your-app.com/avatars/jane.png',
signature: 'e0bdb1f5cc...', // recommended: HMAC identity verification
},
features: {
collaboration: true,
},
});
```
Once the builder session starts, open threads for the design load automatically and the Comments button shows a badge with the open-thread count.
---
## Configuration reference
### `designId`
Threads are stored against the `designId`, not the design content. Use the same identifier every time you load that design — typically your database's primary key for it. If the `designId` changes between sessions, previous comments will not appear.
### `user`
The `user` object identifies the comment author:
| Property | Required | Description |
| -------------------- | ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `id` | Yes | A stable, unique identifier for the user. Used for thread ownership — users can only edit or delete their own comments. |
| `name` | Recommended | Displayed next to each comment. |
| `email` | No | The user's email address. |
| `avatar` | No | Image URL shown beside comments. When omitted, initials from `name` are shown instead. |
| `signature` | Recommended | HMAC signature of the user `id`, generated on your server. |
| `featurePolicyToken` | Instead of `signature` | [Signed feature-policy token](../advanced-configuration/security-settings.md#restricting-features-per-end-user), generated on your server. Required instead of `signature` when your project requires end-user feature policies. |
See [End-User Identification](../advanced-configuration/end-user-identification.md) for details on the `user` object and how to generate the `signature` or `featurePolicyToken` for identity verification.
### Storing data in your own backend
Threads and comments are stored in Unlayer's cloud database by default. To keep them in your own database instead — whether for data ownership, residency, or compliance — register providers and callbacks; the builder then uses your storage in place of the cloud. It works the same whether you use Unlayer's cloud or run on-premise.
In an **on-premise** setup, Unlayer's cloud is not used at all, so a custom backend becomes mandatory: the Comments button stays hidden until you register a `collaborationThreads` provider. See [Custom Backend](./custom-backend.md).
---
## Troubleshooting
The Comments button does not appear when any requirement is missing. Check, in order:
1. `features.collaboration` is `true`.
2. Your plan includes Team Collaboration.
3. `designId` is set.
4. On-premise: the `collaborationThreads` provider is registered.
---
## Using Comments
This page walks through the experience your users get once Team Collaboration is [set up](./setup.md).
---
## Entering Collaboration Mode
The **Comments** button in the builder's action bar shows a badge with the number of open threads. Clicking it switches the builder into Collaboration Mode.
- The **Comments panel** opens, listing all threads on the design — newest activity first.
- Design editing controls are disabled while the mode is active; users browse and discuss instead of editing.
- While the mode is active, the action-bar button reads **Collaboration Mode** — click it again, or the **Close Comments** (×) button in the Comments panel header, to exit.
If the design has no threads yet, the panel prompts the user to select a component to add the first comment.
---
## Starting a thread
In Collaboration Mode, clicking any component of the design — a text block, an image, a row — opens a comment popover for it:
1. Pick a comment type (see below).
2. Type the comment in the **Add a comment** field.
3. Submit. The thread is created and anchored to that component.
Each comment shows the author's name, avatar (or initials), and a timestamp.
### Comment types
Every thread carries one of four types, shown as an icon on the thread:
| Type | Intent |
| ------------ | ------------------------------------------ |
| **Feedback** | General review notes. |
| **Idea** | Suggestions and alternatives. |
| **Question** | Something that needs an answer. |
| **Urgent** | Must be addressed before the design ships. |
---
## Replying
Opening an existing thread — from the panel list or by clicking its component — shows the full conversation in a popover with a **Leave a reply** field. The thread's reply count updates in the panel list (for example "1 reply" or "No replies").
---
## Resolving threads
Each thread popover has a **Resolve** button. Resolving a thread:
- Marks it `resolved` and hides it from the default panel list.
- Removes it from the open-thread badge count.
- Disables new replies while resolved.
Resolved threads aren't deleted — they can be found with the **Resolved** filter and reopened at any time.
---
## Filtering
The Comments panel can filter threads by:
- **All** — every open thread on the design.
- **Only yours** — threads started by the current user.
- **Resolved** — threads that have been resolved.
- **Type** — show only a specific comment type (feedback, idea, question, urgent).
---
## Permissions
- Browsing threads works for any user of the builder; **creating** comments requires an identified `user` (see [Setup](./setup.md)).
- Users can only edit or delete **their own** threads and comments.
- Deleting a thread's last remaining comment removes the thread itself.
---
## From 1.309.4 to 1.339.0
## Text Tool Deprecated
The **Text** tool has been deprecated in favor of the new **Paragraph** tool. Existing templates with Text blocks can still be loaded for backward compatibility, but the legacy Text tool is no longer actively maintained or receiving new bug fixes.
### Key Differences
| | Text Tool (deprecated) | Paragraph Tool (new) |
| :------------ | :--------------------- | :----------------------- |
| Tool name | `text` | `paragraph` |
| Text property | `text` (HTML string) | `textJson` (JSON string) |
### Default Value Format Change
The Text tool used an HTML string for its `text` property:
```javascript
// Text tool (deprecated)
unlayer.init({
tools: {
text: {
properties: {
text: {
value:
'This is a new Text block. Change the text.',
},
},
},
},
});
```
The Paragraph tool uses a JSON string for its `textJson` property:
```javascript
// Paragraph tool (new)
unlayer.init({
tools: {
paragraph: {
properties: {
textJson: {
value:
'{"root":{"children":[{"children":[{"detail":0,"format":0,"mode":"normal","text":"This is a new Paragraph block. Change the text.","type":"extended-text","version":1}],"format":"","indent":0,"type":"paragraph","version":1,"textFormat":0}],"format":"","indent":0,"type":"root","version":1}}',
},
},
},
},
});
```
### Migrate Your Configuration
Update your configuration to use `tools.paragraph` and the `textJson` property format shown above. This changes the defaults for Paragraph blocks; it does not convert Text blocks in your stored design JSON.
### Migrate Existing Templates
Use the Cloud API's [Text-to-Paragraph conversion endpoint](/server/cloud-api/reference#tag/templates/operation/convertTextToParagraph) to convert existing design JSON:
```text
POST /v3/templates/convert/text-to-paragraph
```
Call this endpoint from your server, using the authentication described in the [API reference](/server/cloud-api/reference). Submit the design JSON in the request body's `design` property.
The response includes:
- `data.design`: The converted design JSON. The API returns a converted copy; it does not create or modify a saved template.
- `data.convertedCount`: The number of Text blocks converted.
- `data.warnings`: Warnings about structural or lossy conversions, such as block splitting, unsupported table styling or dropped elements. Each warning identifies its source Text block.
A Text block containing a table, image or horizontal rule can become several blocks: Paragraph blocks plus Table, Image or Divider blocks. The first block keeps the original ID; additional blocks receive new IDs.
Before saving the converted design:
1. Review `data.warnings` for each template and address any conversion issues.
2. Load the returned `data.design` in the builder and review the content and layout.
3. Save the converted design only after reviewing it. The conversion request does not overwrite your stored template.
### Preserve Legacy Text Behavior
If you need to preserve legacy behavior, [lock your builder version](/builder/latest/version-management) to a version where the Text tool is still available. Version locking does not migrate your configuration or stored designs to Paragraph, and backward compatibility does not mean the legacy Text tool receives new fixes.
---
## From 1.339.0 to 1.364.0
## Text Editor Update for Heading and Button Tools
The inline text editor for **Heading** and **Button** tools has been updated. Existing headings and buttons in saved designs will continue using the legacy editor, while new ones dropped into designs will use the updated editor.
## API Changes
For both the **Heading** and **Button** tools, the `text` property has been renamed to `textJson`. The value format changed from a plain string to a JSON structure.
### Heading Tool
**Before (1.339.0):**
```javascript
unlayer.init({
tools: {
heading: {
properties: {
text: {
value: 'This is a heading',
},
},
},
},
});
```
**After (1.364.0):**
```javascript
unlayer.init({
tools: {
heading: {
properties: {
textJson: {
value:
'{"root":{"children":[{"children":[{"detail":0,"format":0,"mode":"normal","style":"","text":"This is a heading","type":"extended-text","version":1}],"format":"","indent":0,"type":"extended-paragraph","version":1,"textFormat":0,"isInlineTool":true}],"format":"","indent":0,"type":"root","version":1}}',
},
},
},
},
});
```
### Button Tool
**Before (1.339.0):**
```javascript
unlayer.init({
tools: {
button: {
properties: {
text: {
value: 'Click here',
},
},
},
},
});
```
**After (1.364.0):**
```javascript
unlayer.init({
tools: {
button: {
properties: {
textJson: {
value:
'{"root":{"children":[{"children":[{"detail":0,"format":0,"mode":"normal","style":"","text":"Click here","type":"extended-text","version":1}],"format":"","indent":0,"type":"extended-paragraph","version":1,"textFormat":0,"isInlineTool":true}],"format":"","indent":0,"type":"root","version":1}}',
},
},
},
},
});
```
## JSON Structure Reference
The new `textJson` value follows this structure:
```json
{
"root": {
"children": [
{
"children": [
{
"detail": 0,
"format": 0,
"mode": "normal",
"style": "",
"text": "Your text here",
"type": "extended-text",
"version": 1
}
],
"format": "",
"indent": 0,
"type": "extended-paragraph",
"version": 1,
"textFormat": 0,
"isInlineTool": true
}
],
"format": "",
"indent": 0,
"type": "root",
"version": 1
}
}
```
To customize the text content, replace the `"text"` field value inside the `extended-text` node.
---
## From 1.382.0 to Latest
## Text Editor Update for Table Tool
The inline text editor for the **Table** tool has been updated. Existing tables in saved designs will continue using the legacy editor, while new ones dropped into designs will use the updated editor.
### API Changes
Each cell in the Table tool's `headers`, `rows`, and `footers` arrays now includes a `textJson` property alongside the existing `text` property. The `textJson` value uses a JSON structure, while `text` remains an HTML string.
**Before (1.382.0):**
```javascript
unlayer.init({
tools: {
table: {
properties: {
table: {
value: {
headers: [
{
cells: [
{ text: 'Add header text', width: 50 },
{ text: '', width: 50 },
],
height: 50,
},
],
rows: [
{
cells: [
{ text: 'Add text', width: 50 },
{ text: '', width: 50 },
],
height: 50,
},
],
footers: [
{
cells: [
{ text: '', width: 50 },
{ text: '', width: 50 },
],
height: 50,
},
],
},
},
},
},
},
});
```
**After (Latest):**
```javascript
unlayer.init({
tools: {
table: {
properties: {
table: {
value: {
headers: [
{
cells: [
{
textJson:
'{"root":{"children":[{"children":[{"detail":0,"format":0,"mode":"normal","style":"","text":"Add header text","type":"extended-text","version":1}],"format":"","indent":0,"type":"extended-paragraph","version":1,"textFormat":0}],"format":"","indent":0,"type":"root","version":1}}',
text: 'Add header text',
width: 50,
},
{
textJson:
'{"root":{"children":[{"children":[],"format":"","indent":0,"type":"extended-paragraph","version":1,"textFormat":0}],"format":"","indent":0,"type":"root","version":1}}',
text: '',
width: 50,
},
],
height: 50,
},
],
rows: [
{
cells: [
{
textJson:
'{"root":{"children":[{"children":[{"detail":0,"format":0,"mode":"normal","style":"","text":"Add text","type":"extended-text","version":1}],"format":"","indent":0,"type":"extended-paragraph","version":1,"textFormat":0}],"format":"","indent":0,"type":"root","version":1}}',
text: 'Add text',
width: 50,
},
{
textJson:
'{"root":{"children":[{"children":[],"format":"","indent":0,"type":"extended-paragraph","version":1,"textFormat":0}],"format":"","indent":0,"type":"root","version":1}}',
text: '',
width: 50,
},
],
height: 50,
},
],
footers: [
{
cells: [
{
textJson:
'{"root":{"children":[{"children":[],"format":"","indent":0,"type":"extended-paragraph","version":1,"textFormat":0}],"format":"","indent":0,"type":"root","version":1}}',
text: '',
width: 50,
},
{
textJson:
'{"root":{"children":[{"children":[],"format":"","indent":0,"type":"extended-paragraph","version":1,"textFormat":0}],"format":"","indent":0,"type":"root","version":1}}',
text: '',
width: 50,
},
],
height: 50,
},
],
},
},
},
},
},
});
```
### JSON Structure Reference
The `textJson` value for each cell follows this structure:
```json
{
"root": {
"children": [
{
"children": [
{
"detail": 0,
"format": 0,
"mode": "normal",
"style": "",
"text": "Your text here",
"type": "extended-text",
"version": 1
}
],
"format": "",
"indent": 0,
"type": "extended-paragraph",
"version": 1,
"textFormat": 0
}
],
"format": "",
"indent": 0,
"type": "root",
"version": 1
}
}
```
To customize the cell text content, replace the `"text"` field value inside the `extended-text` node.
## `rich_text` Property Editor Deprecated
The `rich_text` property editor for custom tools has been deprecated. Use `rich_text_v2` instead. It's a direct replacement with the same HTML string format — no changes needed in your value handling.
**Before:**
```javascript
unlayer.registerTool({
properties: {
content: {
editor: {
data: {
widget: 'rich_text', // Deprecated
},
},
},
},
});
```
**After:**
```javascript
unlayer.registerTool({
properties: {
content: {
editor: {
data: {
widget: 'rich_text_v2', // Use this instead
},
},
},
},
});
```
---
## Authentication(Cli)
The CLI authenticates with **Personal Access Tokens** (PATs). Tokens are scoped to your account and can be revoked any time from the Unlayer Console.
---
## Interactive Login (Recommended)
```bash
unlayer login
```
Here's what happens:
1. Starts a local HTTP server on a random port bound to `127.0.0.1`.
2. Opens your default browser to the Unlayer accounts page (with a `returnUrl` chained through the console's `cli-auth` endpoint).
3. Once you're signed in, the console mints a Personal Access Token and redirects to the local server with the token + a CSRF state parameter.
4. The CLI validates the state, stores the token, and shuts the server down.
The local server binds to `127.0.0.1` only — it's never exposed to the network. The login window times out after 5 minutes.
After the token is verified, you'll be prompted to pick a default workspace and project. The CLI skips that step if you pass `--skip-context`, if there's only one workspace/project to choose from, or if you pass `--workspace-id` and `--project-id` explicitly.
---
## Manual Token Entry
When the browser callback can't reach the CLI's local server (the most common case: you're SSH'd into a remote machine and the browser opens on your laptop), use `--manual`:
```bash
unlayer login --manual
```
This opens the browser to the Personal Access Tokens page (`/home/profile/tokens` in the console) rather than the auto-callback flow. You generate a PAT, copy it, and paste it into the CLI when prompted.
For fully headless environments with no browser at all, skip `login` entirely and use `--token` directly or set `UNLAYER_TOKEN`. See [Non-Interactive Login (CI/CD)](#non-interactive-login-cicd) below.
---
## Non-Interactive Login (CI/CD)
Pass the token directly as a flag or environment variable.
### Via flag
```bash
unlayer login --token unlayer_pat_xxxxxxxxxxxx
```
Tokens must start with `unlayer_pat_`. The CLI validates the prefix and rejects anything else.
### Via environment variable
```bash
export UNLAYER_TOKEN=unlayer_pat_xxxxxxxxxxxx
unlayer template list
```
The CLI checks `UNLAYER_TOKEN` before reading the global config, so an env var always wins.
In CI, you typically set `UNLAYER_TOKEN` as a secret and skip `unlayer login` entirely. Most commands work as long as the token is present in the environment.
---
## All `login` Flags
| Flag | Purpose |
| --------------------- | ----------------------------------------------------- |
| `-t, --token ` | Personal Access Token (skips browser flow) |
| `-u, --url ` | Override API URL (default: `https://api.unlayer.com`) |
| `-m, --manual` | Use manual token entry instead of browser |
| `-f, --force` | Overwrite existing authentication |
| `--workspace-id ` | Auto-select workspace by ID |
| `--project-id ` | Auto-select project by ID |
| `--skip-verify` | Skip token verification (local development only) |
| `--skip-context` | Skip workspace/project selection after login |
| `--json` | Output as JSON |
---
## Verifying Who You Are
```bash
unlayer whoami
```
Calls the API with the active token to confirm it works, then prints a token prefix, the token source (env var or config file), the API URL, the active workspace and project IDs, and the list of workspaces accessible to the token. See [`unlayer whoami`](commands/auth#unlayer-whoami) for the full output.
---
## Logging Out
```bash
unlayer logout
```
Clears the stored token. Pass `-a` / `--all` to clear the entire global config (token, workspace and project preferences, custom API URL, and any environment profiles you defined):
```bash
unlayer logout --all
```
Pass `-f` / `--force` to skip the confirmation prompt.
---
## Token Storage
The CLI uses [`conf`](https://github.com/sindresorhus/conf) to store the token in your OS-standard config location:
| Platform | Path |
| -------- | ------------------------------------------------------ |
| macOS | `~/Library/Preferences/unlayer-cli-nodejs/config.json` |
| Linux | `~/.config/unlayer-cli-nodejs/config.json` |
| Windows | `%APPDATA%\unlayer-cli-nodejs\Config\config.json` |
You can see the exact path with `unlayer config show` (it includes a `Config File` field) or `unlayer config path`.
:::danger Don't commit this file.
It contains your active token. If you ever leak it, revoke the token in the Unlayer Console immediately.
:::
---
## Token Environment Variable Override
By default, the CLI reads the token from `UNLAYER_TOKEN`. You can change the env var name the CLI looks at:
```bash
unlayer config set token-env-var MY_COMPANY_UNLAYER_TOKEN
```
After that, the CLI reads `MY_COMPANY_UNLAYER_TOKEN` instead. Useful if you have multiple Unlayer-related env vars or you're working around naming conflicts in CI.
---
## See Also
- [Configuration](configuration) — full config reference (locations, env profiles)
- [Examples — CI/CD](examples#cicd-token-based) — non-interactive examples
- [Errors](errors) — what to do when the token is invalid or expired
---
## Auth Commands
Three commands handle the authentication lifecycle: `login`, `logout`, `whoami`.
For the conceptual overview of how authentication works (PATs, env vars, token storage), see [Authentication](../authentication).
---
## `unlayer login`
Authenticate with your Unlayer account.
### Syntax
```bash
unlayer login [options]
```
### Description
Starts an OAuth-style browser flow by default: opens the Unlayer accounts page, chains through the console's `cli-auth` endpoint to mint a Personal Access Token, and redirects back to a local server bound to `127.0.0.1`. The token is then stored in your global CLI config.
`--manual` opens the Personal Access Tokens page (`/home/profile/tokens`) instead and prompts you to paste the token. Useful when the browser callback can't reach the CLI — for example, when you're SSH'd into a remote machine.
In CI, pass `--token` or set `UNLAYER_TOKEN` to skip the browser flow entirely.
After authentication, the CLI prompts you to pick a default workspace and project. It skips that step if you pass `--skip-context`, if there's only one workspace/project to choose from, or if you pass `--workspace-id` and `--project-id`. Tokens must start with `unlayer_pat_`; anything else is rejected.
### Options
| Flag | Description |
| --------------------- | --------------------------------------------- |
| `-t, --token ` | Personal Access Token (skip browser flow) |
| `-u, --url ` | API URL (default: `https://api.unlayer.com`) |
| `-m, --manual` | Use manual token entry instead of browser |
| `-f, --force` | Overwrite existing authentication |
| `--workspace-id ` | Auto-select workspace by ID (non-interactive) |
| `--project-id ` | Auto-select project by ID (non-interactive) |
| `--skip-verify` | Skip token verification (local development) |
| `--skip-context` | Skip workspace/project selection after login |
| `--json` | Output as JSON |
### Examples
```bash
# Interactive browser login
unlayer login
# Login with a token (CI-friendly)
unlayer login --token unlayer_pat_xxxxxxxxxxxx
# Auto-select workspace and project (great for scripts)
unlayer login --token $UNLAYER_PAT --workspace-id 42 --project-id 17
# Manual token entry (no browser available)
unlayer login --manual
```
---
## `unlayer logout`
Clear stored credentials.
### Syntax
```bash
unlayer logout [options]
```
### Description
Removes the stored token (and `tokenId`) from the global config. Pass `--all` to clear the entire global config — token, workspace and project preferences, custom API URL, environment profiles, and the active environment.
If you're already not logged in, the command prints `You are not currently logged in.` and exits cleanly without any changes.
### Options
| Flag | Description |
| ------------- | ---------------------------------------------------------------- |
| `-a, --all` | Clear all configuration including workspace and project settings |
| `-f, --force` | Skip confirmation prompt |
| `--json` | Output as JSON |
### Examples
```bash
# Confirm interactively, then clear the token
unlayer logout
# No confirmation (e.g., in scripts)
unlayer logout --force
# Wipe token + workspace + project
unlayer logout --all --force
```
---
## `unlayer whoami`
Verify the active authentication and show context.
### Syntax
```bash
unlayer whoami [options]
```
### Description
Calls the API with the active token to confirm it works, then prints a token prefix, the token source (env var or config file), the API URL, the active workspace and project IDs, and the list of workspaces accessible to the token. Exits with `2` if not authenticated, `1` if the API call fails.
### Options
| Flag | Description |
| -------- | -------------- |
| `--json` | Output as JSON |
### Examples
```bash
unlayer whoami
# Authentication
# Token: unlayer_pat_xxxxxxxx...
# Source: Config file
# API URL: https://api.unlayer.com
#
# Current Context
# Workspace: #42
# Project: #17
#
# Accessible Workspaces
# ├ Acme (ID: 42)
# └ Side Project (ID: 51)
#
# Authentication verified
```
```bash
unlayer whoami --json
# {
# "token": { "prefix": "unlayer_pat_xxxxxxxx...", "isEnvVar": false },
# "apiUrl": "https://api.unlayer.com",
# "workspaceId": 42,
# "projectId": 17,
# "workspaces": [ { "id": 42, "name": "Acme" }, ... ],
# "configPath": "/Users/jane/Library/Preferences/unlayer-cli-nodejs/config.json"
# }
```
A common script pattern — pull the active workspace ID out of the JSON:
```bash
WORKSPACE_ID=$(unlayer whoami --json | jq -r '.workspaceId')
echo "Active workspace: #$WORKSPACE_ID"
```
---
## See Also
- [Authentication](../authentication) — full conceptual guide to PATs and CI
- [Settings commands](settings) — `config show` reveals what's stored
---
## Scaffold a New Project
`unlayer init` creates a new project directory with the email editor pre-wired for your framework. Pick from five official starter templates and the CLI handles install, configuration, and (optionally) connecting the project to your Unlayer account.
## Syntax
```bash
unlayer init [project-name] [options]
```
## Description
`init` creates a new project directory, copies an official starter template, installs dependencies (unless `--no-install`), and optionally connects the project to your Unlayer account.
Run it with no arguments for the interactive flow. The CLI prompts you for a name, framework, and starter template.
## Arguments
| Argument | Description |
| ---------------- | ------------------------------------------------------- |
| `[project-name]` | Name of the project (and the directory it's created in) |
## Options
| Flag | Description |
| ----------------------------- | -------------------------------------------------------------------- |
| `-f, --framework ` | Framework to use (see [supported frameworks](#supported-frameworks)) |
| `-t, --template ` | Starter template (see [starter templates](#starter-templates)) |
| `--no-install` | Skip installing dependencies |
| `--no-typescript` | Disable TypeScript (enabled by default) |
| `--skip-connect` | Skip account connection after scaffolding |
| `--workspace-id ` | Workspace ID to connect (non-interactive) |
| `--project-id ` | Project ID to connect (non-interactive) |
| `-o, --output-dir ` | Directory to create the project in (defaults to cwd) |
| `--json` | Output as JSON |
---
## Supported Frameworks
| Value | Stack |
| ------------ | ---------------------------------- |
| `nextjs` | Next.js 15 (App Router) with React |
| `vite-react` | Vite + React |
| `vite-vue` | Vite + Vue 3 |
| `nuxt` | Nuxt 3 |
| `vanilla` | Plain HTML + JS, no build step |
---
## Starter Templates
| Value | Description |
| ----------- | ---------------------------------- |
| `adventure` | Adventure — travel newsletter |
| `product` | Product — Apple-style announcement |
| `blank` | Blank — start from scratch |
---
## Examples
### Interactive (recommended for first time)
```bash
unlayer init
# → prompts for name, framework, template, account connection
```
### Specify everything inline
```bash
unlayer init my-email-app -f nextjs -t product
```
### Skip dependency install (you'll run it later)
```bash
unlayer init my-app -f vite-react --no-install
cd my-app
pnpm install # or npm/yarn
```
The auto-installer detects your package manager (pnpm → yarn → npm; first one available wins) and runs it inside the new project directory with a 5-minute timeout. Install errors are non-fatal: init reports them and keeps going.
### CI-friendly — fully non-interactive
In non-interactive mode (CI or `--non-interactive`), all three of ``, `--framework`, and `--template` are required. To also auto-connect to your account, supply both `--workspace-id` and `--project-id`.
```bash
unlayer init my-app \
-f nextjs \
-t blank \
--workspace-id 42 \
--project-id 17 \
--json
```
### Plain JS, no TypeScript, no editor connection
```bash
unlayer init landing-page -f vanilla -t blank --no-typescript --skip-connect
```
---
## What `init` Creates
For a Next.js scaffold:
```
my-app/
├── app/
│ ├── editor/
│ │ └── page.tsx # Embedded Unlayer editor
│ ├── layout.tsx
│ └── page.tsx # Landing page
├── public/
│ └── designs/
│ └── sample.json # Starter design (adventure / product / blank)
├── output/
│ └── .gitkeep # Default output directory for `unlayer pull`
├── .gitignore
├── package.json
├── tsconfig.json
├── unlayer.config.json # Project config — see below
└── README.md
```
Other frameworks have their own conventional layouts (Vite + React, Vite + Vue, Nuxt, vanilla HTML). All of them get the same init-managed additions: a starter design at `designs/sample.json` (or `public/designs/sample.json` for non-vanilla), `output/`, `.gitignore`, and `unlayer.config.json`.
### `unlayer.config.json` written by init
```json
{
"$schema": "https://unlayer.com/cli/config-schema.json",
"projectId": null,
"defaults": {
"outputDir": "./output"
}
}
```
`projectId` starts as `null` and is filled in automatically when `init` connects the project to your Unlayer account (interactive prompt or `--workspace-id` + `--project-id` flags). Once set, subsequent CLI commands run inside this directory know which project to operate on.
One thing worth flagging: init's default `outputDir` is `./output` (created with a `.gitkeep`). The CLI's fallback default — used when there's no `unlayer.config.json` — is `./templates`. So `unlayer pull` inside an init-created project lands in `./output/`, but a one-off `unlayer pull` outside a project lands in `./templates/`.
---
## After `init`
```bash
cd my-app
npm run dev # or pnpm/yarn
```
The dev URL depends on the framework. Next.js and Nuxt default to `http://localhost:3000`, Vite to `http://localhost:5173`, and `vanilla` has no dev server (open `index.html` directly). For Next.js the embedded editor is at `/editor`.
If you let `init` connect the project to your Unlayer account (interactive prompt or `--workspace-id` + `--project-id`), `projectId` is set in `unlayer.config.json`. Subsequent CLI commands run inside this directory pick it up:
```bash
unlayer template list # lists templates in this project
unlayer pull # pulls templates into ./output/
```
---
## See Also
- [Configuration — Project Config File](../configuration#project-config-file) — what `unlayer.config.json` does
- [Examples — Bootstrapping a new project](../examples#bootstrapping-a-new-project)
---
## Resource Commands
Three command groups for browsing your Unlayer account:
- `workspace` — list and switch workspaces.
- `project` — list, switch, and inspect projects.
- `template` — list, search, and fetch templates.
All three require authentication ([`unlayer login`](auth#unlayer-login)).
---
## `unlayer workspace`
Manage the active workspace.
### `workspace list`
List all workspaces you have access to. In a TTY (and without `--json`), this is **interactive** — pick a workspace from the list and the CLI offers to set it active and chain into a project picker. In CI or with `--json`, it prints a static `DataTable`.
```bash
unlayer workspace list # interactive picker in a TTY; static table in CI
unlayer workspace list --json # JSON to stdout, no prompts
```
| Flag | Description |
| -------- | -------------- |
| `--json` | Output as JSON |
### `workspace use [workspace-id]`
Set the active workspace. With no argument, prompts interactively.
```bash
unlayer workspace use 42 # set explicitly
unlayer workspace use # interactive picker
```
| Flag | Description |
| -------- | -------------- |
| `--json` | Output as JSON |
The active workspace ID is stored in the global config. It's the default scope for `project list` and similar commands.
---
## `unlayer project`
Manage the active project.
### `project list`
List projects across accessible workspaces. Like `workspace list`, this is **interactive** in a TTY (pick a project to set it active) and a static `DataTable` in CI.
```bash
unlayer project list # interactive picker in a TTY; static table in CI
unlayer project list -w 42 # only workspace 42
unlayer project list --json
```
| Flag | Description |
| ---------------------- | ---------------------- |
| `-w, --workspace ` | Filter by workspace ID |
| `--json` | Output as JSON |
### `project use [project-id]`
Set the active project (interactive picker if you omit the ID).
```bash
unlayer project use 17
unlayer project use # interactive
```
| Flag | Description |
| -------- | -------------- |
| `--json` | Output as JSON |
### `project info [project-id]`
Print detailed information for a project. Defaults to the active project.
```bash
unlayer project info # active project
unlayer project info 17 # specific project
unlayer project info --json
```
| Flag | Description |
| ------------------- | ----------------------------------------- |
| `--project-id ` | Project ID (alias for the positional arg) |
| `--json` | Output as JSON |
Handy in scripts:
```bash
PROJECT_NAME=$(unlayer project info --json | jq -r '.name')
```
---
## `unlayer template`
Browse and fetch templates.
### `template list`
List templates in a project. Defaults to the active project; pass `--project-id` to scope elsewhere. In a TTY this is interactive — after the list loads, pick a template to open an action menu (view, get JSON, etc.). In CI it prints a static `DataTable`.
```bash
unlayer template list # interactive picker in a TTY; static table in CI
unlayer template list --limit 20
unlayer template list -s welcome
unlayer template list --json
```
| Flag | Description |
| ---------------------- | ------------------------------------- |
| `--project-id ` | Filter templates by project ID |
| `--limit ` | Maximum number of templates to return |
| `-s, --search ` | Search templates by name |
| `--json` | Output as JSON |
### `template search `
Search templates by name, case-insensitive. Same interactive-vs-static behavior as `template list`.
```bash
unlayer template search welcome # interactive picker in a TTY
unlayer template search "black friday" --limit 10 --json
```
| Flag | Description |
| ------------------- | ------------------------- |
| `--project-id ` | Filter by project ID |
| `--limit ` | Maximum number of results |
| `--json` | Output as JSON |
### `template get [template-id]`
Fetch a single template. Without an ID in a TTY, opens an interactive picker. In non-interactive mode without an ID, fails with exit `2` and lists available IDs.
By default (no `--json`, no `--design-only`, no `-o`), prints a key/value summary — name, ID, created/updated dates — plus a hint pointing at the flags below. To actually export the data, pick one of:
- `--json` → full envelope to stdout as JSON.
- `--design-only` → just `template.design` to stdout as JSON.
- `-o ` → write envelope (or design with `--design-only`) to a file.
- `-o -` → write to stdout.
```bash
# Interactive summary
unlayer template get 12345
# Print full envelope to stdout
unlayer template get 12345 --json
# Save envelope to file
unlayer template get 12345 -o ./welcome.json
# Just the design JSON, to file
unlayer template get 12345 --design-only -o ./welcome.design.json
# Pipe stdout (use - as the output target)
unlayer template get 12345 -o - | jq '.design.body.rows | length'
```
| Flag | Description |
| --------------------- | ------------------------------------------ |
| `-o, --output ` | Save output to file (`-` writes to stdout) |
| `--design-only` | Output only the design JSON |
| `--project-id ` | Project ID to scope the lookup |
| `--json` | Output as JSON |
To pull every template in a project at once, use [`unlayer pull`](sync#unlayer-pull) instead of looping over `template get`.
---
## See Also
- [Sync commands](sync) — `pull` and `diff` for bulk template work
- [Configuration → Resolution Order](../configuration#resolution-order) — how the active workspace/project is resolved
---
## Settings Commands
Three command groups for managing the CLI itself:
- `config` — read and write the global config.
- `env` — manage environment profiles (self-hosted deployments, etc).
- `status` — health check.
For the conceptual model — where the global config lives, what an environment profile is — see [Configuration](../configuration).
---
## `unlayer config`
Read and modify the global CLI config.
### `config show`
Print the current configuration.
```bash
unlayer config show
unlayer config show --json
```
| Flag | Description |
| -------- | -------------- |
| `--json` | Output as JSON |
The output includes the path to the config file on disk, which is useful when you need to back it up or copy it to another machine.
### `config set `
Set a single configuration key. Two keys are accepted:
| Key | Effect |
| --------------- | ---------------------------------------------------------------------------- |
| `api-url` | Override the API base URL |
| `token-env-var` | Change which env var the CLI reads the token from (default: `UNLAYER_TOKEN`) |
```bash
unlayer config set api-url https://unlayer-api.your-domain.com
unlayer config set token-env-var MY_COMPANY_UNLAYER_TOKEN
```
| Flag | Description |
| -------- | -------------- |
| `--json` | Output as JSON |
To set the **active workspace or project**, use `unlayer workspace use ` or `unlayer project use ` instead. Those are stored differently from the keys above.
### `config path`
Print the path to the global config file. Handy in scripts.
```bash
unlayer config path
# /Users/jane/Library/Preferences/unlayer-cli-nodejs/config.json
unlayer config path --json
# {"path":"/Users/jane/Library/Preferences/unlayer-cli-nodejs/config.json"}
```
| Flag | Description |
| -------- | -------------- |
| `--json` | Output as JSON |
### `config reset`
Reset the configuration to defaults. Clears the token, workspace, project, environments — everything.
```bash
unlayer config reset # prompts for confirmation
unlayer config reset --force # no prompt
```
| Flag | Description |
| ------------- | ------------------------ |
| `-f, --force` | Skip confirmation prompt |
| `--json` | Output as JSON |
---
## `unlayer env`
Manage **environment profiles** — named sets of API/Console/Accounts URLs you can switch between.
Useful when you point the CLI at a self-hosted Unlayer deployment without rewriting the global config every time.
### `env list`
List all environment profiles.
```bash
unlayer env list
unlayer env list --json
```
| Flag | Description |
| -------- | -------------- |
| `--json` | Output as JSON |
The output flags which profile is active and where each one is defined (global config or the project's `unlayer.config.json`).
### `env add `
Add or update a named environment profile in your global config. All three URLs are **required flags** — there is no interactive prompt.
```bash
unlayer env add self-hosted \
--api-url https://unlayer-api.your-domain.com \
--console-url https://unlayer-console.your-domain.com \
--accounts-url https://unlayer-accounts.your-domain.com
```
| Argument | Description |
| -------- | ----------------------------------------------------------------- |
| `` | Profile name (any string you choose, e.g. `self-hosted`, `local`) |
| Flag | Description |
| ---------------------- | ------------------------------- |
| `--api-url ` | **Required.** API base URL |
| `--console-url ` | **Required.** Console base URL |
| `--accounts-url ` | **Required.** Accounts base URL |
| `--json` | Output as JSON |
All three URLs are validated as parsable URLs at runtime. Invalid input fails with exit code `2`.
### `env use [name]`
Switch the active environment profile.
```bash
unlayer env use self-hosted # activate the named profile
unlayer env use --none # back to default URLs
unlayer env use # interactive picker
```
| Argument | Description |
| -------- | ------------------------------------------ |
| `[name]` | Profile name to activate (omit for picker) |
| Flag | Description |
| -------- | --------------------------------------- |
| `--none` | Clear active profile (back to defaults) |
| `--json` | Output as JSON |
### `env show [name]`
Show the URLs configured for a profile.
```bash
unlayer env show self-hosted # specific profile
unlayer env show # the active profile
```
| Argument | Description |
| -------- | --------------------------------- |
| `[name]` | Profile name (defaults to active) |
| Flag | Description |
| -------- | -------------- |
| `--json` | Output as JSON |
### `env remove `
Remove a profile from the global config. If you remove the active profile, the CLI clears the active selection.
```bash
unlayer env remove self-hosted
```
| Argument | Description |
| -------- | ---------------------- |
| `` | Profile name to remove |
| Flag | Description |
| -------- | -------------- |
| `--json` | Output as JSON |
You can also define profiles in `unlayer.config.json` to share them with your team via git. `env add` writes to the global (per-machine) config, and those overrides win on name conflicts with project-defined profiles.
---
## `unlayer status`
Check CLI health and connectivity.
### Syntax
```bash
unlayer status [options]
```
### Description
Reports authentication state, API reachability and latency, the active workspace and project IDs, the API URL, and the path to the global config file. Doesn't require authentication, which makes it useful as the first command to run when something is off. **Exits with code `1` when not authenticated or when the API is unreachable**, otherwise `0`.
### Options
| Flag | Description |
| -------- | -------------- |
| `--json` | Output as JSON |
### Examples
```bash
unlayer status
# Authenticated: Yes
# API Reachable: Yes
# API Latency: 42ms
# API URL: https://api.unlayer.com
# Workspace ID: 42
# Project ID: 17
# Config File: /Users/jane/Library/Preferences/unlayer-cli-nodejs/config.json
# ✓ All systems operational
```
```bash
unlayer status --json
# {
# "authenticated": true,
# "apiReachable": true,
# "apiLatencyMs": 42,
# "apiUrl": "https://api.unlayer.com",
# "workspaceId": 42,
# "projectId": 17,
# "configPath": "/Users/jane/Library/Preferences/unlayer-cli-nodejs/config.json",
# "error": null
# }
# In CI, gate on JSON output
HEALTH=$(unlayer status --json)
echo "$HEALTH" | jq -e '.authenticated and .apiReachable'
```
---
## See Also
- [Configuration](../configuration) — full conceptual reference for the global config and project config file
- [Authentication → Token Environment Variable Override](../authentication#token-environment-variable-override) — why you'd set `tokenEnvVar`
---
## Sync Commands
Two commands for keeping templates in sync between Unlayer and your local files:
- `pull` — download templates as JSON files.
- `diff` — compare a local design against its remote version.
These are the workhorse commands for git-based template workflows.
---
## `unlayer pull`
Download templates from a project to local files.
### Syntax
```bash
unlayer pull [options]
```
### Description
Pulls all templates in the active project (or one template with `--id`) and writes them as JSON files to the output directory. Each file is named `{slugified-name}-{id}.json` (e.g. `welcome-email-42.json`).
The output directory defaults to `./templates`. Override with `--output-dir`, or set `defaults.outputDir` in `unlayer.config.json`.
### Options
| Flag | Description |
| -------------------- | ------------------------------------------------- |
| `--id ` | Pull a single template by ID |
| `--output-dir ` | Output directory (default: `./templates`) |
| `--project-id ` | Project ID to scope the pull |
| `--design-only` | Save only the design JSON (not the full envelope) |
| `--json` | Output as JSON |
### Output Format
Without `--design-only`, each file contains the template envelope:
```json
{
"id": 42,
"name": "Welcome Email",
"displayMode": "email",
"design": {
/* design JSON */
},
"createdAt": "2026-04-01T12:00:00.000Z",
"updatedAt": "2026-05-05T09:30:00.000Z"
}
```
With `--design-only`, files contain just the design JSON — the same shape returned by the visual builder's `saveDesign` callback. That's the form you typically commit to git when you also want to load it via `editor.loadDesign(...)`.
### Examples
```bash
# Pull all templates in the active project
unlayer pull
# Pull a single template
unlayer pull --id 42
# Pull design JSON only (cleaner for git)
unlayer pull --design-only
# Pull from a specific project, custom output dir
unlayer pull --project-id 17 --output-dir ./email-designs
# In CI — JSON output for parsing
unlayer pull --json | jq 'length' # output is an array of {id, name, path}
```
---
## `unlayer diff `
Compare a local design file against the remote template it came from.
### Syntax
```bash
unlayer diff [options]
```
### Description
Reads a local design JSON file, looks up the matching remote template (auto-detected from the file's metadata, or explicit via `--remote`), and prints the differences.
The diff is human-readable by default. Pass `--json` for a structured diff suitable for scripting — typically a CI gate that fails when the local file has drifted from the remote source of truth.
### Arguments
| Argument | Description |
| -------- | -------------------------------- |
| `` | Path to a local design JSON file |
### Options
| Flag | Description |
| ------------------- | ------------------------------------------------------- |
| `--remote ` | Remote template ID (auto-detected from file if omitted) |
| `--project-id ` | Project ID to scope the lookup |
| `--json` | Output diff as structured JSON |
### Examples
```bash
# Compare a local file against its remote counterpart
unlayer diff ./templates/welcome-email-42.json
# Force a specific remote ID (when the file's metadata is stale)
unlayer diff ./welcome.json --remote 42
# Use in CI to fail when a checked-in template is out of sync
if ! unlayer diff ./templates/welcome.json --json | jq -e '.totalChanges == 0'; then
echo "Template has drifted from remote"
exit 1
fi
```
---
## Common Patterns
### Git-based template workflow
Treat the templates dir as part of your repo, pull regularly, commit:
```bash
unlayer pull --design-only
git add templates
git commit -m "Sync templates from Unlayer"
```
### Keep templates in sync with a CI gate
Run on every PR to catch drift between local files and the remote source of truth:
```bash
unlayer pull --design-only --output-dir ./templates.remote
diff -r ./templates ./templates.remote || exit 1
```
See [Examples](../examples) for full end-to-end workflows.
---
## See Also
- [Resource commands → template](resources#unlayer-template) — fetch single templates
- [Examples](../examples) — git-based template workflow
- [Configuration](../configuration) — set `defaults.outputDir` in `unlayer.config.json`
---
## Configuration(Cli)
The CLI reads configuration from three sources, in order of precedence:
1. **Environment variables** — for CI and one-off overrides.
2. **Global config** — your stored CLI state (`unlayer login`, `unlayer config set`, `unlayer workspace use`, etc.).
3. **Project config** — `unlayer.config.json` in your repo.
A typical setup uses the global config for personal authentication and the project config for project-scoped defaults like the project ID and output directory.
---
## Global Flags
These work on every command:
| Flag | Effect |
| ------------------- | ---------------------------------------------------- |
| `--json` | Output as machine-readable JSON (stdout) |
| `--non-interactive` | Never prompt; fail if input would be required |
| `-v, --verbose` | Verbose logging to stderr |
| `-q, --quiet` | Suppress decorative output (header, status messages) |
CI environments automatically enable `--non-interactive` and `--quiet`. The CLI detects them via the `CI` env var, `CONTINUOUS_INTEGRATION`, `UNLAYER_NON_INTERACTIVE`, or a non-TTY stdin.
### Output Contract
The CLI separates streams cleanly so you can pipe and parse:
- **stdout** — machine-readable data (JSON, URLs). Safe to `| jq` or capture.
- **stderr** — human messages, spinners, errors.
- In `--json` mode, errors are written to stderr as `{"error": "..."}`.
---
## Environment Variables
| Variable | Effect |
| ------------------------- | ----------------------------------------------------- |
| `UNLAYER_TOKEN` | Personal Access Token (highest-priority token source) |
| `UNLAYER_API_URL` | Override the API base URL |
| `UNLAYER_WORKSPACE_ID` | Override the active workspace |
| `UNLAYER_PROJECT_ID` | Override the active project |
| `UNLAYER_NON_INTERACTIVE` | Force non-interactive mode |
| `CI` | Auto-enables non-interactive + quiet |
| `CONTINUOUS_INTEGRATION` | Same as `CI` |
The token env var name itself is configurable. See [Authentication → Token Environment Variable Override](authentication#token-environment-variable-override).
---
## Global Config File
Stored by [`conf`](https://github.com/sindresorhus/conf) in your OS-standard config location:
| Platform | Path |
| -------- | ------------------------------------------------------ |
| macOS | `~/Library/Preferences/unlayer-cli-nodejs/config.json` |
| Linux | `~/.config/unlayer-cli-nodejs/config.json` |
| Windows | `%APPDATA%\unlayer-cli-nodejs\Config\config.json` |
Run `unlayer config show` to see the exact path on your machine.
### Stored Keys
| Key | Set By | Purpose |
| ------------------- | ---------------------------------------------------- | -------------------------------------------------------------- |
| `token` | `unlayer login` | Active Personal Access Token |
| `tokenId` | `unlayer login` | Server-side ID of the token (for revocation) |
| `tokenEnvVar` | `unlayer config set token-env-var` | Name of the env var the CLI looks at (default `UNLAYER_TOKEN`) |
| `apiUrl` | `unlayer config set api-url` / `unlayer login --url` | API base URL |
| `workspaceId` | `unlayer workspace use` | Active workspace |
| `projectId` | `unlayer project use` | Active project |
| `environments` | `unlayer env add` | Named environment profiles |
| `activeEnvironment` | `unlayer env use` | Currently selected environment profile |
You normally manage these via commands rather than editing the file directly.
---
## Project Config File
Drop a `unlayer.config.json` at the root of your repo to commit project-scoped defaults:
```json
{
"projectId": 17,
"defaults": {
"outputDir": "./templates"
},
"environments": {
"self-hosted": {
"apiUrl": "https://unlayer-api.your-domain.com",
"consoleUrl": "https://unlayer-console.your-domain.com",
"accountsUrl": "https://unlayer-accounts.your-domain.com"
}
}
}
```
The CLI walks up from the current directory to find this file, the way `.gitignore` resolution works.
| Key | Type | Purpose |
| -------------------- | ----------------------------------------------------- | ----------------------------------------------------------------------- |
| `projectId` | `number \| null` | Default project for commands that need one |
| `defaults.outputDir` | `string` | Default output directory for `unlayer pull` (defaults to `./templates`) |
| `environments` | `Record` | Named environment profiles for this project |
> 🔒 **Security:** the keys `token`, `apiKey`, and `$schema` are stripped from the parsed config so a leaked file can't leak credentials. Don't put secrets in this file. Use env vars instead.
---
## Environment Profiles
If you need to point the CLI at a different Unlayer deployment (a self-hosted instance, for example), save the URLs as a named profile and switch with one command:
```bash
# Define a profile (saved in global config)
unlayer env add self-hosted
# Switch the active profile
unlayer env use self-hosted
# Inspect
unlayer env list
unlayer env show self-hosted
# Switch back to defaults
unlayer env use --none
```
Profiles set the API URL, Console URL, and Accounts URL together. They can be defined in the global config (personal) or in `unlayer.config.json` (project-shared). Global wins on name conflicts. See [Settings commands → env](commands/settings#unlayer-env) for details.
---
## Resolution Order
For each setting, the CLI uses the first source that has a value:
| Setting | 1st | 2nd | 3rd | 4th |
| ------------ | --------------------------------------------------------- | ------------------------------------------ | --------------------------------- | ------------------------- |
| Token | `UNLAYER_TOKEN` env var (or whatever `tokenEnvVar` names) | global config `token` | — | — |
| API URL | `UNLAYER_API_URL` | active env profile | global config `apiUrl` | `https://api.unlayer.com` |
| Workspace ID | `UNLAYER_WORKSPACE_ID` | global config `workspaceId` | — | — |
| Project ID | `UNLAYER_PROJECT_ID` | global config `projectId` | `unlayer.config.json` `projectId` | — |
| Output dir | command-line `--output-dir` | `unlayer.config.json` `defaults.outputDir` | `./templates` | — |
---
## See Also
- [Authentication](authentication) — token storage, the `tokenEnvVar` knob
- [Settings commands](commands/settings) — `config`, `env`, `status`
- [Examples — pointing at a self-hosted deployment](examples#pointing-at-a-self-hosted-deployment)
---
## Errors & Troubleshooting
The CLI uses three exit codes and writes errors to stderr. In `--json` mode, errors are JSON-encoded so they're parseable.
---
## Exit Codes
| Code | Meaning |
| ---- | ------------------------------------------------------------------------------ |
| `0` | Success |
| `1` | Runtime error — API failure, network problem, unexpected exception |
| `2` | Usage error — bad input, missing required arg, unknown flag, not authenticated |
Use these in shell scripts:
```bash
if ! unlayer pull; then
case $? in
1) echo "API or runtime error — retry?" ;;
2) echo "Bad usage or not authenticated — fix invocation" ;;
esac
fi
```
---
## Output Streams
| Stream | Content |
| ------ | ------------------------------------------------------ |
| stdout | Machine-readable data only (JSON, URLs). Safe to pipe. |
| stderr | Human-readable messages, spinners, errors |
In `--json` mode, errors land on stderr in the form `{"error": "..."}`.
---
## Common Errors
### `Not authenticated`
```
✗ Not authenticated. Run unlayer login to get started.
```
The CLI couldn't find a token. Fix:
```bash
unlayer login
# or in CI:
export UNLAYER_TOKEN=unlayer_pat_xxxxxxxx
```
If you've configured a non-default token env var name (via `config set token-env-var ...`), the CLI looks at _that_ variable, not `UNLAYER_TOKEN`. Check with:
```bash
unlayer config show
# → look for the "Token Env Var" line
```
### `Invalid token` / `401 Unauthorized`
The stored token has been revoked or expired. Re-authenticate:
```bash
unlayer logout
unlayer login
```
### `Project not found` / `Project ID required`
Some commands need a project ID. Resolution order:
1. `--project-id` flag on the command
2. `UNLAYER_PROJECT_ID` env var
3. `unlayer project use ` (writes to global config)
4. `projectId` in `unlayer.config.json` at the repo root
If none of these is set, commands that scope to a project will fail. Run:
```bash
unlayer project list
unlayer project use
```
### `Workspace not found` / `Workspace ID required`
Same pattern as Project ID, but for workspace scope. Resolved in this order:
1. `UNLAYER_WORKSPACE_ID` env var
2. `unlayer workspace use `
```bash
unlayer workspace list
unlayer workspace use
```
### `unknown option '--xxx'` / `missing required argument`
These are Commander parse errors. The CLI exits with code `2`. The error message names the offending command and option. Run `unlayer --help` to see valid options.
```bash
unlayer pull --help
```
### `unlayer.config.json` parse warning
```
Warning: Failed to parse /path/to/unlayer.config.json: ...
```
The CLI found a config file but it isn't valid JSON. The CLI keeps going with defaults. Validate the file with `cat unlayer.config.json | jq .`.
### Authentication browser flow times out
```
Authentication timed out after 5 minutes. Please try again.
```
The CLI listened for the OAuth callback for 5 minutes and gave up. Common causes:
- The browser couldn't reach `localhost`.
- A firewall blocked the local server (it binds to `127.0.0.1`).
- You closed the browser tab before completing sign-in.
Try again, or use manual token entry:
```bash
unlayer login --manual
```
### `EACCES` / `permission denied` during install
```bash
npm install -g @unlayer/cli
# → EACCES: permission denied
```
Use a Node version manager (nvm, fnm, volta) instead of system Node, or change npm's global prefix to a user-writable location. Don't `sudo npm install -g`.
### `Node version not supported`
The CLI requires **Node 20+**. Check with `node --version`. If you're below 20:
```bash
nvm install 20
nvm use 20
```
---
## Verbose Logging
When you can't tell why a command is failing, run with `--verbose`:
```bash
unlayer pull --verbose
```
Verbose output goes to stderr (so it doesn't break `--json` piping) and shows config resolution, API URLs, and HTTP status codes.
---
## Connectivity Check
`unlayer status` is the quickest way to verify the CLI can reach the API:
```bash
unlayer status
```
It works without authentication, which makes it useful when your token has expired or you're debugging a corporate proxy.
---
## Where to Report Bugs
Open an issue at [github.com/unlayer/cli/issues](https://github.com/unlayer/cli/issues) with:
- The command you ran
- The output (use `--verbose` to capture more)
- `unlayer status --json` output
- Your OS and Node version
---
## See Also
- [Authentication](authentication) — token-related errors
- [Configuration](configuration) — config-related errors
- [Settings → status](commands/settings#unlayer-status) — health-check command
---
## Examples(Cli)
Realistic end-to-end workflows for the CLI.
---
## Bootstrapping a new project
You want a working email editor in your app, with a starter design and the project pre-connected to your Unlayer account.
```bash
# 1. Sign in
unlayer login
# 2. Scaffold (Next.js + product starter)
unlayer init my-emails -f nextjs -t product
# 3. Run it
cd my-emails
npm run dev
# → http://localhost:3000/editor
```
The scaffold writes `unlayer.config.json` with your `projectId`, so any future CLI command run from inside the project automatically scopes to it:
```bash
unlayer template list # lists templates in *this* project
unlayer pull # pulls them into ./output (the outputDir written by `unlayer init`)
```
---
## Git-based template workflow
You want templates checked into your repo so design changes are visible in PRs.
### One-time setup
```bash
cd your-app
unlayer login
unlayer project use 17 # pick the project
unlayer pull --design-only # writes designs into ./templates
git add templates
git commit -m "Initial template snapshot"
```
### Daily flow
```bash
# Designer makes changes in the visual editor → save in Unlayer
unlayer pull --design-only
git diff # → see exactly what changed
git commit -m "Sync templates"
```
### CI gate (catch drift)
Add to your CI:
```bash
unlayer pull --design-only --output-dir ./templates.remote
if ! diff -r ./templates ./templates.remote >/dev/null; then
echo "::error::Templates in repo are out of sync with Unlayer"
exit 1
fi
```
Or use `unlayer diff` per file. The JSON result has a `totalChanges` field; zero means no drift:
```bash
for f in templates/*.json; do
if ! unlayer diff "$f" --json | jq -e '.totalChanges == 0' >/dev/null; then
echo "Drifted: $f"
exit 1
fi
done
```
---
## CI/CD (token-based)
Most CI workflows skip `unlayer login` entirely and pass the token via env var instead:
```yaml
# .github/workflows/sync-templates.yml
name: Sync Unlayer Templates
on:
schedule:
- cron: '0 6 * * *' # daily 06:00 UTC
workflow_dispatch:
jobs:
sync:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with: { node-version: 24 }
- run: npm install -g @unlayer/cli
- run: unlayer pull --design-only --json
env:
UNLAYER_TOKEN: ${{ secrets.UNLAYER_PAT }}
UNLAYER_PROJECT_ID: '17'
- uses: peter-evans/create-pull-request@v6
with:
title: 'chore: sync Unlayer templates'
commit-message: 'chore: sync Unlayer templates'
branch: unlayer-template-sync
```
The CLI auto-enables `--non-interactive` and `--quiet` when it sees the `CI` env var. Errors go to stderr; `--json` keeps stdout machine-parseable.
---
## Pointing at a self-hosted deployment
Your team runs a self-hosted Unlayer deployment alongside the default `api.unlayer.com`. Save the alternate URLs as a named profile and switch with one command.
### Define the profile
```bash
unlayer env add self-hosted \
--api-url https://unlayer-api.your-domain.com \
--console-url https://unlayer-console.your-domain.com \
--accounts-url https://unlayer-accounts.your-domain.com
```
### Switch between deployments
```bash
unlayer env use self-hosted
unlayer template list # → reads from your self-hosted instance
unlayer pull --design-only
unlayer env use --none # back to the default URLs
unlayer template list # → reads from api.unlayer.com
```
### Share profiles via git
Drop a `unlayer.config.json` at the repo root so the whole team can `unlayer env use self-hosted` without configuring URLs locally:
```json
{
"projectId": 17,
"environments": {
"self-hosted": {
"apiUrl": "https://unlayer-api.your-domain.com",
"consoleUrl": "https://unlayer-console.your-domain.com",
"accountsUrl": "https://unlayer-accounts.your-domain.com"
}
}
}
```
---
## Inspect a single template programmatically
```bash
TEMPLATE_ID=42
# Pull just the design JSON to stdout
unlayer template get "$TEMPLATE_ID" --design-only -o -
# Save it
unlayer template get "$TEMPLATE_ID" --design-only -o ./welcome.json
# Count rows in the design
unlayer template get "$TEMPLATE_ID" --design-only -o - \
| jq '.body.rows | length'
```
---
## Troubleshooting in one command
When something is off, run `status` first:
```bash
unlayer status
```
It prints authentication state, API reachability and latency, the active workspace/project IDs, and your config file path. It doesn't require auth, so it works even when your token has expired. Exits with code `1` when something is wrong, otherwise `0`.
If `Authenticated: No`, run `unlayer login` again.
---
## See Also
- [Authentication](authentication) — token setup
- [Configuration](configuration) — env profiles, project config
- [Errors](errors) — exit codes and what to do when commands fail
---
## Installation(Cli)
The CLI ships as [`@unlayer/cli`](https://www.npmjs.com/package/@unlayer/cli) on npm. The binary is `unlayer`.
---
## Requirements
| Requirement | Version |
| ----------- | ------- |
| Node.js | `>= 20` |
The CLI is published as ESM. Older Node versions aren't supported.
---
## Install Globally
```bash
npm install -g @unlayer/cli
# or
pnpm add -g @unlayer/cli
# or
yarn global add @unlayer/cli
```
After install, the `unlayer` binary is on your `PATH`:
```bash
unlayer --version
# 0.1.0
```
---
## Run Without Installing
For a one-off invocation, use `pnpm dlx`:
```bash
pnpm dlx @unlayer/cli login
pnpm dlx @unlayer/cli template list
```
This pulls the latest published version each time.
---
## Verify the Install
```bash
unlayer --version
# 0.1.0
unlayer status
```
`unlayer status` reports authentication state, API reachability and latency, the active workspace and project IDs, and the path to your config file. It works without authentication, which makes it useful as the first command to run when something is off.
---
## Update Notifications
The CLI checks for a newer version in the background once per day and prints a notification on exit when an update is available:
```
Update available 0.1.0 → 0.2.0
Run npm i -g @unlayer/cli to update
```
---
## What's Next
- [Authentication](authentication) — sign in with a Personal Access Token
- [Quick Start](/cli) — first command in 30 seconds
---
## CLI
`@unlayer/cli` lets you manage your Unlayer account from the terminal: list and pull templates, switch workspaces and projects, scaffold new apps from official starter templates, and run automation in CI.
It's `unlayer` on the command line.
```bash
unlayer login
unlayer template list
unlayer pull
unlayer diff ./templates/welcome-email-42.json
```
:::tip Looking for the programmatic API?
For typed access to supported Cloud API operations from Node.js, serverless, or other server-side code, see the **[SDK](/sdk)**.
:::
---
## What you can do
| Group | Commands | Use For |
| ------------- | ------------------------------------ | ------------------------------------------------------------------------- |
| **Auth** | `login` · `logout` · `whoami` | Sign in with a Personal Access Token |
| **Resources** | `workspace` · `project` · `template` | Browse, select, and inspect your account |
| **Sync** | `pull` · `diff` | Pull templates to local files, compare local vs remote |
| **Init** | `init` | Scaffold a new project (Next.js, Vite + React, Vite + Vue, Nuxt, vanilla) |
| **Settings** | `config` · `env` · `status` | Manage CLI configuration, environment profiles, health |
Every command supports `--json` for machine-readable output and `--non-interactive` for CI usage. See [Authentication](/cli/authentication) for token setup.
---
## Quick Start
```bash
# 1. Install
npm install -g @unlayer/cli
# 2. Authenticate (opens browser)
unlayer login
# 3. Scaffold a project
unlayer init my-app
# 4. Or pull templates from an existing project
unlayer pull
```
Walkthrough: [Installation](/cli/installation) → [Authentication](/cli/authentication) → [Examples](/cli/examples).
---
## Documentation Map
**Getting started**
- [Installation](/cli/installation) — install via npm, Node version, verify
- [Authentication](/cli/authentication) — Personal Access Tokens, browser login, CI usage
- [Configuration](/cli/configuration) — project config file, environment profiles, global flags
**Command reference**
- [Auth commands](/cli/commands/auth) — `login`, `logout`, `whoami`
- [Resource commands](/cli/commands/resources) — `workspace`, `project`, `template`
- [Sync commands](/cli/commands/sync) — `pull`, `diff`
- [Init command](/cli/commands/init) — `init` (with frameworks and starter templates)
- [Settings commands](/cli/commands/settings) — `config`, `env`, `status`
**Reference**
- [Examples](/cli/examples) — end-to-end workflows (CI/CD, template sync, multi-environment)
- [Errors](/cli/errors) — exit codes and common error messages
- [Quick Reference](/cli/quick-reference) — single-page cheat sheet
---
## Requirements
- **Node.js 20 or later**
- An Unlayer account (free signup at [accounts.unlayer.com](https://accounts.unlayer.com/signup/console))
---
## Quick Reference
Every command, flag, env var, and exit code on one page.
---
## Install
```bash
npm install -g @unlayer/cli # requires Node 20+
unlayer --version # → 0.1.0
```
---
## Auth
| Command | Description |
| --------------------------- | --------------------------------------- |
| `unlayer login` | Authenticate (browser flow) |
| `unlayer login --token ` | Non-interactive login |
| `unlayer login --manual` | Manual token entry |
| `unlayer logout` | Clear token |
| `unlayer logout --all` | Clear token + workspace + project |
| `unlayer whoami` | Show current user / workspace / project |
**`login` flags:** `-t/--token`, `-u/--url`, `-m/--manual`, `-f/--force`, `--workspace-id`, `--project-id`, `--skip-verify`, `--skip-context`, `--json`
**`logout` flags:** `-a/--all`, `-f/--force`, `--json`
---
## Resources
```bash
# Workspaces
unlayer workspace list
unlayer workspace use [id]
# Projects
unlayer project list [-w ]
unlayer project use [id]
unlayer project info [id]
# Templates
unlayer template list [--limit n] [-s ] [--project-id ]
unlayer template search [--limit n] [--project-id ]
unlayer template get [id] [-o ] [--design-only] [--project-id ]
```
---
## Sync
```bash
unlayer pull [--id ] [--output-dir ] [--project-id ] [--design-only]
unlayer diff [--remote ] [--project-id ]
```
---
## Init
```bash
unlayer init [name] [-f ] [-t ] [options]
```
| `-f, --framework` | `nextjs` · `vite-react` · `vite-vue` · `nuxt` · `vanilla` |
| ----------------- | --------------------------------------------------------- |
| `-t, --template` | `adventure` · `product` · `blank` |
Other flags: `--no-install`, `--no-typescript`, `--skip-connect`, `--workspace-id`, `--project-id`, `-o/--output-dir`, `--json`
---
## Settings
```bash
# Global config
unlayer config show
unlayer config path # print config file path
unlayer config set # keys: api-url, token-env-var
unlayer config reset [-f]
# Environment profiles
unlayer env list
unlayer env add --api-url --console-url --accounts-url
unlayer env use [name] [--none]
unlayer env show [name]
unlayer env remove
# Health check (exit 1 when unauthenticated or unreachable)
unlayer status
```
---
## Global Flags
| Flag | Effect |
| ------------------- | -------------------------------- |
| `--json` | Machine-readable JSON to stdout |
| `--non-interactive` | Never prompt; auto-enabled in CI |
| `-v, --verbose` | Verbose logging to stderr |
| `-q, --quiet` | Suppress decorative output |
CI mode auto-enabled when any of `CI`, `CONTINUOUS_INTEGRATION`, or `UNLAYER_NON_INTERACTIVE` is set, or when stdin is not a TTY.
---
## Environment Variables
| Variable | Effect |
| ------------------------------- | ------------------------------------ |
| `UNLAYER_TOKEN` | Personal Access Token |
| `UNLAYER_API_URL` | Override API base URL |
| `UNLAYER_WORKSPACE_ID` | Override active workspace |
| `UNLAYER_PROJECT_ID` | Override active project |
| `UNLAYER_NON_INTERACTIVE` | Force non-interactive mode |
| `CI` / `CONTINUOUS_INTEGRATION` | Auto-enables non-interactive + quiet |
The token env var name itself is configurable: `unlayer config set token-env-var MY_VAR`.
---
## Exit Codes
| Code | Meaning |
| ---- | ------------------------------------------------------ |
| `0` | Success |
| `1` | Runtime error (API, network, unexpected) |
| `2` | Usage error (bad flag, not authenticated, missing arg) |
---
## Resolution Order
| Setting | 1st | 2nd | 3rd | 4th |
| ------------ | ---------------------- | ------------------------------------------ | ---------------------- | ------------------------- |
| Token | env var | global config | — | — |
| API URL | `UNLAYER_API_URL` | active env profile | global config `apiUrl` | `https://api.unlayer.com` |
| Workspace ID | `UNLAYER_WORKSPACE_ID` | global config | — | — |
| Project ID | `UNLAYER_PROJECT_ID` | global config | `unlayer.config.json` | — |
| Output dir | `--output-dir` | `unlayer.config.json` `defaults.outputDir` | `./templates` | — |
---
## `unlayer.config.json`
Drop at the repo root to commit project-scoped defaults:
```json
{
"projectId": 17,
"defaults": {
"outputDir": "./templates"
},
"environments": {
"self-hosted": {
"apiUrl": "https://unlayer-api.your-domain.com",
"consoleUrl": "https://unlayer-console.your-domain.com",
"accountsUrl": "https://unlayer-accounts.your-domain.com"
}
}
}
```
`token`, `apiKey`, and `$schema` are stripped on read. Don't put secrets here.
---
## Common Workflows (one-liners)
```bash
# First-time setup
unlayer login && unlayer init my-app -f nextjs
# Pull templates and commit them
unlayer pull --design-only && git add templates && git commit -m "sync"
# CI: token via env, JSON output
UNLAYER_TOKEN=$PAT UNLAYER_PROJECT_ID=17 unlayer pull --json
# Drift gate
for f in templates/*.json; do
unlayer diff "$f" --json | jq -e '.identical' || exit 1
done
# Switch between deployments
unlayer env use self-hosted && unlayer pull
unlayer env use --none && unlayer pull # back to api.unlayer.com
# When something is broken
unlayer status # health check (no auth needed); exits 1 when unhealthy
unlayer --verbose # detailed logs
```
---
## See Also
- [Overview](/cli)
- [Authentication](authentication)
- [Configuration](configuration)
- [Examples](examples)
- [Errors](errors)
---
## Elements
**Unlayer Elements is now [Hyper Elements](https://hyperelements.dev)**, a free, open-source React library for writing emails, web pages, documents, PDFs, and images in code. It's built by the team behind Unlayer, and its docs and releases now live on its own site.
## Get started
```bash
npm install @hyper-elements/react
```
- [Quickstart](https://hyperelements.dev/docs/quickstart): write and render your first template.
- [Documentation](https://hyperelements.dev/docs): components, styles, rendering, and every output.
- [Visual editing](https://hyperelements.dev/docs/guides/visual-editor): open a template in the Unlayer builder.
Coding agents can install its skill with `npx skills add hyper-elements/hyper-elements`. See [AI agents](https://hyperelements.dev/docs/guides/ai-agents).
## Already using `@unlayer/react-elements`?
Hyper Elements has new components, so templates written with `@unlayer/react-elements` have to move. A codemod rewrites them and keeps your props, loops, and helpers:
```bash
npx @hyper-elements/migrate src/emails --from unlayer-elements
```
It lists what it would change, and `--write` replaces the files. See [From Unlayer Elements](https://hyperelements.dev/docs/migrate/unlayer-elements) for the details.
Nothing changes until you move: `@unlayer/react-elements` stays on npm, and your existing templates keep working with it.
## Coming from React Email?
The same tool converts React Email templates and checks each one against its original. See [From React Email](https://hyperelements.dev/docs/migrate/react-email).
---
## SDK
The **Unlayer SDK** is the official typed client for supported operations in the Unlayer Cloud REST API. Its request and response types and Fetch transport are generated from the public OpenAPI document, while a small allowlist keeps the public resource API intentional and stable.
---
## Available packages
Published to npm:
| npm package | Language | Requirements | Status |
| ------------------------------------------------------------ | ----------------------- | ------------ | --------- |
| [`@unlayer/sdk`](https://www.npmjs.com/package/@unlayer/sdk) | TypeScript / JavaScript | Node.js 20+ | Available |
The TypeScript SDK uses the same OpenAPI document that backs the [Cloud API reference](/server/cloud-api/reference). Approved operations are regenerated when their API contracts change; a new API endpoint does not become part of the SDK automatically.
---
## Install
```bash
npm install @unlayer/sdk
```
## Quick start
```ts
const unlayer = new Unlayer({
apiKey: process.env['UNLAYER_API_KEY'],
});
const page = await unlayer.templates.list({ limit: 10 });
console.info(page.data[0]?.id);
```
The SDK also reads `UNLAYER_API_KEY`, `UNLAYER_PERSONAL_ACCESS_TOKEN`, `UNLAYER_PROJECT_ID`, and `UNLAYER_BASE_URL` when the corresponding constructor option is omitted. See [Authentication](/server/authentication) for how to get an API Key or Personal Access Token from Console.
The default API URL is `https://api.unlayer.com`. Pass `baseURL` only when intentionally targeting another environment.
---
## Available methods
The SDK exposes seven allowlisted methods. All methods hang off the `unlayer` instance created in [Quick start](#quick-start).
| Resource | Methods | Use for |
| -------------- | ----------------------------------------------------------------- | --------------------------------------------------------------------------------------------- |
| **Templates** | `templates.list()` · `templates.retrieve()` | List templates in a project (cursor-paginated) and fetch one by ID, including its design JSON |
| **Projects** | `projects.retrieve()` | Fetch a project by ID |
| **Workspaces** | `workspaces.list()` · `workspaces.retrieve()` | List accessible workspaces and fetch one by ID (PAT required) |
| **Convert** | `convert.fullToSimple.create()` · `convert.simpleToFull.create()` | Convert designs between the [Full](/design-schema/design-object) and Simple schema forms |
Every method is fully typed, so IDE autocomplete shows the accepted parameters and response shape. For API v3 operations that are not listed here, use the [Cloud API reference](/server/cloud-api/reference) and call the REST endpoint directly.
Template, project, and conversion methods accept an API Key or PAT. Workspace methods require a PAT. When a PAT request targets a project, configure `projectID` on the client.
---
## Highlights
- **Typed everywhere** — request parameters and response fields are fully typed; method signatures and field docs appear on hover in modern editors.
- **Great for AI agents** — the typed surface, JSDoc descriptions, and predictable error subclasses help coding agents call supported operations correctly. Combine it with [Skills](/ai/skills) for editor integration guidance.
- **Cursor pagination** — iterate over template pages or individual templates without handling cursors yourself.
- **Built-in retries** — connection errors, 408, 409, 429, and 5xx responses are retried twice by default with backoff; configure `maxRetries` per client or request.
- **Configurable timeouts** — each HTTP attempt times out after one minute by default; retries can make the complete operation take longer. Configure `timeout` per client or request.
- **Error subclasses** — `APIError` and status-specific subclasses expose the response status, headers, and parsed error body.
- **Server-side use** — API keys belong on your server; the SDK is built for backend / serverless / CI use, never the browser.
---
## Related
- **[Cloud API reference](/server/cloud-api/reference)** — the REST surface this SDK wraps.
- **[Design Schema](/design-schema/)** — the design JSON shape the SDK accepts and returns.
- **[CLI](/cli)** — terminal tool for the same account (login/init/pull/diff).
---
## Block object
# Block objects
A design's structure follows a fixed three-level hierarchy: **body → rows → columns → contents**. Every block object — body, row, column, content — shares the same envelope:
```ts
{
id?: string; // editor-assigned stable identifier
values: object; // styling and behavior for this block
// …container-specific arrays of children below
}
```
The shape of `values` depends on the block type and (for content blocks) on the display mode (email vs web vs document vs popup) — the embedded editor only surfaces options that make sense in the current mode.
## Body
The top-level container inside the [Design object](./design-object.md). Wraps an ordered list of rows and the body-level styling.
```json
{
"id": "body-1",
"rows": [
/* Row objects */
],
"values": {
"backgroundColor": "#ffffff",
"contentWidth": "600px",
"fontFamily": { "label": "Arial", "value": "arial,helvetica,sans-serif" }
}
}
```
| Field | Type | Notes |
| -------- | --------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
| `id` | `string` | Editor-assigned stable identifier. Required in the Full schema; designs from older editor versions without ids are repaired by migration. |
| `rows` | [Row\[\]](#row) | Ordered list of rows. |
| `values` | `object` | Body-level styling — background color, default font, content width, and so on. |
Email designs also accept `headers` and `footers` arrays — see [Design object → Email-only fields](./design-object.md#email-only-fields).
## Row
A horizontal slice of the body. Holds one or more columns and a cells layout that controls how the columns split the row's width.
```json
{
"id": "u_row_1",
"cells": [12],
"columns": [
/* Column objects */
],
"values": {
"columnsBackgroundColor": "",
"backgroundColor": "",
"padding": "0px",
"hideDesktop": false,
"hideMobile": false
}
}
```
| Field | Type | Notes |
| --------- | --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `id` | `string` | Editor-assigned stable identifier. Required in the Full schema; designs from older editor versions without ids are repaired by migration. |
| `cells` | `number[]` | The 12-column-grid layout for this row, e.g. `[12]` for a single full-width column, `[6, 6]` for two equal halves, `[4, 8]` for a 1/3-2/3 split. The numbers must sum to **12**. |
| `columns` | [Column\[\]](#column) | One column entry per cell — `cells.length === columns.length`. |
| `values` | `object` | Row-level styling: padding, background colors, device visibility, anchors, and so on. |
## Column
A vertical slice of a row. Holds a stack of content blocks and column-level styling.
```json
{
"id": "u_column_1",
"contents": [
/* Content objects */
],
"values": {
"backgroundColor": "",
"padding": "0px",
"border": {}
}
}
```
| Field | Type | Notes |
| ---------- | --------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
| `id` | `string` | Editor-assigned stable identifier. Required in the Full schema; designs from older editor versions without ids are repaired by migration. |
| `contents` | [Content\[\]](./content-types.md) | Ordered stack of content blocks rendered inside the column. |
| `values` | `object` | Column-level styling: background, padding, borders. |
## Content (envelope)
Every content block in a column shares a tagged-union envelope. The `type` field discriminates which content type the values shape comes from — see [Content types](./content-types.md) for the full enumeration.
```ts
{
id?: string;
type: 'text' | 'image' | 'button' | 'heading' | 'divider'
| 'html' | 'video' | 'social' | 'menu' | 'timer'
| 'custom';
// 'custom' blocks also carry a `slug: string` identifying the registered tool
values: object; // shape depends on `type` (and on the display mode)
}
```
See **[Content types](./content-types.md)** for the per-type `values` shapes.
## Related
- **[Design object](./design-object.md)** — the root that wraps everything.
- **[Content types](./content-types.md)** — what goes inside `column.contents`.
- **[Validate](/server/cloud-api/reference#operation/validateDesign)** — verify a block tree conforms to the schema.
---
## Content types
Every content block in a column carries the [Content envelope](./block-object.md#content-envelope) — `id`, `type`, and `values`. The `type` discriminates which shape `values` takes. This page is the per-type reference.
:::info Per-mode variants
Content blocks render in four display modes — **email**, **web**, **document**, **popup**. Each mode exposes a subset of `values` fields (e.g. email-only border-collapse handling, web-only hover states). The embedded editor surfaces only the options that apply to the active mode. [`/v3/templates/validate`](/server/cloud-api/reference#operation/validateDesign) applies the rules of one mode at a time — `email` unless you pass `displayMode` — so pass the mode your design was saved from.
:::
## Built-in types
There are 15 built-in content types. **Modes** lists the display modes where the type is available — "all" means `email`, `web`, `popup`, and `document`.
| `type` | Modes | What it is |
| ------------ | ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `button` | all | A call-to-action button — label, link, color, border, padding, alignment. |
| `carousel` | `email`, `web`, `popup` | An image slideshow. Interactive on web/popup and in AMP email. |
| `divider` | all | A horizontal rule with color, thickness, and width controls. |
| `form` | `web`, `popup` | A submittable form — configurable fields, layout, labels, and a submit button. |
| `heading` | all | An `h1`–`h4` heading. `values.headingType` controls the level. |
| `html` | `email`, `web`, `popup` | A raw-HTML escape hatch. Use sparingly — the editor renders the string verbatim, no sanitization. |
| `image` | all | An image with optional link, alt text, alignment, and per-device sizing. |
| `menu` | `email`, `web`, `popup` | A navigation menu — a list of labeled links with a shared style. |
| `page_break` | `document` | Forces a page break at this point when the document is exported. |
| `paragraph` | all | A rich-text paragraph stored as Lexical editor state in `values.textJson`. The editor inserts these for new text content. |
| `social` | all | A row of social-network icons with per-network URLs and a shared style. |
| `table` | all | A data table with header, body, and footer bands and per-cell styling. |
| `text` | all | The legacy rich-text block (TinyMCE era): `values.text` holds inline HTML. Kept for backward compatibility with existing templates — the editor now inserts [`paragraph`](#paragraph) (Lexical) instead. |
| `timer` | `email`, `web`, `popup` | A countdown to a target timestamp. Renders a server-side image so it works in email clients without JS. |
| `video` | `email`, `web`, `popup` | A YouTube/Vimeo video. Web and popup embed a player; email renders a linked thumbnail with an overlaid play icon. |
### Shared properties
Nearly every type's `values` carries this common envelope of layout and behavior fields — the exact subset varies by type and display mode. They are documented once here and omitted from the per-type tables below.
| Property | Type | Notes |
| ------------------------------------------------------------------ | -------------------------------------------- | --------------------------------------------------------------------------------------------------------- |
| `containerPadding` | `string` | CSS-style padding shorthand around the block, e.g. `"10px"` or `"10px 20px"`. |
| `anchor` | `string` | Optional fragment id for in-page anchor links. |
| `hideDesktop` | `boolean` | Hide on desktop breakpoint. |
| `hideMobile` | `boolean` | Hide on mobile breakpoint. |
| `displayCondition` | `object \| null` | Merge-tag-based show/hide condition; `null` = always show. |
| `_meta` | `{ htmlID: string, htmlClassNames: string }` | Stable identifiers for CSS targeting. Editor-managed. |
| `selectable`, `draggable`, `duplicatable`, `deletable`, `hideable` | `boolean` | Per-block editor permissions (all default `true`). Set to `false` to lock that interaction in the editor. |
| `locked` | `boolean` | Locks the block against all editing (default `false`). |
For the canonical per-type schema, validate a payload against [`/v3/templates/validate`](/server/cloud-api/reference#operation/validateDesign) — the response will tell you exactly which fields are required and which are extras.
### `button`
A call-to-action button with a label, click action, and full typography and box styling.
| Property | Type | Modes | Description |
| --------------- | -------------------------------------------------------------- | ----- | ---------------------------------------------------------------------------------------------------------------------- |
| `text` | `string` | | Legacy inline-HTML label, kept for backward compatibility with existing templates — new designs should set `textJson`. |
| `textJson` | `string` | | JSON-stringified Lexical editor state for the label — the current format (the editor is Lexical-based). |
| `href` | `{ name, attrs, values }` | | Click action: `{ name, values: { href, target } }` — `name` is the action type (`web`, `email`, `phone`, ...). |
| `buttonColors` | `{ color, backgroundColor, hoverColor, hoverBackgroundColor }` | | `{ color, backgroundColor, hoverColor, hoverBackgroundColor }` — CSS colors. |
| `size` | `{ autoWidth, width }` | | `{ autoWidth, width }` — set `autoWidth: false` to honor `width` (e.g. `"50%"`). |
| `fontFamily` | `{ defaultFont, type, label, value, url, weights }` | | `{ label, value }` — `value` is the CSS font stack; Google fonts also carry `url`. |
| `fontSize` | `string \| number` | | e.g. `"14px"`. |
| `lineHeight` | `string` | | e.g. `"120%"`. |
| `textAlign` | `'left' \| 'center' \| 'right' \| 'justify'` | | Button alignment in the column — `left`, `center`, `right`. |
| `padding` | `string` | | Inner padding, e.g. `"10px 20px"`. |
| `border` | `object` | | Per-side keys: `borderTopWidth`, `borderTopStyle`, `borderTopColor` (and `Left`/`Right`/`Bottom`). |
| `borderRadius` | `string` | | e.g. `"4px"`. |
| `_styleGuide` | `string \| null` | | |
| `ai_banner` | `never` | | |
| `fontWeight` | `number \| { label, value }` | | |
| `letterSpacing` | `number \| string` | | |
| `suggestions` | `never` | | |
| `synced` | `{ id, dirty, updatedAt } \| null` | | |
### `carousel`
An image slideshow. Fully interactive on web and popup and in the AMP email variant.
| Property | Type | Modes | Description |
| -------------- | ---------------------------------- | ----------------------- | -------------------------------------------------------------------- |
| `showPreviews` | `boolean` | `email`, `web`, `popup` | Show thumbnail previews under the active slide. |
| `previewWidth` | `number \| string` | `email`, `web`, `popup` | Thumbnail width, e.g. `"100px"`. |
| `autoplay` | `boolean` | `email`, `web`, `popup` | Auto-advance slides (AMP email variant only). |
| `loop` | `boolean` | `email`, `web`, `popup` | Wrap from the last slide back to the first (AMP email variant only). |
| `_styleGuide` | `string \| null` | `email`, `web`, `popup` | |
| `ai_banner` | `never` | `email`, `web`, `popup` | |
| `synced` | `{ id, dirty, updatedAt } \| null` | `email`, `web`, `popup` | |
The slides themselves live outside `values`: the content object carries a sibling `embedded` field — `{ "images": { "type": "image", "values": [ ... ] } }` — with one [`image`](#image)-shaped `values` object per slide (`src`, `altText`, `action`).
### `divider`
A horizontal rule.
| Property | Type | Modes | Description |
| ------------- | ---------------------------------------------------- | ----- | -------------------------------------------------------------------------------------------- |
| `width` | `number \| string` | | Line length as a percentage of the column, e.g. `"100%"`. |
| `border` | `{ borderTopColor, borderTopStyle, borderTopWidth }` | | `{ borderTopWidth, borderTopStyle, borderTopColor }` — style is `solid`, `dotted`, `dashed`. |
| `textAlign` | `'left' \| 'center' \| 'right' \| 'justify'` | | Where the line sits when narrower than the column — `left`, `center`, `right`. |
| `_styleGuide` | `string \| null` | | |
| `ai_banner` | `never` | | |
| `synced` | `{ id, dirty, updatedAt } \| null` | | |
### `form`
A submittable form with configurable fields and a submit button. `web` and `popup` modes only.
| Property | Type | Modes | Description |
| ---------------------- | -------------------------------------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| `action` | `{ method, target, url }` | `web`, `popup` | Submit endpoint: `{ url, method, target }` — `method` is `GET` or `POST`, `target` is `_self` or `_blank`. |
| `fields` | `array` | `web`, `popup` | One object per field: `{ name, type, label, placeholder_text, show_label, required, options? }` — `options` is a string array for choices. |
| `fieldWidth` | `string` | `web`, `popup` | Width of each field, e.g. `"100%"`. |
| `fieldDistance` | `string` | `web`, `popup` | Vertical space between fields, e.g. `"10px"`. |
| `formWidth` | `{ autoWidth, width }` | `web`, `popup` | `{ autoWidth, width }`. |
| `formAlign` | `'left' \| 'center' \| 'right' \| 'justify'` | `web`, `popup` | `left`, `center`, `right`. |
| `buttonText` | `number \| string` | `web`, `popup` | Submit button label. |
| `buttonColors` | `{ color, backgroundColor, hoverColor, hoverBackgroundColor }` | `web`, `popup` | `{ color, backgroundColor, hoverColor, hoverBackgroundColor }`. |
| `buttonAlign` | `'left' \| 'center' \| 'right' \| 'justify'` | `web`, `popup` | Submit button alignment. |
| `labelColor` | `string` | `web`, `popup` | Field label color — see also `labelFontFamily`, `labelFontSize`, `labelAlign`. |
| `_styleGuide` | `string \| null` | `web`, `popup` | |
| `ai_banner` | `never` | `web`, `popup` | |
| `buttonBorder` | `object` | `web`, `popup` | |
| `buttonBorderRadius` | `string` | `web`, `popup` | |
| `buttonFontFamily` | `{ defaultFont, type, label, value, url, weights }` | `web`, `popup` | |
| `buttonFontSize` | `string \| number` | `web`, `popup` | |
| `buttonMargin` | `string` | `web`, `popup` | |
| `buttonPadding` | `string` | `web`, `popup` | |
| `buttonWidth` | `{ autoWidth, width }` | `web`, `popup` | |
| `fieldBackgroundColor` | `string` | `web`, `popup` | |
| `fieldBorder` | `object` | `web`, `popup` | |
| `fieldBorderRadius` | `string` | `web`, `popup` | |
| `fieldColor` | `string` | `web`, `popup` | |
| `fieldFontFamily` | `{ defaultFont, type, label, value, url, weights }` | `web`, `popup` | |
| `fieldFontSize` | `string \| number` | `web`, `popup` | |
| `fieldPadding` | `string` | `web`, `popup` | |
| `labelAlign` | `'left' \| 'center' \| 'right' \| 'justify'` | `web`, `popup` | |
| `labelFontFamily` | `{ defaultFont, type, label, value, url, weights }` | `web`, `popup` | |
| `labelFontSize` | `string \| number` | `web`, `popup` | |
| `labelPadding` | `string` | `web`, `popup` | |
| `placeholderAlign` | `'left' \| 'center' \| 'right' \| 'justify'` | `web`, `popup` | |
| `synced` | `{ id, dirty, updatedAt } \| null` | `web`, `popup` | |
### `heading`
A heading. `headingType` controls the rendered level.
| Property | Type | Modes | Description |
| --------------- | --------------------------------------------------- | ----- | ----------------------------------------------------------------------------------------------------------------------------- |
| `text` | `string` | | Legacy inline-HTML heading text, kept for backward compatibility with existing templates — new designs should set `textJson`. |
| `textJson` | `string` | | JSON-stringified Lexical editor state for the heading — the current format (the editor is Lexical-based). |
| `headingType` | `'h1' \| 'h2' \| 'h3' \| 'h4'` | | `h1`, `h2`, `h3`, or `h4`. |
| `fontSize` | `string \| number` | | e.g. `"22px"`. |
| `fontFamily` | `{ defaultFont, type, label, value, url, weights }` | | `{ label, value }` — `value` is the CSS font stack. |
| `fontWeight` | `number \| { label, value }` | | `100`–`900`. |
| `color` | `string` | | Text color. |
| `textAlign` | `'left' \| 'center' \| 'right' \| 'justify'` | | `left`, `center`, `right`, `justify`. |
| `lineHeight` | `string` | | e.g. `"140%"`. |
| `linkStyle` | `object` | | `{ inherit, linkColor, linkHoverColor, linkUnderline, linkHoverUnderline }` — `inherit: true` uses the body's link styling. |
| `_styleGuide` | `string \| null` | | |
| `ai_banner` | `never` | | |
| `letterSpacing` | `number \| string` | | |
| `suggestions` | `never` | | |
| `synced` | `{ id, dirty, updatedAt } \| null` | | |
### `html`
A raw-HTML escape hatch.
| Property | Type | Modes | Description |
| ------------- | ---------------------------------- | ----------------------- | --------------------------------------------- |
| `html` | `string` | `email`, `web`, `popup` | Raw HTML rendered verbatim — no sanitization. |
| `_styleGuide` | `string \| null` | `email`, `web`, `popup` | |
| `ai_banner` | `never` | `email`, `web`, `popup` | |
| `synced` | `{ id, dirty, updatedAt } \| null` | `email`, `web`, `popup` | |
### `image`
An image with optional link and alt text.
| Property | Type | Modes | Description |
| ------------- | -------------------------------------------- | ----- | ------------------------------------------------------------------------------------------------------------------------------------ |
| `src` | `object` | | `{ url, width?, height?, autoWidth?, maxWidth? }` — `width`/`height` are intrinsic pixel numbers; `maxWidth` is a percentage string. |
| `altText` | `number \| string` | | Alternate text for accessibility and blocked-image fallback. |
| `textAlign` | `'left' \| 'center' \| 'right' \| 'justify'` | | Alignment in the column — `left`, `center`, `right`. |
| `action` | `{ name, attrs, values }` | | Optional click-through link: `{ name: "web", values: { href, target } }`. |
| `_styleGuide` | `string \| null` | | |
| `ai_banner` | `never` | | |
| `suggestions` | `never` | | |
| `synced` | `{ id, dirty, updatedAt } \| null` | | |
### `menu`
A navigation menu — a list of labeled links with a shared style.
| Property | Type | Modes | Description |
| --------------- | --------------------------------------------------- | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
| `menu` | `{ items }` | `email`, `web`, `popup` | `{ items: [...] }` — each item is `{ key, text, link }`; `key` is a unique id, `link` is `{ name, values: { href, target } }`. |
| `layout` | `'horizontal' \| 'vertical'` | `email`, `web`, `popup` | `horizontal` or `vertical`. |
| `align` | `'left' \| 'center' \| 'right' \| 'justify'` | `email`, `web`, `popup` | `left`, `center`, `right`. |
| `separator` | `string` | `email`, `web`, `popup` | Text rendered between items in horizontal layout. |
| `textColor` | `string` | `email`, `web`, `popup` | Item text color. |
| `linkColor` | `string` | `email`, `web`, `popup` | Link color. |
| `fontFamily` | `{ defaultFont, type, label, value, url, weights }` | `email`, `web`, `popup` | `{ label, value }`. |
| `fontSize` | `string \| number` | `email`, `web`, `popup` | e.g. `"14px"`. |
| `padding` | `string` | `email`, `web`, `popup` | Per-item padding, e.g. `"5px 15px"`. |
| `_styleGuide` | `string \| null` | `email`, `web`, `popup` | |
| `ai_banner` | `never` | `email`, `web`, `popup` | |
| `fontWeight` | `number \| { label, value }` | `email`, `web`, `popup` | |
| `letterSpacing` | `number \| string` | `email`, `web`, `popup` | |
| `synced` | `{ id, dirty, updatedAt } \| null` | `email`, `web`, `popup` | |
### `page_break`
Forces a page break at this point when the document is exported. `document` mode only.
| Property | Type | Modes | Description |
| ------------- | ---------------------------------- | ---------- | ----------------------------- |
| `color` | `string` | `document` | Color of the page-break rule. |
| `_styleGuide` | `string \| null` | `document` | |
| `ai_banner` | `never` | `document` | |
| `synced` | `{ id, dirty, updatedAt } \| null` | `document` | |
### `paragraph`
A rich-text paragraph stored as Lexical editor state — the block the editor inserts for all new text content.
| Property | Type | Modes | Description |
| --------------- | --------------------------------------------------- | ----- | ---------------------------------------------------------------------------- |
| `textJson` | `string` | | JSON-stringified Lexical editor state. Required. |
| `fontSize` | `string \| number` | | e.g. `"14px"`. |
| `fontFamily` | `{ defaultFont, type, label, value, url, weights }` | | `{ label, value }` — `value` is the CSS font stack. |
| `fontWeight` | `number \| { label, value }` | | `100`–`900`. |
| `color` | `string` | | Text color. |
| `textAlign` | `'left' \| 'center' \| 'right' \| 'justify'` | | `left`, `center`, `right`, `justify`. |
| `lineHeight` | `string` | | e.g. `"140%"`. |
| `linkStyle` | `object` | | `{ inherit, linkColor, linkHoverColor, linkUnderline, linkHoverUnderline }`. |
| `_styleGuide` | `string \| null` | | |
| `ai_banner` | `never` | | |
| `letterSpacing` | `number \| string` | | |
| `synced` | `{ id, dirty, updatedAt } \| null` | | |
### `social`
A row of social-network icons.
| Property | Type | Modes | Description |
| ------------- | -------------------------------------------- | ----- | ----------------------------------------------------------------------------------------------------------- |
| `icons` | `{ iconType, icons, editor }` | | `{ iconType, icons: [{ name, url }] }` — `name` is the network (e.g. `"Facebook"`), `url` the profile link. |
| `align` | `'left' \| 'center' \| 'right' \| 'justify'` | | `left`, `center`, `right`. |
| `iconSize` | `number \| string` | | Icon size in pixels (15–72). |
| `spacing` | `number \| string` | | Space between icons in pixels. |
| `_styleGuide` | `string \| null` | | |
| `ai_banner` | `never` | | |
| `synced` | `{ id, dirty, updatedAt } \| null` | | |
`iconType` picks the icon style: `circle`, `circle-black`, `circle-white`, `rounded`, `rounded-black`, `squared`, `squared-black`.
### `table`
A data table with optional header and footer bands, striped rows, and per-cell styling.
| Property | Type | Modes | Description |
| ---------------------------- | --------------------------------------------------- | ----- | ---------------------------------------------------------------------------------------------------------- |
| `table` | `{ headers, rows, footers }` | | The cell data: `{ headers, rows, footers }`, each an array of `{ cells, height }` rows — cell shape below. |
| `columns` | `number \| string` | | Column count (1–8); must match the number of cells per row. |
| `rows` | `number \| string` | | Body row count; must match `table.rows.length`. |
| `border` | `object` | | Per-side table border (`borderTopWidth`, `borderTopStyle`, `borderTopColor`, ...). |
| `enableHeader` | `boolean` | | Render the `table.headers` band. |
| `enableFooter` | `boolean` | | Render the `table.footers` band. |
| `stripedRows` | `boolean` | | Alternate body-row backgrounds. |
| `stripedRowsBackgroundColor` | `string` | | Stripe color. |
| `linkStyle` | `object` | | Link styling inside cells. |
| `_styleGuide` | `string \| null` | | |
| `ai_banner` | `never` | | |
| `cellBackgroundColor` | `{ property, selectedCellId }` | | |
| `cellColor` | `{ property, selectedCellId }` | | |
| `cellPadding` | `{ property, selectedCellId }` | | |
| `cellTextAlign` | `{ property, selectedCellId }` | | |
| `cellVerticalAlign` | `{ property, selectedCellId }` | | |
| `contentBackgroundColor` | `string` | | |
| `contentColor` | `string` | | |
| `contentFontFamily` | `{ defaultFont, type, label, value, url, weights }` | | |
| `contentFontSize` | `string \| number` | | |
| `contentFontWeight` | `number \| { label, value }` | | |
| `contentLetterSpacing` | `number \| string` | | |
| `contentLineHeight` | `string` | | |
| `contentPadding` | `string` | | |
| `contentTextAlign` | `'left' \| 'center' \| 'right' \| 'justify'` | | |
| `contentVerticalAlign` | `'top' \| 'middle' \| 'bottom'` | | |
| `footerBackgroundColor` | `string` | | |
| `footerColor` | `string` | | |
| `footerFontFamily` | `{ defaultFont, type, label, value, url, weights }` | | |
| `footerFontSize` | `string \| number` | | |
| `footerFontWeight` | `number \| { label, value }` | | |
| `footerPadding` | `string` | | |
| `footerTextAlign` | `'left' \| 'center' \| 'right' \| 'justify'` | | |
| `footerVerticalAlign` | `'top' \| 'middle' \| 'bottom'` | | |
| `headerBackgroundColor` | `string` | | |
| `headerColor` | `string` | | |
| `headerFontFamily` | `{ defaultFont, type, label, value, url, weights }` | | |
| `headerFontSize` | `string \| number` | | |
| `headerFontWeight` | `number \| { label, value }` | | |
| `headerPadding` | `string` | | |
| `headerTextAlign` | `'left' \| 'center' \| 'right' \| 'justify'` | | |
| `headerVerticalAlign` | `'top' \| 'middle' \| 'bottom'` | | |
Each cell in `table` is `{ text?, textJson?, width, backgroundColor?, color?, textAlign?, verticalAlign?, padding? }` — `width` is a percentage number, row `height` is in pixels, and cells store their content in `textJson` (Lexical editor state, the current format) with `text` as the legacy HTML field kept for existing templates — the same convention as [`button`](#button).
Each band also has a styling family of prefixed properties — `header*`, `content*`, and `footer*` (e.g. `headerBackgroundColor`, `contentFontSize`, `footerColor`) — covering font family, size, weight, colors, alignment, and padding per band.
### `text`
The legacy rich-text block from the TinyMCE era. `values.text` holds inline HTML; merge tags work via `{{ tag }}`. Kept for backward compatibility with existing templates — the editor now uses Lexical and inserts [`paragraph`](#paragraph) blocks for new text content.
| Property | Type | Modes | Description |
| --------------- | --------------------------------------------------- | ----- | --------------------------------------------------------------------------------------------- |
| `text` | `string` | | Inline HTML — ``, ``, ``, spans for color/size. Required on this legacy block. |
| `fontSize` | `string \| number` | | e.g. `"14px"`. |
| `fontFamily` | `{ defaultFont, type, label, value, url, weights }` | | `{ label, value }` — `value` is the CSS font stack. |
| `color` | `string` | | Text color. |
| `textAlign` | `'left' \| 'center' \| 'right' \| 'justify'` | | `left`, `center`, `right`, `justify`. |
| `lineHeight` | `string` | | e.g. `"140%"`. |
| `linkStyle` | `object` | | `{ inherit, linkColor, linkHoverColor, linkUnderline, linkHoverUnderline }`. |
| `_styleGuide` | `string \| null` | | |
| `ai_banner` | `never` | | |
| `fontWeight` | `number \| { label, value }` | | |
| `letterSpacing` | `number \| string` | | |
| `synced` | `{ id, dirty, updatedAt } \| null` | | |
### `timer`
A countdown to a target timestamp, rendered server-side as an animated image so it works in email clients without JS.
| Property | Type | Modes | Description |
| --------------------------------------------------------------------------- | -------------------------------------------- | ----------------------- | ---------------------------------------------------------------------------------------------- |
| `countdown` | `object` | `email`, `web`, `popup` | The timer definition — key sub-fields below. |
| `countdown.endTime` | `string` | `email`, `web`, `popup` | Target end time as `"YYYY-MM-DDTHH:mm:ss"` (no zone suffix — interpreted in `timezone`). |
| `countdown.timezone` | `string` | `email`, `web`, `popup` | IANA timezone, e.g. `"America/Los_Angeles"`. |
| `countdown.showLabels` | `boolean` | `email`, `web`, `popup` | Show the Days/Hours/Minutes/Seconds labels. |
| `countdown.digitColor`, `countdown.labelColor`, `countdown.backgroundColor` | `string` | `email`, `web`, `popup` | Colors for digits, labels, and the image background. |
| `countdown.digitFontSize`, `countdown.labelFontSize` | `number` | `email`, `web`, `popup` | Font sizes in pixels; font families via `digitFontFamily` / `labelFontFamily`. |
| `width` | `{ autoWidth, width }` | `email`, `web`, `popup` | `{ autoWidth, width }` — rendered image width. |
| `textAlign` | `'left' \| 'center' \| 'right' \| 'justify'` | `email`, `web`, `popup` | Alignment in the column. |
| `altText` | `number \| string` | `email`, `web`, `popup` | Alternate text for the rendered image. Empty or `"Countdown"` uses the end date in `timezone`. |
| `action` | `{ name, attrs, values }` | `email`, `web`, `popup` | Optional click-through link: `{ name: "web", values: { href, target } }`. |
| `_styleGuide` | `string \| null` | `email`, `web`, `popup` | |
| `ai_banner` | `never` | `email`, `web`, `popup` | |
| `synced` | `{ id, dirty, updatedAt } \| null` | `email`, `web`, `popup` | |
### `video`
A YouTube or Vimeo video. Web and popup embed a real player; email renders a linked thumbnail with an overlaid play icon (email clients can't run embedded players).
| Property | Type | Modes | Description |
| ------------- | ---------------------------------- | ----------------------- | ------------------------------------------------------------------------------------------------------ |
| `video` | `object` | `email`, `web`, `popup` | `{ url, type, videoId?, thumbnail?, playIconColor?, playIconSize? }` — `type` is `youtube` or `vimeo`. |
| `href` | `{ name, attrs, values }` | `email`, `web`, `popup` | Click-through action for the email thumbnail: `{ name, values: { href, target } }`. |
| `_styleGuide` | `string \| null` | `email`, `web`, `popup` | |
| `ai_banner` | `never` | `email`, `web`, `popup` | |
| `synced` | `{ id, dirty, updatedAt } \| null` | `email`, `web`, `popup` | |
## Custom tools
Embedders can register their own content types via `unlayer.registerTool(...)`. Custom blocks carry an extra `slug` discriminator:
```json
{
"type": "custom",
"slug": "my_pricing_block",
"values": {
/* shape defined by the embedder */
}
}
```
The `values` shape is whatever your tool definition declares — by default Unlayer validates the envelope and treats `values` as opaque. To go deeper, pass your tool declarations in the `customTools` field of [`/v3/templates/validate`](/server/cloud-api/reference#operation/validateDesign) and each declared option is checked with the exact value schema a built-in tool would have. See **[Custom Tools](/builder/tools/custom/create)** for the registration API.
## Related
- **[Design object](./design-object.md)** — the root that contains everything.
- **[Block object](./block-object.md)** — the rows / columns that hold these content items.
- **[Custom Tools](/builder/tools/custom/create)** — register your own content types.
- **[Validate](/server/cloud-api/reference#operation/validateDesign)** — verify a design against the canonical schema.
---
## Design object
# The Design object
The design object is the root of every Unlayer design. The embedded builder reads and writes it, the [Cloud API](/server/cloud-api/reference) exports, converts, and validates it, and every endpoint that takes a design accepts this shape.
## Shape
```json
{
"counters": {
"u_row": 4,
"u_column": 6,
"u_content_text": 3,
"u_content_image": 2,
"u_content_button": 1
},
"body": {
"id": "body-1",
"rows": [
/* Row objects */
],
"values": {
/* body-level styling */
}
},
"schemaVersion": 21
}
```
## Fields
| Field | Type | Required | Notes |
| --------------- | ---------------------------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `body` | [Body](./block-object.md#body) | yes | The single body of the design — rows, columns, content, body-level styling. Email designs also accept `body.headers` and `body.footers` arrays. |
| `counters` | `Record` | yes¹ | Per-type counters the editor uses to assign stable IDs to new blocks (e.g. `u_content_text: 3` means the next text block will be `u_content_text_4`). Required in the Full schema, optional in the [Simple schema](./schema-forms.md). |
| `schemaVersion` | `number` | no | The design-schema version the payload was authored against. Migrations apply forward when the editor loads a design from an older version. |
| `_conversion` | `{ data: string, version: number}` | no² | Present only on Simple-form designs that were produced with `includeConversion: true` on [`/v3/templates/convert/full-to-simple`](/server/cloud-api/reference#operation/convertFullToSimple). Pass it back to `simple-to-full` to [round-trip cleanly](./schema-forms.md#converting-between-forms). |
¹ Required in the Full schema; optional in the Simple schema.
² Only present on Simple-form designs produced with `includeConversion: true`.
## Email-only fields
`body` accepts two additional arrays in email designs:
| Field | Type | Notes |
| -------------- | -------------------------------- | ----------------------------------------------------------------------------------------------------- |
| `body.headers` | [Row\[\]](./block-object.md#row) | Rows pinned to the top of every page when the email is broken across pages (PDF / printed scenarios). |
| `body.footers` | [Row\[\]](./block-object.md#row) | Rows pinned to the bottom of every page. |
## Related
- **[Block object](./block-object.md)** — what's inside `body.rows`.
- **[Content types](./content-types.md)** — what each row's columns hold.
- **[Validate](/server/cloud-api/reference#operation/validateDesign)** — verify a design conforms to the schema.
---
## Design Schema
The **design schema** is how Unlayer represents a design — an email, landing page, popup, or document — as structured JSON. It's a single tree that captures the whole design: the layout (rows and columns), the content blocks inside them (text, images, buttons, and more), and the styling applied at every level.
That JSON is the shared contract across the platform: the embedded builder reads and writes it as users drag and drop, the [Cloud API](/server/cloud-api/reference) exports, converts, and validates it, and the [AI Assistant](/ai/assistant) generates and edits it. Learn it once and the same shape carries a design through storage, server-side transforms, AI generation, and HTML rendering. This section is the reference — each object gets its own page with typed fields and examples.
## Top-level objects
- **[Design object](./design-object.md)** — the root JSON object the editor reads and writes. Wraps a single `body`, plus counters and a schema version.
- **[Block object](./block-object.md)** — the containers inside a body: rows, columns, and the content items inside them.
- **[Content types](./content-types.md)** — the leaf content blocks: text, image, button, heading, divider, HTML, video, social, menu, timer, and the `custom` slot for embedder-defined tools.
## Full and Simple schemas
Every design exists in two interchangeable forms: a verbose **Full** schema the embedded editor manipulates in memory, and a compact **Simple** schema — the one the [AI Assistant](/ai/assistant) reads and writes, and the form Unlayer ships over the wire.
Not working with AI? You can ignore the Simple schema entirely and use the Full schema everywhere — it's what the editor loads, saves, and exports. See **[Full vs Simple](./schema-forms.md)** for what each form looks like side by side, how they convert (and round-trip losslessly), and why AI generation works in the Simple schema.
## Validation
Use [`POST /v3/templates/validate`](/server/cloud-api/reference#operation/validateDesign) to check whether a payload conforms to the schema before it lands in storage or in front of the editor — much better DX than letting a malformed design crash a render.
## Related
- **[Cloud API](/server/cloud-api/reference)** — the REST surface that consumes and produces these structures.
- **[Cloud API reference](/server/cloud-api/reference)** — the v2 export and template APIs that operate on designs.
- **[AI Assistant](/ai/assistant)** — generates and edits these structures in place inside the embedded editor.
---
## Full and Simple schemas
Every Unlayer design exists in two interchangeable forms of the same JSON. They describe the same design — same rows, columns, and content — but at different levels of verbosity.
:::tip Not working with AI? You only need Full.
If you're not building on the AI features, you can ignore the Simple schema entirely and work with the **Full** schema everywhere: it's what the editor loads, saves, and exports, and what [`POST /v3/templates/validate`](/server/cloud-api/reference#operation/validateDesign) checks by default (`schema: "full"`). Simple only enters the picture when a language model reads or writes the design — or when you explicitly [convert](#converting-between-forms).
:::
The one you reach for most when working with AI is the **Simple** schema.
## The Simple schema is the AI schema
When the [AI Assistant](/ai/assistant) generates or edits a design — and when you use the [template importer](/ai/template-importer) — the model reads and writes the **Simple** schema, not the Full one.
That's deliberate. The Simple form drops everything a language model doesn't need to reason about a design: editor bookkeeping, computed values, and any field already sitting at its default. The result is a much smaller payload that costs fewer tokens, is easier for a model to produce correctly, and contains only the fields that actually describe the design.
The editor always holds the **Full** design in memory. On an AI request it converts that to **Simple** before handing it to the model, validates the Simple JSON the model returns, then converts back to **Full** to apply it to the canvas. You never have to do this dance by hand inside the builder — but if you call the AI or convert APIs directly, knowing which form you're holding is the whole game.
:::note
Simple isn't _only_ for AI. It's also the compact form Unlayer stores and ships over the wire, and the shape the [Cloud API convert endpoints](/server/cloud-api/reference#operation/convertFullToSimple) produce. "AI schema" and "wire format" are the same Simple schema.
:::
## Get the schemas as JSON Schema files
Both the Full and Simple schemas are published as standard [JSON Schema](https://json-schema.org/) documents — the exact schemas [`/v3/templates/validate`](/server/cloud-api/reference#operation/validateDesign) checks against. No authentication required:
```
GET https://api.unlayer.com/v3/templates/schema # Full (default)
GET https://api.unlayer.com/v3/templates/schema?simple=true # Simple
GET https://api.unlayer.com/v3/templates/schema?displayMode=web # per display mode
```
Plug them into any JSON Schema validator, IDE, or codegen tooling. See [`GET /templates/schema`](/server/cloud-api/reference#operation/getDesignSchema) in the API reference.
## Full vs Simple at a glance
The **Full** schema is what the embedded editor manipulates in memory — every option, every computed default, every internal property. Verbose, but lossless.
The **Simple** schema is the compact projection of it. Going from Full to Simple:
- **Drops `counters`** — the editor's ID bookkeeping at the design root.
- **Strips editor- and admin-only fields** — `_meta`, `_styleGuide`, `selectable`, `draggable`, `duplicatable`, `deletable`, `hideable`, `locked`, `displayCondition`, `anchor`, and computed values like `calculatedWidth`/`calculatedHeight`.
- **Omits fields that equal their default** — e.g. a row whose `padding` is already `"0px"` simply won't carry it.
- **Reshapes some fields into terser forms** — most notably `border` (a per-side object becomes a CSS-shorthand string) and `fontSize` (`"14px"` becomes the number `14`).
Everything that's stripped or reshaped can be restored exactly — see [Converting between forms](#converting-between-forms).
## Structure, side by side
Here is the same design — one row, one column, one button — in each form. Watch `counters`, the `_meta`/`selectable`/`displayCondition` bookkeeping, `border`, and `fontSize`.
### Full
_84 lines · ~2.7 KB_
```json
{
"counters": { "u_row": 1, "u_column": 1, "u_content_button": 1 },
"body": {
"id": "body",
"rows": [
{
"id": "row_1",
"cells": [1],
"columns": [
{
"id": "column_1",
"contents": [
{
"id": "button_1",
"type": "button",
"values": {
"text": "Get started",
"href": {
"name": "web",
"values": {
"href": "https://example.com",
"target": "_blank"
}
},
"buttonColors": {
"color": "#FFFFFF",
"backgroundColor": "#0879A1",
"hoverColor": "#FFFFFF",
"hoverBackgroundColor": "#0879A1"
},
"size": { "autoWidth": true, "width": "100%" },
"fontSize": "14px",
"textAlign": "center",
"padding": "10px 20px",
"border": {
"borderTopWidth": "2px",
"borderTopStyle": "solid",
"borderTopColor": "#2dc26b"
},
"borderRadius": "4px",
"containerPadding": "10px",
"displayCondition": null,
"_meta": {
"htmlID": "u_content_button_1",
"htmlClassNames": "u_content_button"
},
"selectable": true,
"draggable": true,
"duplicatable": true,
"deletable": true,
"hideable": true,
"locked": false
}
}
],
"values": {
"backgroundColor": "",
"padding": "0px",
"border": {},
"_meta": { "htmlID": "u_column_1", "htmlClassNames": "u_column" }
}
}
],
"values": {
"backgroundColor": "",
"columnsBackgroundColor": "",
"padding": "0px",
"hideDesktop": false,
"_meta": { "htmlID": "u_row_1", "htmlClassNames": "u_row" },
"selectable": true,
"draggable": true,
"deletable": true
}
}
],
"values": {
"contentWidth": "500px",
"contentAlign": "center",
"textColor": "#000000",
"backgroundColor": "#F7F8F9",
"fontFamily": { "label": "Arial", "value": "arial,helvetica,sans-serif" },
"preheaderText": "",
"_meta": { "htmlID": "u_body", "htmlClassNames": "u_body" }
}
},
"schemaVersion": 27
}
```
### Simple
_59 lines · ~1.7 KB_
```json
{
"body": {
"id": "body",
"rows": [
{
"id": "row_1",
"cells": [1],
"columns": [
{
"id": "column_1",
"contents": [
{
"id": "button_1",
"type": "button",
"values": {
"text": "Get started",
"href": {
"name": "web",
"values": {
"href": "https://example.com",
"target": "_blank"
}
},
"buttonColors": {
"color": "#FFFFFF",
"backgroundColor": "#0879A1",
"hoverColor": "#FFFFFF",
"hoverBackgroundColor": "#0879A1"
},
"size": { "autoWidth": true, "width": "100%" },
"fontSize": 14,
"textAlign": "center",
"padding": "10px 20px",
"border": "2px solid #2dc26b, 0px solid #000, 0px solid #000, 0px solid #000",
"borderRadius": "4px",
"containerPadding": "10px"
}
}
],
"values": {
"backgroundColor": "",
"padding": "0px"
}
}
],
"values": {
"backgroundColor": "",
"columnsBackgroundColor": "",
"padding": "0px"
}
}
],
"values": {
"contentWidth": "500px",
"contentAlign": "center",
"textColor": "#000000",
"backgroundColor": "#F7F8F9",
"preheaderText": ""
}
},
"schemaVersion": 27
}
```
Both describe an identical button, yet the Simple form is **25 lines (~30%) shorter and ~38% smaller** — and it contains only the fields that carry meaning. That's exactly what makes it the right input and output for a language model, and the gap widens fast on a real, multi-row template where the stripped bookkeeping, defaults, and per-side `border` objects add up across every block.
## Converting between forms
Convert in either direction with the Cloud API:
- [`POST /v3/templates/convert/full-to-simple`](/server/cloud-api/reference#operation/convertFullToSimple) — Full → Simple.
- [`POST /v3/templates/convert/simple-to-full`](/server/cloud-api/reference#operation/convertSimpleToFull) — Simple → Full.
Two flags shape the output of full-to-simple:
- **`includeConversion: true`** attaches a `_conversion` block to the Simple result. It records the fields that were stripped or reshaped, including legacy values removed while migrating an older design, so that `simple-to-full` can rebuild the original Full design exactly — a lossless round-trip. Without it, stripped editor metadata and unknown fields can't be recovered. See [`_conversion`](./design-object.md#fields) on the Design object.
Older version-1 `_conversion` blocks restore codec-stripped fields but do not downgrade the schema version of current-shaped output. Current version-1 blocks add the migration delta needed to restore the original version safely; older readers ignore that additive data and still complete the conversion. If the Simple design edits a value that an older migration reshaped, the reverse conversion keeps the current schema version so the edited value is never mislabeled as an older schema shape.
- **`includeDefaultValues: true`** keeps default-valued fields in the Simple output instead of omitting them.
## Validation
Before storing a design or handing it to the editor, check it against the canonical schema with [`POST /v3/templates/validate`](/server/cloud-api/reference#operation/validateDesign). Pass `displayMode` (`email`, `web`, `document`, or `popup`) so the right per-mode field rules apply — it defaults to `email` when omitted. Much better DX than letting a malformed design crash a render.
## Related
- **[Design object](./design-object.md)** — the root JSON object and the `_conversion` round-trip block.
- **[Block object](./block-object.md)** — the rows, columns, and content envelope shared by both forms.
- **[Content types](./content-types.md)** — the per-type `values` shapes.
- **[AI Assistant](/ai/assistant)** — generates and edits designs in the Simple form.
- **[Cloud API](/server/cloud-api/reference)** — the REST surface that converts and validates these structures.