Live Preview Implementation for SSR without Contentstack SDK
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 your SSR websites.
Note: This guide is focused on configuring the live preview feature for REST APIs. If you are working with GraphQL APIs, please refer to the Set up Live Preview with GraphQL for SSR document.
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 these 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 toggle.
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.
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. Therefore, this SDK needs to be executed on the client side.
To install it, you can use the script tag in your HTML page or any other view engine code.
Using script tag: To import and initialize the Live Preview Utils SDK using the script tag of the HTML file, run 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>
Set up a middleware:
When you access your website in the Live Preview panel, it obtains the hash through query parameters in SSR mode. Utilize the ContentstackLivePreview.setConfigFromParams() method to extract and store this hash, making it accessible via ContentstackLivePreview.hash.
You'll need to use ContentstackLivePreview.hash when retrieving data from the server.
import ContentstackLivePreview from "@contentstack/live-preview-utils"; app.use((req, response, next) => { ContentstackLivePreview.setConfigFromParams(req.query) // You could use objects provided by the frameworks as well. next(); });
Update the REST URL and headers
To ensure the proper functioning of the website within the Live Preview panel, it's necessary to change the REST API’s hostname. When the website operates within a Live Preview panel, the Live Preview SDK receives a hash via the URL search params in SSR mode. Consequently, you can examine this hash to switch to the appropriate hostname.
function getHeaders() { const headers = new Headers(); headers.append("Content-Type", "application/json"); headers.append("access_token", REACT_APP_CONTENTSTACK_DELIVERY_TOKEN); headers.append("api_key", REACT_APP_CONTENTSTACK_API_KEY); return headers; } export const fetchData = async (ctUID, entryUID) => { const contentstackURL = new URL( `https://${CONTENTSTACK_CDN_URL}/v3/content_types/${ctUID}/entries/${entryUID}?environment=${REACT_APP_CONTENTSTACK_ENVIRONMENT}` ); const headers = getHeaders(); const res = await fetch(contentstackURL.toString(), { method: "GET", headers: headers, }); return res.json(); };
In this setup, a simple configuration directs the contentstackURL to the Contentstack CDN endpoint, while the getHeaders() function generates the necessary headers for requests. The fetchData() function manages data retrieval, ensuring the correct information is fetched from the server.
import ContentstackLivePreview from "@contentstack/live-preview-utils"; const CONTENTSTACK_CDN_URL = "cdn.contentstack.io"; const LIVE_PREVIEW_HOST_NAME = "rest-preview.contentstack.com"; function getHeaders() { const headers = new Headers(); headers.append("Content-Type", "application/json"); headers.append("access_token", REACT_APP_CONTENTSTACK_DELIVERY_TOKEN); headers.append("api_key", REACT_APP_CONTENTSTACK_API_KEY); return headers; } export const fetchData = async (ctUID, entryUID) => { const contentstackURL = new URL( `https://${CONTENTSTACK_CDN_URL}/v3/content_types/${ctUID}/entries/${entryUID}?environment=${REACT_APP_CONTENTSTACK_ENVIRONMENT}` ); const hash = ContentstackLivePreview.hash; const headers = getHeaders(); if (hash) { headers.append("live_preview", hash); // Optionally, to enable variant support add the include_applied_variants header. headers.append("include_applied_variants", "true"); headers.append("preview_token", REACT_APP_CONTENTSTACK_PREVIEW_TOKEN); contentstackURL.hostname = LIVE_PREVIEW_HOST_NAME; } else { contentstackURL.hostname = CONTENTSTACK_CDN_URL; } const res = await fetch(contentstackURL.toString(), { method: "GET", headers: headers, }); return res.json(); };
In this example, you can use ContentstackLivePreview.hash to selectively modify the hostname and headers. When it comes to enabling Live Preview, it's essential to transmit both the hash and preview_token. Optionally, to enable variant support in edit tags add the include_applied_variants header. Once you have configured this data, you can continue using REST API just as you normally would.
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
- GCP NA: : gcp-na-rest-preview.contentstack.com
To fetch content in the live preview panel, it is recommended to utilize the preview token instead of the read-only management token. For additional details, please refer to the documentation on Preview tokens.
Host the Website
To host a website, you can simply use ngrok or any other website hosting service.
Note: Make sure your website is HTTPS enabled.
Update Stack Settings
To enable Live Preview through the stack settings in Contentstack, follow the steps given below:
- Go to Settings.
- 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