cs-icon.svg

Set Up Live Preview for Gatsby-Powered Sites

Gatsby is an open-source framework that combines functionality from React, GraphQL, and Webpack into a single tool for building static websites and apps. This guide explains how to configure Live Preview for your Gatsby-powered websites using Contentstack.

Prerequisites

Follow these steps to configure Live Preview with GraphQL for your Gatsby-powered website:

  1. Set Up the Website

    To enable Live Preview on your website, begin by setting up the essentials—create a preview token, install the Live Preview Utils SDK, and configure your GraphQL requests to support real-time updates.

    1. Generate a Preview Token

      Create a preview token by navigating to Settings > Tokens > Delivery Tokens (press “Alt + O” for Windows or “Option + O” for Mac).

      Note: 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. If a delivery token doesn't exist, create one and enable the Create Preview Token toggle. For an existing delivery token, use the + Create Preview Token option and copy the generated token.

      Preview Token Setup

    2. Initialize the Contentstack Gatsby Class

      Create a live-preview.js file in the src folder (or any preferred path). Import ContentstackGatsby from the gatsby-source-plugin, initialize it with your config, and export it. This enables Live Preview data fetching.

      // live-preview.js
      import { ContentstackGatsby } from "gatsby-source-contentstack/live-preview";
      export const getCSData = new ContentstackGatsby({
        api_key: GATSBY_CONTENTSTACK_API_KEY,
        environment: GATSBY_CONTENTSTACK_ENVIRONMENT,
        live_preview: {
          preview_token: GATSBY_CONTENTSTACK_PREVIEW_TOKEN,
          enable: true,
          host: "rest-preview.contentstack.com"
        }
      });
      Note: For the North America endpoint, set the host parameter to rest-preview.contentstack.com. For other data centers:
      • AWS EU: eu-rest-preview.contentstack.com
      • Azure NA: azure-na-rest-preview.contentstack.com
      • Azure EU: azure-eu-rest-preview.contentstack.com
      • GCP NA: gcp-na-rest-preview.contentstack.com
      • GCP EU: gcp-eu-rest-preview.contentstack.com
    3. Install and Initialize the Live Preview Utils SDK

      Use the Live Preview Utils SDK to listen for content updates and fetch real-time preview data on the client side.

      Install the Live Preview Utils SDK package via npm by running the following command:

      npm install @contentstack/live-preview-utils@contentstack/utils

      Initialize the SDK using the init() method to set up event listeners for content updates:

      // LivePreviewInitComponent.jsx 
      "use client";
      
      import { useEffect } from "react"
      import ContentstackLivePreview from "@contentstack/live-preview-utils"
      
      export default function LivePreviewInitComponent() {
        useEffect(() => {
          ContentstackLivePreview.init({});
        }, []);
      
        return (<>);
      }

      Note: To avoid configuration reset errors due to rerendering, place the initialization code in a separate JavaScript file.

    4. Configure Live Preview Across Each Webpage

      When you update an entry, the onEntryChange() method detects the change and runs your defined logic to fetch updated data.

      The example below demonstrates how to enable Live Preview for a Gatsby page.

      import React from "react";
      import { graphql } from "gatsby" 
      import ContentstackLivePreview from "@contentstack/live-preview-utils";
      import LivePreviewInitComponent from "../components/LivePreviewInitComponent"
      export const pageQuery = graphql`
      // your Gatsby query
      query {
        allContentstackPage {
          nodes {
            title
            url
          }
        }
      }`;
      
      const Home = (props) => {
        return (
              <LivePreviewInitComponent />
      
          <div>{props.data.allContentstackPage.nodes[0].title}</div>
        );
      };
      
      export default Home;

      In the example above, the title is displayed directly from the props received by the component. To make Live Preview work, you need to store this data in the component’s state so it can update automatically when content changes. First, import ContentstackLivePreview and getCSData (from step two). Then, create a function that fetches the updated data using getCSData.get() and update the state with this new data. Finally, connect this function to ContentstackLivePreview.onLiveEdit(), which will call the function every time someone edits the entry, allowing you to see the changes instantly. Make sure your GraphQL query includes both __typename and uid fields—these are needed by Live Preview to correctly track and refresh the content.

      import React, { useEffect, useState } from "react";
      import { graphql } from "gatsby" 
      import ContentstackLivePreview from "@contentstack/live-preview-utils";
      import LivePreviewInitComponent from "../components/LivePreviewInitComponent"
      import { getCSData } from "../live-preview";
      export const pageQuery = graphql`
      // your Gatsby query
      query {
        allContentstackPage {
          nodes {
            title
            url
          }
        }
      }`;
      
      const Home = (props) => {
        const [data, setData] = useState(props.data.allContentstackPage.nodes[0]);
      
        const fetchLivePreviewData = async () => {
          const updatedData = await getCSData.get(props.data.allContentstackPage.nodes[0]);
          setData(updatedData);
        };
      
        useEffect(() => {
          ContentstackLivePreview.onLiveEdit(fetchLivePreviewData);
        }, []);
      
        return (
              <LivePreviewInitComponent />
      
          <div>{data.title}</div>
        );
      };
      
      export default Home;
      Note:
      • In the above example, onLiveEdit() is used instead of onEntryChange() because onLiveEdit() only runs the fetch function when you are actively editing content. This helps avoid unnecessary updates. If you use onEntryChange() together with ContentstackGatsby.get(), it can cause issues and may lead to errors.
      • If your content model supports multiple locales, make sure to pass the locale explicitly in the object passed to getCSData.get(). Omitting the locale may cause the SDK to fetch data incorrectly or fail altogether, especially if no default locale fallback is configured.
  2. Host the Website

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

  3. Update Stack Settings

    To set up Live Preview for the entries of your stack, perform the following steps:

    1. Navigate to Settings and select Environments.
    2. Set the base URLs for different locales, and click Update.
      Base URL Setup
    3. Navigate to Live Preview in the left navigation panel and select the Enable Live Preview checkbox.
    4. Set the Default Preview Environment and click Save to save the settings.

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

      Preview Environment Configuration

      You can now see the Live Preview icon within all the entries of your stack and the feature previews data from the hosted website.

  4. Live Edit Tags for Entries (optional)

    Live Edit tags allow editors to directly jump from the Live Preview pane to the corresponding content fields in the entry editor. Clicking the Edit button next to a content block automatically opens the relevant field. If the field refers to another entry, you’ll be redirected to that entry’s editor page.

    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?
^