cs-icon.svg

Set Up Live Preview with GraphQL for SSR

Use GraphQL APIs to preview content in real time with Live Preview. This guide explains how to configure Live Preview with GraphQL for a Server-side Rendering (SSR) website.

Prerequisites

Follow these steps to configure Live Preview with GraphQL for your SSR 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 for Configuration

      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.

      Create Preview Token UI

    2. 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 server side.

      Install the SDK using one of the following methods:

      1. Via npm:

        Install the SDK via npm:

        npm install @contentstack/live-preview-utils

        Initialize the SDK using the init() method:

        import ContentstackLivePreview from "@contentstack/live-preview-utils";
        ContentstackLivePreview.init({ enable: true, ssr: true });

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

      2. Via script:

        Install the SDK using a script tag in your HTML:

        <script type='module'>
          import ContentstackLivePreview from 'https://esm.sh/@contentstack/live-preview-utils@3.0.1';
          ContentstackLivePreview.init({
            enable: true,
            stackDetails: {
              apiKey: "your-stack-api-key",
            },
            ssr: true
          });
        </script>
    3. Utilize the Live Preview Hash

      When your website runs inside the Live Preview panel in SSR mode, the SDK appends a hash to the URL as a query string parameter. Use this hash to retrieve the corresponding preview data from the server.
      The following example uses an Express.js route handler to extract the Live Preview Hash from the query string.

      app.get('/', async (request, response) => {
        const livePreviewHash = request.query.live_preview;
        const data = await gqlRequest(gql, livePreviewHash);
        ...
      });
    4. Update the GraphQL URL and Headers

      To enable Live Preview in the preview panel, update the GraphQL API’s hostname dynamically based on the presence of a hash.

      Example: Basic configuration for GraphQL requests

      const graphqlUrl = new URL(
        `https://graphql.contentstack.com/stacks/${REACT_APP_CONTENTSTACK_API_KEY}?environment=${REACT_APP_CONTENTSTACK_ENVIRONMENT}`,
      );
      
      function getHeaders() {
        const headers = new Headers();
        headers.append("Content-Type", "application/json");
        headers.append("access_token", REACT_APP_CONTENTSTACK_DELIVERY_TOKEN);
        return headers;
      }
      
      export const gqlRequest = async (gql) => {
        const headers = getHeaders();
        const res = await fetch(graphqlUrl.toString(), {
          method: "POST",
          headers: headers,
          body: JSON.stringify({ query: gql }),
        });
        return res.json;
      };

      This example sets up the GraphQL endpoint and defines getHeaders() to supply the required headers. The gqlRequest() function fetches data from Contentstack’s GraphQL API.

      Example: Conditional configuration for Live Preview

      const graphqlUrl = new URL(
        `https://graphql.contentstack.com/stacks/${REACT_APP_CONTENTSTACK_API_KEY}?environment=${REACT_APP_CONTENTSTACK_ENVIRONMENT}`,
      );
      
      const GRAPHQL_HOST_NAME = "graphql.contentstack.com";
      const LIVE_PREVIEW_HOST_NAME = "graphql-preview.contentstack.com";
      
      function getHeaders() {
        const headers = new Headers();
        headers.append("Content-Type", "application/json");
        headers.append("access_token", REACT_APP_CONTENTSTACK_DELIVERY_TOKEN);
        return headers;
      }
      
      export const gqlRequest = async (gql, hash) => {
        const headers = getHeaders();
        if (hash) {
          headers.append("live_preview", hash);
          headers.append("preview_token", REACT_APP_CONTENTSTACK_PREVIEW_TOKEN);
          headers.append("include_applied_variants", "true");
          graphqlUrl.hostname = LIVE_PREVIEW_HOST_NAME;
        } else {
          graphqlUrl.hostname = GRAPHQL_HOST_NAME;
        }
      
        const res = await fetch(graphqlUrl.toString(), {
          method: "POST",
          headers: headers,
          body: JSON.stringify({ query: gql }),
        });
        return res.json;
      };

      In this example, you can use the hash to selectively update the hostname and headers. To enable Live Preview, it is important to send both the hash and preview_token. Optionally, if you want to support variants in edit tags, include the include_applied_variants header.

      Once configured, you can continue using GraphQL as usual.

      Note: Always use a preview token for Live Preview instead of a read-only management token. For region-specific hostnames, refer to the Base URLs for Live Preview section.

  2. Host the Website

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

    Note: Make sure your website is HTTPS enabled.

  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 Save.
      Base URL Configuration
    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.

      Live Preview 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, refer to our documentation on Set Up Live Edit Tags for Entries with REST.

Was this article helpful?
^