Skip to content

Event Hooks

Event hooks allow developers to execute custom code in response to specific events within Sveltia CMS. This feature enables advanced customization and integration with other systems by providing a way to listen for and react to various actions taken within the CMS.

Overview

To register an event listener, use the registerEventListener method on the CMS object:

js
CMS.registerEventListener({ name, handler });

The registerEventListener method allows you to register a callback function (handler) that will be invoked when a specific event (name) occurs within the CMS. The handler function receives an object containing relevant data about the event, allowing you to perform custom logic based on the event context.

Multiple event listeners can be registered for the same event, and they will be executed in the order they were registered.

Parameters

  • name (string): The name of the event to listen for. See the Supported Events section for a list of available events.
  • handler (function): A callback function that will be executed when the event is triggered. See the Event Handler section for details on the parameters passed to the handler.

Supported Events

The following events are supported for event hooks:

  • preSave: Triggered before an entry is saved. You can modify the entry data before it is persisted.
  • postSave: Triggered after an entry has been saved.

Additionally, the following events are available when using Editorial Workflow:

  • prePublish: Triggered before an entry is published. You can modify the entry data before it is persisted.
  • postPublish: Triggered after an entry has been published.
  • preUnpublish: Triggered before an entry is unpublished.
  • postUnpublish: Triggered after an entry has been unpublished.

Event Handler

The handler function receives an object with the following properties:

  • author: The author object that contains the login (login name) and name (display name) of the user who triggered the event. It’s not available for the Local Workflow since it doesn’t track user information.
  • entry: The entry object serialized to an Immutable Map. It contains the following properties:
    js
    {
      data: { ... }, // Default locale data
      i18n: {
        [locale]: {
          data: { ... } // Non-default locale data
        }
      },
      slug, // Entry slug
      path, // Entry path
      newRecord, // Boolean indicating if it's a new entry
      collection, // Collection name
      mediaFiles, // Array of associated media files
    }

For the preSave and prePublish events, the handler can return a modified entry object in Immutable Map format to change the data before it is saved. The handler can be asynchronous and return a Promise that resolves to the modified entry or entry data.

For other events, the return value is ignored.

Examples

Modifying Entry Data Before Save

The following example demonstrates how to register a pre-save hook that adds a last modified timestamp to the entry data before it is saved.

js
CMS.registerEventListener({
  name: 'preSave',
  handler: ({ entry }) => {
    return entry.get('data').set('last_modified', new Date().toISOString());
  },
});

Accessing I18n Data

If you have internationalization (i18n) support enabled, localized data can be accessed and modified within the event handlers, under the i18n property of the entry object. The following example shows how to read and update localized fields in a pre-save hook, assuming the entry has English (default), French and other locales configured.

js
CMS.registerEventListener({
  name: 'preSave',
  handler: ({ entry }) => {
    console.info('English Title:', entry.getIn(['data', 'title']));

    entry.get('i18n').forEach((localeData, locale) => {
      console.info(`Locale (${locale}) Title:`, localeData.getIn(['data', 'title']));
    });

    return entry.setIn(['i18n', 'fr', 'data', 'title'], 'Titre en Français');
  },
});

The getIn and setIn methods from Immutable.js are used to work with nested data structures.

Accessing Media Files

Getting Notification of Saved Entries

The following example demonstrates how to register a post-save hook that logs information about the saved entry and the author who made the changes.

js
CMS.registerEventListener({
  name: 'postSave',
  handler: ({ author, entry }) => {
    console.log(`Entry saved by ${author?.login ?? 'Unknown'}:` entry.toJS());
  },
});

The toJS method from Immutable.js is used to convert the entry object back to a plain JavaScript object for easier logging.

Released under the MIT License.