Live Preview with Custom Middleware

Coding5m 49sReleased: April 2, 2025

This guide explains how to implement Contentstack's Live Preview functionality when your architecture includes a middleware layer between the CMS and your website or front end.

Understanding Live Preview with Middleware

Contentstack's Live Preview allows content editors to see changes in real-time. When you use middleware, you need to make specific adjustments to ensure the live preview works correctly.

Requirements

  • Contentstack account
  • Middleware layer integrated between Contentstack and your website
  • Basic understanding of server-side rendering (SSR)

Steps for Implementation

Step 1: Configure Your Middleware

Your middleware should be able to handle requests differently depending on whether it's a Live Preview or a standard request.

Step 2: Initialize Live Preview in Your Front-end

Use the Contentstack Live Preview utilities with SSR enabled:

import ContentstackLivePreview from '@contentstack/live-preview-utils';
ContentstackLivePreview.init({
ssr: true,
enable: true,
mode: "builder",
stackDetails: {
apiKey: YOUR_API_KEY,
environment: YOUR_ENVIRONMENT,
branch: YOUR_BRANCH
}
});

Step 3: Capture Live Preview URL Parameters

When in Live Preview mode, Contentstack sends the following parameters via URL:

  • live_preview
  • entry_uid
  • content_type_uid

Use your front-end framework (e.g., Next.js 15) to capture these parameters from the request.

Example with Next.js

export default async function Page({ searchParams }) {
const { live_preview, entry_uid, content_type_uid } = searchParams;
const content = await fetchMiddlewareContent({ live_preview, entry_uid, content_type_uid });
return <YourComponent content={content} />;
}

Step 4: Adjust Middleware API Calls

If a Live Preview hash is present (live_preview), make requests to Contentstack's draft API endpoint instead of the CDN endpoint.

  • Draft API URL: Replace the CDN URL with the draft endpoint.
  • Headers: Include your preview token and the live preview hash.

Middleware Example

const headers = {
api_key: 'your-stack-api-key',
access_token: 'your-preview-token',
live_preview: livePreviewHash
};

const url = livePreviewHash ? 'https://<your-region>-api.contentstack.io/v3/content_types/<content_type_uid>/entries/<entry_uid>' : 'https://cdn.contentstack.io/v3/content_types/<content_type_uid>/entries/<entry_uid>';

fetch(url, { headers }).then(response => response.json());

Key Considerations

  • Always distinguish between Live Preview and regular requests in your middleware.
  • Ensure proper header management to securely interact with draft and CDN endpoints.

Benefits

  • Real-time content updates directly within a visual editing environment.
  • Enhanced content management flexibility when using middleware layers.

Additional Resources