Skip to main content

Configure live preview

In order to fetch draft content from Contentful during live preview mode, you must make some changes to your front-end application.

pages/index.js
import {
CANVAS_DRAFT_STATE,
CANVAS_PUBLISHED_STATE,
enhance,
EnhancerBuilder
} from '@uniformdev/canvas';

import {
createContentfulEnhancer,
ContentfulClientList,
CANVAS_CONTENTFUL_PARAMETER_TYPES,
} from "@uniformdev/canvas-contentful";

import createClient from "contentful";

// read the value of preview from the Next.js context
export const getStaticProps = async ({ preview }) => {
// keep the canvas client as is
const client = new CanvasClient({
apiKey: process.env.UNIFORM_API_KEY,
projectId: process.env.UNIFORM_PROJECT_ID,
});

const { composition } = await client.getCompositionBySlug({
slug: '/',
// add state dependent on the Next.js preview value
// this enables fetching draft compositions from Canvas API if preview=true
state: preview ? CANVAS_DRAFT_STATE : CANVAS_PUBLISHED_STATE,
});

// as an example here we are configuring the Contentful enhancer to fetch preview entries from Contentful,
// as well as preview layout from Canvas. This code creates a Contentful client, as outlined in the Contentful data tutorial.
const contentfulClient = createClient({
space: 'space-id',
accessToken: 'delivery-token',
});

// for previewing Contentful data, we need a second client that tells it how to get preview entries
const contentfulPreviewClient = createClient({
space: 'space-id',
accessToken: 'preview-token',
host: 'preview.contentful.com',
});

// add the previewClient to the ContentfulClientList
// NOTE: the ContentfulClientList allows you to use Canvas data that references multiple spaces / environments
// by providing a Contentful client for each space / environment.
const clientList = new ContentfulClientList([
{
spaceId: 'space-id',
environmentId: "environment-name",
client: contentfulClient,
previewClient: contentfulPreviewClient,
},
]);

// create the Contentful enhancer with client list
const contentfulEnhancer = createContentfulEnhancer({ client: clientList });

await enhance({
composition,
enhancers: new EnhancerBuilder().parameterType(CANVAS_CONTENTFUL_PARAMETER_TYPES, contentfulEnhancer),
// make sure to set the preview context here
context: { preview },
});

return {
props: {
composition,
},
};
};