Disclaimer: This website requires Please enable JavaScript in your browser settings for the best experience.

HomeDev GuideRecipesAPI Reference
Dev GuideAPI ReferenceUser GuideGitHubNuGetDev CommunityOptimizely AcademySubmit a ticketLog In
Dev Guide

Enable live preview

Optimizely CMS (SaaS) provides a user-friendly WYSIWYG (what you see is what you get) authoring interface.

Optimizely CMS (SaaS) provides a user-friendly WYSIWYG (what you see is what you get) authoring interface. To ensure compatibility, you should develop your application's views with this in mind. The preview functionality is framework-agnostic, and you can use plain JavaScript.

You must complete four main tasks to enable a live preview of the content.

  1. Configure an application.
  2. Enable communication between CMS (SaaS) and your application.
  3. Enable property overlays.
  4. Refresh the application's view when content has changed.

Prerequisites

To complete the following steps, you must create a

Configure application

CMS (SaaS) requires information about your application, particularly its URL.

  1. Go to Settings > Applications.
  2. Click Create Application.
  3. Enter an Application Name. The API ID is automatically generated. If you want to update it, click Change.

    📘

    Note

    The API ID must have 2 to 255 characters and start with a lowercase or uppercase letter followed by any combination of letters, digits, or underscores.

  4. Select From Existing and click on an existing page to use as your start page. Or, select New to create a new Experience or Page as your start page.
  5. Click Create Application.
  6. After the application is created, click on the Application Name or click More > Edit.
  7. Click on the Hostnames tab.
  8. Click Add Hostname and add a Hostname where Optimizely can locate your application.

    📘

    Note

    Your Hostname can be a local hostname on your computer, for example localhost:5000. See Get started with a demo site to get started quickly.

  9. (Optional) Select or deselect Use a secure connection (HTTPS).
  10. Click Add.

Enable communication between CMS and your application

For seamless content updates, CMS (SaaS) must notify your application whenever editors change the content. Additionally, the system needs to identify which properties your view is rendering and how to display an overlay for them. To establish this communication, you must implement a script that facilitates interaction between CMS (SaaS) and your application.

You must embed the https://app-[UUID].cms.optimizely.com/util/javascript/communicationinjector.js script (available from your instance) in your application to preview content in CMS (SaaS). Replace [UUID] with your instance's ID.

🚧

Important

If your application has configured Content Security Policies (CSP), make sure the policies let you embed your application in an iframe and lets the communication script be loaded from your CMS (SaaS) URL: https://app-[UUID].cms.optimizely.com.

Content preview

You can use the CMS (SaaS) URL to determine when content is being previewed. CMS (SaaS) uses the following URL format:

https://your-app.com/preview?key={key}&ver={version}&loc={locale}&ctx={edit|preview}&preview_token={token}
  • /preview – Check if the current path is /preview.
  • preview_token – Check if the incoming URL contains the preview_token parameter.
  • ctx – Check if the context mode is set to edit or preview. See the Context modes section for information.
  • ver – Identify the version of the content being previewed.
  • loc – Check the locale of the content.

📘

Note

The preview URL format is fixed, but soon you can define your own format.

Authorization

Live preview requires access to unpublished content, such as drafts. To retrieve this content from Optimizely Graph, use the preview_token provided in the URL.

Extract the token and use it in the Authorization header of your GraphQL request:

curl --location 'https://cg.optimizely.com/content/v2' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer {the preview token}' \
--data '{ your GraphQL query }'

📘

Note

The preview token is valid for five minutes.

Enable property overlays

To create an interactive editing environment, CMS (SaaS) lets you enable property overlays. These overlays offer a visual representation of editable content properties, letting you easily click and edit them. In Visual Builder, the preview automatically scrolls the preview to the property that is being edited.

Example of property overlays in place in the Visual Builder.

Example of property overlays in Visual Builder.

Required attributes

Use data-epi-block-id on all blocks, sections, rows, and columns. This attribute is required for Visual Builder to recognize and select components. Set its value using the key returned by your Optimizely Graph query.

Use data-epi-edit on individual properties that should be editable. Set its value to the property name, such as heading, body, or title.

The user interface introduces the data-epi-edit attribute that can be added to editable DOM elements:

<section data-epi-block-id="block_abc123">
  <h2 data-epi-edit="heading">Welcome</h2>
  <p data-epi-edit="bodyText">This is the main content</p>
</section>

Each component that should be selectable in the Visual Builder must have a data-epi-block-id attribute matching the content item's id. Add data-epi-edit to individual elements that represent CMS properties.

📘

Note

The id field from each content item in your GraphQL query (for example, rows, columns, components) must be rendered as the data-epi-block-id attribute.

The structure of your GraphQL query must match the structure of your DOM. For example, if a row contains columns, and each column contains components, your rendered HTML must reflect this nesting.

This ensures that the Visual Builder can locate and display overlay editing controls correctly.

Encapsulate the rendering of these HTML attributes within a shared function that ensures they are only rendered during content preview and when the context mode is set to edit.

Context modes

Two context modes are available when previewing content: edit and preview. The context mode is determined by the ctx query parameter in the preview URL. You should only render data-epi-edit and data-epi-block-id attributes when the context mode is edit. This prevents overlays from affecting the user experience during normal content preview. This lets editors preview the content without the property overlays blocking the view. See Visual Builder.

Refresh the application's view when content has changed

Subscribe to events emitted by the communication script to ensure real-time updates of your application's view when content is changed by an editor in CMS (SaaS). These events contain an updated preview URL and a preview token that you should use to update your application's view with the latest content version from Optimizely Graph.

The optimizely:cms:contentSaved event that indicates that the changes to the content being authored were saved, indexed by Optimizely Graph, and can be fetched. Now the view application can refetch or rerender the data and see the changes.

window.addEventListener('optimizely:cms:contentSaved', (event) => {
   const message = event.detail;
   // Re-run your GraphQL queries using the new previewToken which is returned as part of `message` or
   // extract the new preview URL from the message and refresh your view or state with it.
});
interface ContentSavedEventArgs {
    contentLink: string;
    previewUrl: string;
    previewToken: string;
    properties: PropertySaved[];
    parentId?: string;
    sectionId?: string;
}

window.addEventListener('optimizely:cms:contentSaved', (event) => {
   const message = event.detail as ContentSavedEventArgs;
   // Re-run your graphql queries using the new previewToken which is returned as part of `message` or
   // extract the new preview URL from message and refresh your view or state with it.
});

Get new Preview Token from ContentSaved event message

For security reasons, the preview token has a short lifetime, so the front-end site cannot use the same token to query for contents after it has expired.

However, you can get a fresh new preview token from the event message of ContentSaved event. The event message includes a new previewUrl field that includes the new preview token.

 onSuccess: (message: ContentSavedMessage) => {
   //...
   const newPreviewUrl = message.previewUrl
   const urlParams = new URLSearchParams(newPreviewUrl);
   const newPreviewToken = urlParams.get('preview_token');
   //...
 }

This new preview token can be used to query from Optimizely Graph to refresh the front-end page.

📘

Note

The preview token has a short lifetime and must be replaced after expiration