Appearance
Callbacks
Callbacks are how the editor reports events back to your application. Configuration travels into the editor through the config object ("props down"), and events travel back out through the callback functions you pass next to it ("callbacks up"). Saves, test sends, file manager actions, undo and redo, and errors all surface this way.
Every callback is optional. Register only the ones your integration reacts to.
How to use Callbacks
Callbacks are top-level properties of the object passed to TopolEmailEditor(), next to config. They are not part of the options object:
ts
const TOPOL_OPTIONS = {
// other options...
};
const editor = TopolEmailEditor({
config: TOPOL_OPTIONS,
onSave({ json, html, mutations, syncedSections }) {
// Handle save logic
},
onInit() {
// Handle editor initialization
},
// more callbacks...
});Every callback receives at most one argument: a payload object with named properties, as listed in its heading below. Destructure just the properties you need. Callbacks documented with empty parentheses receive no argument at all.
Available Callbacks and their Usage
onSave({ json, html, mutations, syncedSections })
Triggered when the Save button is clicked or when editor.save() is called manually. This is the callback that hands you the template to store, so an integration that persists templates needs at least this one.
Use this to save the template data (json) and its HTML output (html) to your backend or local storage. The mutations property is used only by the Multilingual Template feature, and arrives as an array of { code, primary } entries describing each language mutation. Without that feature it is an empty array and can be ignored.
The syncedSections property is an array of synced section IDs (number[]) that are currently placed in the template. The editor walks the template's body sections and returns every syncedId it finds. Use this list to look the synced sections up in your api.SAVED_SECTIONS storage and pass them to the Convert JSON template to HTML endpoint when re-rendering. If you are not using synced sections, this will be an empty array. See Server-Side Resolution for the full render pipeline.
The email subject line is accessible from the json property at json.attributes["mj-subject"].text. When using multilingual templates, per-language subject lines are stored in json.langs[].translations["mj-subject"].content.
onSave may return a Promise. While it is pending, the editor keeps its saving indicator active, so your users see the save spinner until your backend has actually stored the template. A resolved Promise (or no return value at all) completes the save; a rejected Promise makes the editor show a saving error instead of the success notification.
If the Promise hasn't settled after 30 seconds, the editor stops waiting and tells the user that the save hasn't been confirmed: "The template was handed to the host, but it has not confirmed the save yet. Please check that your changes were stored." The template then stays marked as unsaved. It is marked as saved only when the Promise resolves within those 30 seconds and nothing was edited while the save was running.
ts
const editor = TopolEmailEditor({
config: TOPOL_OPTIONS,
async onSave({ json, html, mutations, syncedSections }) {
// save json and html to your infrastructure.
// save mutations only if using Multilingual Templates.
// persist syncedSections (array of IDs) only if using Synced Sections.
const res = await fetch("/api/templates", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ json, html }),
});
// fetch resolves on 4xx/5xx too; throw so the editor shows a saving error.
if (!res.ok) throw new Error(`Save failed: ${res.status}`);
// The editor shows the save spinner until this async function settles.
},
});One save at a time
The editor runs one save at a time. editor.save() returns a Promise that settles after the export finished and your onSave Promise settled, so the onSave that fires while it is pending is the answer to that call. Calling editor.save() while a save is still running (yours, or one started from the Save button) rejects with an error whose code is "SAVE_IN_PROGRESS" and fires no onSave.
js
try {
await editor.save();
} catch (err) {
if (err.code === "SAVE_IN_PROGRESS") {
// A save is already running; its onSave carries the current template.
}
}The rejection reaches your page as a plain Error, because the editor runs in an iframe and an error's class does not survive the crossing. Check err.code rather than instanceof or the message text.
Every other outcome resolves the editor.save() Promise, so the callbacks tell success from failure. When the render fails, onSave does not fire and onEditorError fires with source: "save". When your onSave Promise rejects, onSave has already fired, and the editor then shows its saving error and fires onEditorError with source: "save" and detail.stage: "host". An onSave Promise that is still pending after 30 seconds is released without an error: the editor shows a notice that the save was not confirmed and keeps the template marked as unsaved.
onSaveAndClose({ json, html, mutations, syncedSections })
Called when the Save and Close button is clicked in the editor Top Bar.
Use this for saving and then exiting the editor or redirecting the user. The mutations and syncedSections properties are identical to those passed to onSave.
Like onSave, it may return a Promise: the editor stays in its saving state until it settles, so you can finish persisting before tearing the editor down. If the Promise rejects, the editor shows a saving error. Treat that as the cue not to close it.
ts
const editor = TopolEmailEditor({
config: TOPOL_OPTIONS,
async onSaveAndClose({ json, html, mutations, syncedSections }) {
// save json and html to your infrastructure, then close the editor
await persistTemplate({ json, html });
closeEditorModal();
},
});onTestSend({ email, json, html })
Fires when a user sends a test email from the preview screen.
The email property is a single address by default. With testingEmails set to true it is always an array of addresses.
Use this callback to send test emails through your own service (SendGrid, Mailgun, custom SMTP, or anything else).
ts
const editor = TopolEmailEditor({
config: TOPOL_OPTIONS,
onTestSend({ email, json, html }) {
// send a test email using your preferred sender
},
});onOpenFileManager()
Called when a user clicks "Choose a file" inside image or video properties. Takes no arguments.
Use this to open your own file manager UI, as described in custom file manager.
ts
const editor = TopolEmailEditor({
config: TOPOL_OPTIONS,
onOpenFileManager() {
// open your custom filemanager dialog window
},
});onImageDelete({ items })
Fires when a user removes one or more files or folders from the built-in File Manager. The callback runs only after the deletion has succeeded, so the items it reports have already been removed from your storage.
Use this to keep your own system in sync with the editor, for example to clean up records in your database, update an external asset library, or log removals.
ts
const editor = TopolEmailEditor({
config: TOPOL_OPTIONS,
onImageDelete({ items }) {
// react to removed files and folders, e.g. clean up your own records
items.forEach((item) => {
console.log(`${item.type} removed: ${item.name} (${item.path})`);
});
},
});The items property is an array, with one entry per deleted file or folder. Each entry has the following shape:
| Field | Type | Description |
|---|---|---|
name | string | The name of the deleted file or folder. |
type | "file" | "folder" | Whether a file or a folder was deleted. |
path | string | The location of the item within the File Manager. |
url | string (optional) | The item's URL. This may be a temporary blob: URL for files that were uploaded in the same session but never persisted, so do not rely on it being long-lived or fetchable. |
key | string | null | The storage key of the item. This is null for folders and for items without an original key, and a string otherwise. |
Deletion works normally whether or not this callback is registered.
onInit()
Executed when the editor is fully initialized.
Commonly used to hide loading spinners or initialize user tracking once the editor is ready. Takes no arguments.
ts
const editor = TopolEmailEditor({
config: TOPOL_OPTIONS,
onInit() {
// hide the loader or track the usage
},
});onLoaded()
Fires after calling editor.load(YOUR_TEMPLATE) and the template is fully rendered. Takes no arguments.
ts
const editor = TopolEmailEditor({
config: TOPOL_OPTIONS,
onLoaded() {
// hide the loader
},
});onTemplateUpdated()
Fires after calling editor.updateTemplate(YOUR_TEMPLATE) and the template is successfully updated.
ts
const editor = TopolEmailEditor({
config: TOPOL_OPTIONS,
onTemplateUpdated() {
// template was updated programmatically
},
});onSavedSectionSave({ section })
Triggered when a user saves a section to their personal library and savedSections is configured as a local array (manual mode).
Use this to store the block definition on your own infrastructure. See saved sections for the full picture.
ts
const editor = TopolEmailEditor({
config: TOPOL_OPTIONS,
onSavedSectionSave({ section }) {
// save the block on your infrastructure
},
});Saved sections vs synced sections
onSavedSectionSavefires wheneversavedSectionsis not literallytrue(i.e. an array, or the defaultfalse). SettingsavedSections: trueswitches the panel into API-based mode and the save flow goes straight to yourapi.SAVED_SECTIONSendpoint instead.onSavedSectionEditandonSavedSectionRemoveonly fire when the legacy local-array panel is rendered. Configuringapi.SAVED_SECTIONSis enough to switch the panel into API mode and silence these callbacks, even ifsavedSectionsis still an array.- Synced sections always run in API-based mode and never trigger any of these callbacks. To react to synced section changes, implement the
api.SAVED_SECTIONSendpoints on your server instead.
onSavedSectionRemove({ id })
Fires when a user removes a saved section in manual mode. Does not fire for API-based saved sections or for synced sections, as those are handled through the api.SAVED_SECTIONS endpoint. See saved sections.
ts
const editor = TopolEmailEditor({
config: TOPOL_OPTIONS,
onSavedSectionRemove({ id }) {
// remove the block on your infrastructure
},
});onSavedSectionEdit({ id })
Called when a user edits an existing saved section in manual mode. Does not fire for API-based saved sections or for synced sections, as edits to those are persisted via PATCH calls against your api.SAVED_SECTIONS endpoint. See saved sections.
ts
const editor = TopolEmailEditor({
config: TOPOL_OPTIONS,
onSavedSectionEdit({ id }) {
// edit the block on your infrastructure
},
});onEditorClose()
Fires when a user closes the editor without saving, from the close button in the Window Bar. The button appears only when windowBar includes "close". Takes no arguments.
Use it to navigate away, unmount the editor, or restore your own interface. To warn about unsaved work first, see onUnsavedChangesChange.
ts
const editor = TopolEmailEditor({
config: TOPOL_OPTIONS,
onEditorClose() {
// leave the editor screen
},
});onUnsavedChangesChange({ hasUnsavedChanges })
Reports whether the template currently holds unsaved changes via the boolean hasUnsavedChanges property. It fires on every transition in both directions, so the value stays accurate as the user edits and saves.
A save only clears the flag when the template still matches what was sent. Edits made while an export is running keep the template marked as unsaved, so hasUnsavedChanges stays true (no callback fires, because nothing changed) until a later save covers those edits.
Store the value to drive your own exit flow, for example blocking a route change or enabling a save button. See the unsaved changes guide for the related showUnsavedDialogBeforeExit option.
ts
const editor = TopolEmailEditor({
config: TOPOL_OPTIONS,
onUnsavedChangesChange({ hasUnsavedChanges }) {
// true = unsaved changes, false = fully saved
},
});onTemplateRename({ name })
Fires when a user clicks the rename (pencil) icon next to the template name in the Window Bar, with the name property holding the current template name as a string. Requires the renameTemplate: true option, which places the icon. The editor has no rename input of its own - the callback only signals that the user wants to rename.
Collect the new name in your own UI, persist it, then call editor.setTemplateName() to reflect it in the editor. See rename template.
ts
const editor = TopolEmailEditor({
config: TOPOL_OPTIONS,
onTemplateRename({ name }) {
// open your own rename dialog, prefilled with the current name
},
});onTestingEmailsChange({ emails })
Fires when a user edits the list of test email addresses in the preview screen, with the emails property holding the updated list as an array of strings. Relevant when testingEmails is enabled, so the addresses persist between sessions rather than being retyped.
ts
const editor = TopolEmailEditor({
config: TOPOL_OPTIONS,
onTestingEmailsChange({ emails }) {
// persist the updated address list
},
});onUndoChange({ count })
Fired whenever the undo history changes: after an edit, an undo or a redo. The count property is the number of steps that can currently be undone, which makes it a direct fit for enabling or disabling an Undo button in a custom top bar.
ts
const editor = TopolEmailEditor({
config: TOPOL_OPTIONS,
onUndoChange({ count }) {
undoButton.disabled = count === 0;
},
});onRedoChange({ count })
Fired whenever the redo history changes. The count property is the number of steps that can currently be redone. A new edit after an undo clears the redo history.
ts
const editor = TopolEmailEditor({
config: TOPOL_OPTIONS,
onRedoChange({ count }) {
redoButton.disabled = count === 0;
},
});onPreview({ html })
Called when the user enters the Preview mode.
ts
const editor = TopolEmailEditor({
config: TOPOL_OPTIONS,
onPreview({ html }) {
// ...
},
});onPreviewClose()
Called when the user exits the Preview mode and returns to the editor. Useful for syncing host-app UI that should only be visible while preview is active (e.g., a host-rendered Dark Mode toggle).
Takes no arguments. The rendered HTML was already delivered to your host on entry via onPreview.
ts
const editor = TopolEmailEditor({
config: TOPOL_OPTIONS,
onPreviewClose() {
// ...
},
});onAlert({ notification })
Replaces the built-in notifications with your own alert system. This callback fires only while disableAlerts: true is set, since the editor either renders a notification itself or forwards it here, never both. Notifications you raise yourself with editor.createNotification() are the exception: those always render in the editor, so they do not arrive here.
See custom notifications for the full setup.
ts
const editor = TopolEmailEditor({
config: TOPOL_OPTIONS,
onAlert({ notification }) {
//use your own notification, or create proxy for built-in notifications
},
});onEditorError({ source, message, detail })
Fires when the editor encounters an unrecoverable error. Useful for diagnostics and fallbacks. One source, templateLoad, is a notice rather than a failure: the editor keeps working.
The source property tells you where the error comes from. The NPM packages export the list as the EditorErrorSource type:
integration- The NPM wrapper or loader could not start the editor (for examplerender()failed or the iframe never booted). Only the NPM packages report it.init- The editor started but crashed while initialising, for example after a failedauthorize.load- Indicates that the JSON of the template is not correct and editor cannot read it correctly.network- Indicates that network issue happened during internal or external (endpoints given in API property inTOPOL_OPTIONS) Fetch/XHR calls.authorize- Invalid API key or wrong/unverified domain. With nonce authentication also a missinggetNoncecallback or a first nonce that could not be obtained.nonceAuth- A scheduled nonce refresh failed (getNoncerejected, timed out or returned something other than a nonce). The editor keeps working on the last valid nonce until it expires.updateTemplate- Indicates that the template passed toeditor.updateTemplate()could not be parsed (invalid JSON)templateLoad- The template loaded, but something in it does not fit the options. Reported when the template carries several languages but themultilingualoption is off. The template loaded and stays editable in its primary language; the other languages are kept as stored and returned unchanged on save. Turnmultilingualon to make them editable.detailis{ languages }, the language codes of the template.save- A save did not complete: the HTML render failed or youronSave/onSaveAndClosePromise rejected. The editor shows its "saving error" notification and fires this callback as well. A rejectedonSavetherefore reaches you twice: first as theonSavecall itself, then as this error.
When many users hit errors at the same time, check status.topol.io for an incident on Topol's side.
The optional detail property (unknown) contains the raw parsed response body from your server (error.response.data) for network errors. It is available for all HTTP error responses (4xx, 5xx) and is undefined for network errors where no response was received. A backend that returns JSON delivers the parsed object directly.
For source: "save", detail is { stage, langCode }: stage is "render" or "host" (your callback rejected), and langCode echoes what was passed to editor.save({ langCode }) (undefined for saves started from the editor's own UI). See one save at a time.
js
const editor = TopolEmailEditor({
config: TOPOL_OPTIONS,
onEditorError({ source, message, detail }) {
if (source === "network") {
console.log("Network issue: " + message);
// Access custom error data from your backend
if (detail?.errors) {
detail.errors.forEach((err) => {
editor.createNotification({
text: err.detail,
type: "error",
});
});
}
}
},
});Language State Callbacks
These callbacks keep external UI in sync with the editor's Multilingual Templates state. They fire whenever a language mutation is created, deleted, or selected, and when the primary language changes. Both the built-in UI and programmatic API calls trigger them.
onLanguageCreated({ code, mutations })
Triggered when a new language mutation is created, either via the editor UI or by calling editor.createLanguage(code).
code: the language code of the newly created mutation (e.g."fr")mutations: the updated array of all mutations after the creation
ts
const editor = TopolEmailEditor({
config: TOPOL_OPTIONS,
onLanguageCreated({ code, mutations }) {
console.log(`Language "${code}" created. Current mutations:`, mutations);
// Update your external language selector
},
});onLanguageDeleted({ code, mutations })
Triggered when a language mutation is deleted. Deletion always requires user confirmation via a modal dialog, whether initiated from the UI or via editor.deleteLanguage(code).
code: the language code of the deleted mutationmutations: the updated array of all remaining mutations after the deletion
ts
const editor = TopolEmailEditor({
config: TOPOL_OPTIONS,
onLanguageDeleted({ code, mutations }) {
console.log(`Language "${code}" deleted. Remaining mutations:`, mutations);
// Update your external language selector
},
});onLanguageSelected({ code })
Triggered when the active editing language changes, either via the editor UI dropdown or by calling editor.selectLanguage(code). Does not fire if the requested language is already active or does not exist.
code: the language code of the newly active mutation
ts
const editor = TopolEmailEditor({
config: TOPOL_OPTIONS,
onLanguageSelected({ code }) {
console.log(`Switched to language "${code}"`);
// Highlight the active language in your external UI
},
});onPrimaryLanguageChanged({ code, mutations })
Triggered when the primary language is changed via the editor UI or by calling editor.setPrimaryLanguage(code). If the language does not yet exist, it will be created first (firing onLanguageCreated as well).
code: the language code of the new primary mutationmutations: the updated array of all mutations reflecting the new primary assignment
ts
const editor = TopolEmailEditor({
config: TOPOL_OPTIONS,
onPrimaryLanguageChanged({ code, mutations }) {
console.log(`Primary language changed to "${code}"`);
// Update your external UI to reflect the new primary
},
});onGetMutations({ mutations })
Triggered when editor.getMutations() is called, with the same list that call resolves to. Reading the mutations does not modify any state.
mutations: array of all current mutations, each withcode(string) andprimary(boolean)
editor.getMutations() also resolves with the same list, so awaiting the call works without this callback.
ts
const editor = TopolEmailEditor({
config: TOPOL_OPTIONS,
onGetMutations({ mutations }) {
console.log("Current mutations:", mutations);
// Use this data to populate your external language selector
},
});getNonce()
The only callback that returns a value. Passing it turns on nonce authentication: the editor calls it at boot and again before the current nonce expires, and awaits the Promise. It must resolve to a fresh nc_… nonce minted on your backend from the Secret key.
ts
const editor = TopolEmailEditor({
config: TOPOL_OPTIONS,
async getNonce() {
const res = await fetch("/api/topol/nonce", { method: "POST" });
return (await res.json()).nonce;
},
});A rejected Promise, a non-string result or no answer within 15 seconds counts as a failed refresh; see onEditorError above for how it is reported.
