# Live Preview

With this feature, you'll be able to manage and preview your content right from the Contentstack panel without publishing it. You can read more about this in Contentstack's documentation (opens new window).

However, this feature requires some additional custom work with your template and HTML markup.


# Setup

Pass the configuration to your middleware.config.js.

// middleware.config.js
livePreview: {
  managementToken: 'MANAGEMENT_TOKEN',
  enable: true,
  host: 'CONTENT_HOST',
}

# Example - Live Preview on Page component (SSR)

  1. Implement body-parser library to parse request query parameters (optional)

Install body parser

$ yarn add body-parser

Create server middleware

// serverMiddleware/body-parser.js
const bodyParser = require('body-parser');
const app = require('express')();

app.use(bodyParser.json());
module.exports = app;

Add body parser middleware and contentstackScriptSrc to nuxt.config

// nuxt.config.js
serverMiddleware: [
  '~/serverMiddleware/body-parser'
],
  // ...
buildModules: [
  '@vsf-enterprise/commercetools/nuxt', {
    // ...
    contentstackScriptSrc: 'https://unpkg.com/@contentstack/live-preview-utils@^1.2/dist/index.js'
  }
]
  1. Update Nuxt page component to consume Contentstack Live Preview Query (some component parts has been omitted for readability)

<script>
import { useContent } from '@vsf-enterprise/contentstack';
import { useMeta, useContext, defineComponent } from '@nuxtjs/composition-api';
import { onSSR, useVSFContext } from '@vue-storefront/core';

export default defineComponent({
  head: {},
  setup() {
    const { search, content } = useContent();
    const { req } = useContext();
    const { $ct: { config: { contentstackScriptSrc } } } = useVSFContext();

    useMeta({
      script: [
        {
          src: contentstackScriptSrc,
          callback: () => {
            window.ContentstackLivePreview.init();
          }
        }
      ]
    });

    onSSR(async () => {
      let livePreviewQuery;
      if (process.server && req.query.live_preview) {
        livePreviewQuery = req.query;
      }
      await search({
        url: 'example',
        livePreviewQuery: livePreviewQuery
      });
    });

    return {
      content
    };
  },
})
</script>

WARNING

req.query property is available only, if you implemented body-parser library from Step 1, otherwise you need to parse query string from req.url property.