Live Preview Implementation for NextJS SSR App Router
Server-side rendering (SSR) is the process where an application converts HTML files on a server instead of a browser into a rendered HTML client page. This guide explains in detail how to set up Live Preview for NextJS SSR App router
Prerequisites
- Contentstack account
- Access to stack settings
- Preview token
- Website that uses Contentstack Delivery SDKs
- IFrame-compatible website to avoid CORS errors
Steps for Execution
Here is an overview of the steps involved in setting up live preview with REST for your Server-side Rendering (SSR) sites:
Set up the Website
You must first set up your website. To do so, follow the steps given below:
- 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 button.
For an existing Delivery token, you will find an option to generate a Preview token. Click on the + Create Preview Token toggle and copy the resulting token number.
Update Contentstack's delivery SDK:
To indicate to Contentstack's delivery SDK that it can fetch draft or preview content, add Live Preview configs to the Contentstack.Stack() method, e.g., here is a sample code for the JavaScript Delivery SDK:
//utils.js 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:
//utils.js ... 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.
Install and initialize the Live Preview utils SDK:
The Live Preview Utils SDK listens to content changes and requests Contentstack's delivery SDK to fetch draft or preview content or process real-time content changes. Consequently, this SDK needs to 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.
Using script tag: To import and initialize the Live Preview Utils SDK using the script tag of the HTML file, add the following code:
<script type='module'> import ContentstackLivePreview from 'https://esm.sh/@contentstack/live-preview-utils@2.0.3'; ContentstackLivePreview.init({ stackDetails: { apiKey: "your-stack-api-key", }, ssr : true }); </script>
Using npm: Alternatively, you can install the Live Preview Utils SDK package via npm using the following command:
npm install @contentstack/live-preview-utils
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.
Note:- If you are using npm you are required to create a new component, initialize the live preview inside and then you can call this new component inside the main page file.
"use client"; import { useEffect } from "react" import ContentstackLivePreview from "@contentstack/live-preview-utils" export default function LivePreviewInitComponent() { useEffect(() => { ContentstackLivePreview.init({}); }, []); return (<></>); }
- 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.
- If you are using npm you are required to create a new component, initialize the live preview inside and then you can call this new component inside the main page file.
Set up a middleware:
Set up a middleware to track all new changes being made to the entry content. This middleware injects the live preview hash and content type UID into the Stack class using the livePreviewQuery() method.
// utils.js ... export const setLivePreviewQueryParams = (queryParams) => { if(queryParams?.live_preview) { Stack.livePreviewQuery(queryParams) } } ...
Note: In order to prevent communication errors between Contentstack SDK initialization and live preview SSR, the livePreviewQuery method operates on an instance basis.
Configure Live Preview across each webpage:
Whenever you update an entry, the live preview will re-render the entire page. This allows you to implement any coding logic necessary to fetch data within the component.
// page.js import { setLivePreviewQueryParams, SomeCallToGetData } from "./utils.js" import LivePreviewInitComponent from "../components/LivePreviewInitComponent" export default async function Page(props) { const queryParams = props?.searchParams; setLivePreviewQueryParams(queryParams); const entryData = await SomeCallToGetData(); return ( <> <h1> Hello, World! {" " + entryData?.title} </h1> <LivePreviewInitComponent /> </> ); }
With these steps completed, the user website is ready. Let's move ahead and host this website.
Host the Website
To host a website, you can simply use ngrok or any other website hosting service.
Update Stack Settings
To enable Live Preview through the stack settings in Contentstack, follow the steps given below:
- Go to Settings > Environments.
- Create a new environment if there are no existing environments in your stack.
- Add your hosted website URL as the base URL for the environment created.
- Navigate to the Live Preview section under stack's "Settings".
- Select the Enable Live Preview checkbox.
- Select the Default Preview Environment from the dropdown. This helps avoid having to add the preview settings manually across multiple entries.
- Save the settings.
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.
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.