Was this page helpful?

Live preview - Inspector mode

Table of contents

Overview

Inspector mode is an advanced live preview feature that allows you to access an entry that contains a specific piece of website content with one click. When you click "Edit" button beside a content block in the preview iframe, you are redirected to the corresponding field within the entry. This is particularly helpful when authors share the preview URL with colleagues, as it enables them to access the correct Contentful entry with a single click.

If the field contains reference to another entry, you are redirected to the referenced entry editor.

In inspector mode, you can open entries that are referenced from other spaces. The entry opens in a new tab where you can make changes to it.

Live preview inspector mode

Inspector mode setup options

Inspector mode is set up by tagging fields. This tagging can be done according to one of the following options:

  • Recommended: Automatically with Content Source Maps - Tagging is done automatically, hidden strings are included as tagging information. Content Source Maps tag text fields, Rich Text fields, and assets.
Content Source Maps are only available on our Premium plan.
  • Manually - corresponding fields are tagged manually by adding data attributes.
We strongly recommend Content Source Maps option since tagging is automated, and the setup is quick - 30 minutes to a day for the most common use cases and content setups. Content Source Maps provide scalability - they also work when new content types are created in the future.

To better understand the difference between the two approaches, view their main characteristics in the table below:

Characteristic Content Source Maps (recommended) Manual tagging
Pricing plan Premium All users
Supported fields Text, Rich text, list of Short text, assets All field types
Setup time 30 minutes to a day Significantly more time
Maintenance Scales to new content types Needs to be adapted for new content types

Set up inspector mode

To enable inspector mode, it is required to set up live preview first.

Content Source Maps

How it works

When enabled, our APIs return source maps for certain visual fields that have links to the correct field in Contentful. The Live Preview SDK then transforms these Content Source Maps to hidden metadata into the results of your queries.

This integration employs a method known as steganography, which conceals hidden information within other data. Specifically, this approach embeds the metadata into invisible Unicode characters incorporated into the existing text strings.

The use of these "enhanced strings" on your web pages allows live preview to detect and decipher the concealed metadata in the final HTML. This enables the display of interactive links that guide users directly to the relevant field in Contentful.

Supported field types

Content Source Maps support the following field types:

  • Short text (Symbol) and Long Text: We only support fields with the Appearance setting Single line and Multiple line. We purposely don’t support URL, Dropdown, Radio, and Slug.
Radio and Dropdowns are not supported since they are primarily used for non-visual text purposes, such as CSS styling properties (e.g. a #F4F4F4 color code in a dropdown for the button color).
We are still working on a solution to also support Markdown.
  • Rich Text, including embedded references and assets.
  • Lists of Short text (Symbol).
  • Title and Description fields in an asset - Use one of them as the alt attribute of the image.
Custom widgets of supported field types can also be tagged with Content Source Maps.

We don’t support URL or ISO Date values (even in the supported field types), because adding hidden metadata would cause issues.

Content Source Maps currently don't support cross-space content.

Implementation

Content Source Maps can be set up according to one of the following options:

GraphQL
  1. Install the latest version of the Live Preview SDK.
npm install @contentful/live-preview
  1. Initialize the SDK.
   import { ContentfulLivePreviewProvider } from
   '@contentful/live-preview/react';
   const CustomApp = ({ Component, pageProps }) => (
     <ContentfulLivePreviewProvider locale="en-US">
       <Component {...pageProps}>
     </ContentfulLivePreviewProvider>
)
  1. Use the query level directive in your GraphQL queries.
Content Source Maps will only be generated for preview content.

Content Source Maps return from our GraphQL API under the “extensions”:

query @contentSourceMaps { //Add the query level directive
      postCollection(preview: true) { //And preview: true
         items { 
            title
         } 
    }
}
   // This will return:
   {
     "data": ...
     "extensions": ... //Content Source Maps will be here
}
  1. Use the encodeGraphQLResponse function from the Live Preview SDK by passing it the GraphQL Response with Content Source Maps. It will return with your content that includes the hidden metadata to enable inspector mode.
import { encodeGraphQLResponse } from "@contentful/live-preview";
const dataWithAutoTagging = encodeGraphQLResponse(data);
Content Preview API (CPA)
  • With Contentful.js SDK (recommended):
  1. Initialize the Live Preview SDK
   import { ContentfulLivePreviewProvider } from
   '@contentful/live-preview/react';
   const CustomApp = ({ Component, pageProps }) => (
     <ContentfulLivePreviewProvider locale="en-US">
       <Component {...pageProps}>
     </ContentfulLivePreviewProvider>
   )
  1. Enable Content Source Maps using the Contentful Client SDK, by setting includeContentSourceMaps in the client to true:
export const clientPreview = createClient({
space: process.env.CONTENTFUL_SPACE_ID!,
          accessToken: process.env.CONTENTFUL_PREVIEW_ACCESS_TOKEN!,
     host: "preview.contentful.com",
       includeContentSourceMaps: true
});
  • Without Contentful.js SDK:
  1. Initialize the Live Preview SDK
   import { ContentfulLivePreviewProvider } from
   '@contentful/live-preview/react';
   const CustomApp = ({ Component, pageProps }) => (
     <ContentfulLivePreviewProvider locale="en-US">
       <Component {...pageProps}>
     </ContentfulLivePreviewProvider>
   )
  1. Directly access the Contentful CPA without using the Contentful.js SDK.

Please be aware that without the Contentful Client SDK, certain protections, such as automatically requesting the sys.id, are not enforced. To ensure Content Source Maps function properly, the complete sys object needs to be retrieved. Therefore, using a select operator to exclude this from the response would cause errors.

  1. Add &includeContentSourceMaps=true to the URL:
fetch("https://preview.contentful.com/spaces/:spaceId/environments/:e nvId/entries&includeContentSourceMaps=true",
    {
      method: "GET",
      headers: {
        Authorization: "Bearer YOUR_ACCESS_TOKEN",
        Content-Type: "application/json",
      },
} )
  1. Use the encodeCPAResponse function from the Live Preview SDK by passing it the CPA Response with Content Source Maps. It will return with your content that includes the hidden metadata to enable inspector mode.
   import { encodeCPAResponse } from "@contentful/live-preview";
   const dataWithAutoTagging = encodeCPAResponse(data);

Troubleshooting and tips

We've taken a cautious approach in determining which fields to generate Content Source Maps for, ensuring that it won't disrupt your website. The remaining potential issues might include the following:

  • Under certain circumstances, such as when applying letter-spacing in CSS, fields may display styles that weren't intended. In these cases, you can utilize the functions provided by the Live Preview SDK to retrieve the content and remove any hidden metadata.
import { splitEncoding } from "@contentful/live-preview";
const { cleaned, encoded } = splitEncoding(text);

Known issues and limitations

  • Markdown support is currently in development.
  • Adding hidden metadata to content can result in problems, e.g. when being used for CSS values, for dates or URL content. You can remove the hidden strings using the splitEncoding function from the Live Preview SDK.
  • Encoding is skipped on the following formats:
    • Any date format that does not use English letters (e.g. 4/30/24);
    • ISO dates (e.g. 2024-04-30T12:34:59Z);
    • URLs.
  • We intentionally avoid tagging certain widgets, such as dropdowns, because they are primarily used for non-visual text purposes, such as CSS styling properties (e.g. #f4f4f4 color code). Adding hidden strings to these fields could potentially cause issues.
  • We do not support Gatsby with the gatsby-source-contentful plugin, since it uses the Sync API under the hood. Content Source Maps currently only get generated for the CPA and GraphQL API.

Manual tagging

Implementation

  1. Initialize the live preview SDK with the live preview provider.
import { ContentfulLivePreviewProvider } from '@contentful/live-preview/react';

const App = ({ Component, pageProps }) => (
  <ContentfulLivePreviewProvider locale="en-US">
    <Component {...pageProps}>
  </ContentfulLivePreviewProvider>
)
  1. Tag the corresponding field(s). To tag a field, specify its location within the entry by writing data attributes. The live preview SDK scans for these elements containing the correct field tags.
The manual tagging only works with fields that have the correct data attributes. Fields without these data attributes aren't seen as tagged and don't work with this feature.

The required data attributes can be added according to one of the following options:

  • Adding the data attributes directly into your code:
data-contentful-field-id
data-contentful-entry-id or data-contentful-asset-id
data-contentful-locale // Optional: override the locale you have defined in the provider
data-contentful-space // Optional: only required for tagging content from a different space
data-contentful-environment // Optional: only required for tagging content from a different space
  • Running the helper function from the live preview SDK:
import { ContentfulLivePreview } from '@contentful/live-preview';

<h1 {...ContentfulLivePreview.getProps({ entryId: id, fieldId: 'title' })}>
  {title}
</h1>;

Provider configuration

The ContentfulLivePreviewProvider accepts parameters that allow you to customize your live preview SDK experience. The following options are available:

import { ContentfulLivePreviewProvider } from '@contentful/live-preview/react';

<ContentfulLivePreviewProvider
  locale="set-your-locale-here" // Required: allows you to set the locale once and have it reused throughout the preview.
  enableInspectorMode={false} // Optional: allows you to toggle inspector mode which is on by default.
  enableLiveUpdates={false} // Optional: allows you to toggle live updates which are on by default.
  targetOrigin="https://app.contentful.com" // Optional: allows you to configure the allowed host(s) of live preview (default: ['https://app.contentful.com', 'https://app.eu.contentful.com'])
  debugMode={false} // Optional: allows you to toggle debug mode which is off by default.
>

To optimize non-preview websites, it is advisable to disable live preview functionality by setting both enableInspectorMode and enableLiveUpdates to "false". By doing so, any specific data related to live preview, such as data-attributes, is removed.

Best practices

We recommend to tag fields as follows:

  • Tag larger elements — Only tag elements of the page that are significantly larger than the mouse cursor. Tagging smaller elements such as icons inside buttons can result in a very fragmented tagging surface and we recommend to rather only tag the button itself then.

  • Nested entries — Don't tag pages further than 3 nesting levels. We believe that there is a tipping point where additional tagging of nested entries is not beneficial for the user experience since moving the mouse slightly will potentially show you various "Edit" buttons of different content pieces.

  • References — Tag the whole referenced entry and the main content inside for faster editing. In case where the text inside is short - for example, the reference is a circle with a one-word text inside — then the recommendation is to refrain from tagging this text.

  • Website sections — We definitely recommend tagging the sections of a page.

  • Styling — Many customers manage styling parameters with Contentful, e.g. the background color for a section or the margins around texts. We generally don’t recommend tagging styling as it might result in a confusing user experience, as hover areas intersect to a large extent or fully with the element the styling applies to.