cs-icon.svg

Set up Live Preview for Static-Site Generator (SSG)

Static Site Generators (SSGs) let you create static HTML websites from raw data and templates, and are often used for websites that don't need much dynamic content.

When it comes to working with Live Preview, these websites use Live Preview in the CSR (Client-side Rendering) mode. Let’s look at how to set up Live Preview for your SSG websites in detail.

Prerequisites

Steps for Execution

  1. Set up the User Website

    1. Generate a preview token for configuration

      You can create a preview token within the Contentstack app by navigating to Settings > Tokens > Delivery Tokens (press “alt + O” for Windows or “option key + O” for Mac). It is recommended to use a preview token for Live Preview instead of a previously utilized, read-only management token.

      Each preview token is associated with a delivery token and shares access to the specific environment. Therefore, if a delivery token doesn't exist, you must create a new one, where you can enable the Create Preview Token toggle. For an existing delivery token, you will find an option to generate a preview token. Click + Create Preview Token and copy the resulting token.

      Create-a-Preview-Token_GIF.gif
    2. Update Contentstack's Delivery SDK:

      Add Live Preview configs to the Contentstack.Stack() method of Contentstack's Delivery SDK, e.g., here is a sample code for the JavaScript Delivery SDK:

      import Contentstack from 'contentstack'
      const Stack = Contentstack.Stack({ 
        ...
        // update your configs here
        live_preview: {
          preview_token: preview_token,
          enable: true,
          host: 'rest-preview.contentstack.com' //optional
        },
        ...
      })
      
      Note: For the North America endpoint, set the host parameter to rest-preview.contentstack.com. If your website is hosted on other data centers, pass the following:
      • AWS EU: eu-rest-preview.contentstack.com
      • Azure NA: azure-na-rest-preview.contentstack.com
      • Azure EU: azure-eu-rest-preview.contentstack.com

      Migrate to new preview service (optional)

      Upgrade the Contentstack SDK to its latest version. Find the Contentstack.Stack() initialization method and replace the management_token parameter with the preview_token as shown below:

      Contentstack.Stack({
      ...,
      live_preview: {
      enable: true,
      host: "rest-preview.contentstack.com", // optional
      preview_token: "csxxxxxxxxxxxx"
      }
      })
      

      Warning: Upgrading to the latest SDK version won't disrupt your existing configuration, but you might notice suboptimal performance in live preview within references and other operations. To enhance efficiency, update the host and replace management_token with preview_token.

    3. Install and Initialize the Live Preview Utils SDK

      The Live Preview Utils SDK actively monitors content updates and triggers requests to Contentstack's Delivery SDK to retrieve draft or preview content, as well as manage real-time content changes. As a result, this SDK must be executed on the client-side.To install it, you can either use npm or import it using the script tag in your HTML page code.

      Via Script: To import the Live Preview Utils SDK using the script tag of the HTML file, run the following code:

      <script src="https://unpkg.com/@contentstack/live-preview-utils@1.4.0/dist/index.js"></script>
      

      Then, you can initialize the SDK using the init() method and set the enable key to true.

      <script>
          ContentstackLivePreview.init({
              enable: true
              });
      </script>
      

      Via npm:Alternatively, you can install the Live Preview Utils SDK package via npm using the following command:

      npm install @contenstack/live-preview-utils
      
      You can then initialize the SDK using the init() method. This method helps set up event listeners that keep a tab of any changes made to the previewed entry's content.Pass the Stack object against the stackSdk parameter.
      import ContentstackLivePreview from "@contentstack/live-preview-utils";
      ContentstackLivePreview.init({
       
          stackSdk: Stack,
      });
      export const onLiveEdit = ContentstackLivePreview.onLiveEdit;
      

      Note: You need to define your SDK initialization code within a separate JavaScript file to prevent configuration resetting errors in your Live Preview setup caused by rerendering.

    4. Configure Live Preview across each webpage

      Whenever you update an entry, the onLiveEdit() method will be executed. Hence, you can define any coding logic that helps fetch data inside this method.Each page has a function responsible for retrieving data and setting it to the state. Here, we have used React.js for demonstration. We have created an updateData() function responsible for fetching the data and setting it to React state.Now, inside the useEffect() function, we pass the updateData() function to the onLiveEdit() method. This onLiveEdit() method runs the updateData() function every time you update entry content.

      // Footer.js
      import React from "react";
      import { onLiveEdit } from "./utils.js";
      const Footer = () => {
          const [data, setData] = React.useState({});
          const updateData = () => {
              const fetchedData = SomeCallToGetData();
              setData(fetchedData);
          };
          React.useEffect(() => {
              onLiveEdit(updateData);
          }, []);
          return <div>{data.company_name}</div>;
      };
      
  2. Host the Website

    To host a website, you can simply use ngrok or any other website hosting service.

  3. Update Stack Settings

    To enable Live Preview through the stack settings in Contentstack, follow the steps given below:

    1. Go to Settings.
    2. Create a new environment if there are no existing environments in your stack.
    3. Add your hosted website URL as the base URL for the environment created. Set_Base_URL_for_Environment.png
    4. Navigate to the Live Preview section under stack's "Settings".
    5. Select the Enable Live Preview checkbox.
    6. Select the Default Preview Environment from the dropdown. This helps avoid having to add the preview settings manually across multiple entries.

      Tip: You can also update the preview URL and environment from the preview settings available on the entry page.

    7. Save the settings.
    Set_up_Live_Preview_-_Update_stack_settings_-_Save.png

    Tip: Once you have set up Live Preview for your stack, you can refer to the Live Editing for Entries section below to learn how to set up real-time content editing and preview for stack entries.

    You will now be able to see the Live Preview icon within all the entries of your stack and the feature will preview data from the hosted website.

  4. Live Edit Tags for Entries (optional)

    Live edit tags provide a seamless way to jump directly to the specific content you want to modify within the live preview. Clicking the "Edit" button next to a content block in the preview pane automatically takes you to the corresponding field in the entry editor. If the field refers to another entry, you'll be directed to that entry's editor page for further editing.

    Additional Resource: For detailed information on how to set up Live Edit tags, please refer to our documentation on Set Up Live Edit Tags for Entries with REST

Was this article helpful?
^