### Contentful Setup Script Output Example Source: https://github.com/contentful/live-preview/blob/main/examples/next-pages-router/README.md This is an example of the expected output when running the content model setup script. It confirms the entities that will be imported into your Contentful space. ```bash > cms-contentful@1.0.0 setup /Users/john.doe/documents/next-app-router > node ./contentful/setup.js $CONTENTFUL_SPACE_ID $CONTENTFUL_MANAGEMENT_TOKEN ┌──────────────────────────────────────────────────┐ │ The following entities are going to be imported: │ ├─────────────────────────────────┬────────────────┤ │ Content Types │ 1 │ ├─────────────────────────────────┼────────────────┤ │ Editor Interfaces │ 2 │ ├─────────────────────────────────┼────────────────┤ │ Locales │ 1 │ ├─────────────────────────────────┼────────────────┤ │ Webhooks │ 0 │ ├─────────────────────────────────┼────────────────┤ │ Entries │ 0 │ ├─────────────────────────────────┼────────────────┤ │ Assets │ 0 │ └─────────────────────────────────┴────────────────┘ ✔ Validating content-file ✔ Initialize client (1s) ✔ Checking if destination space already has any content and retrieving it (2s) ✔ Apply transformations to source data (1s) ✔ Push content to destination space ✔ Connecting to space (1s) ... ... ... ``` -------------------------------- ### Install Dependencies and Build Project Source: https://github.com/contentful/live-preview/blob/main/CONTRIBUTING.md Run these commands from the project root to install all necessary dependencies and build all packages. ```bash yarn yarn build ``` -------------------------------- ### Install Live Preview SDK Source: https://github.com/contentful/live-preview/blob/main/packages/content-source-maps/README.md Install the Live Preview SDK using npm. This is a prerequisite for using Content Source Maps and other Live Preview features. ```bash npm install @contentful/live-preview ``` -------------------------------- ### Install Timeline Preview Package Source: https://github.com/contentful/live-preview/blob/main/packages/timeline-preview/README.md Install the @contentful/timeline-preview package using npm. ```bash npm install @contentful/timeline-preview ``` -------------------------------- ### Install @contentful/live-preview with Yarn Source: https://github.com/contentful/live-preview/blob/main/README.md Use this command to add the live preview SDK to your project using Yarn. ```bash yarn add @contentful/live-preview ``` -------------------------------- ### Install Contentful Live Preview SDK Source: https://github.com/contentful/live-preview/blob/main/README.md Add the @contentful/live-preview package to your project using yarn or npm. ```bash yarn add @contentful/live-preview ``` ```bash npm install @contentful/live-preview ``` -------------------------------- ### Install Dependencies with npm Source: https://github.com/contentful/live-preview/blob/main/examples/vanilla-js/README.md Use this command to install the necessary project dependencies. ```bash npm install ``` -------------------------------- ### Run Gatsby Project Locally Source: https://github.com/contentful/live-preview/blob/main/examples/gatsby/README.md Use this command to start the Gatsby development server and enable live preview functionality. ```bash npm run develop ``` -------------------------------- ### Setup Content Model Script Source: https://github.com/contentful/live-preview/blob/main/examples/next-pages-router/README.md Execute this command to automatically create the required content model in your Contentful space. Ensure you replace YOUR_SPACE_ID and XXX with your actual Contentful Space ID and Management Token. ```bash npx cross-env CONTENTFUL_SPACE_ID=YOUR_SPACE_ID CONTENTFUL_MANAGEMENT_TOKEN=XXX npm run setup ``` -------------------------------- ### Revalidate Endpoint Setup Source: https://github.com/contentful/live-preview/blob/main/examples/next-app-router-rsc/README.md This file demonstrates how to set up a revalidation endpoint for Contentful Live Preview to invalidate pages when content changes. ```typescript import { revalidateTag } from 'next/cache'; export async function POST(request: Request) { const tag = request.headers.get('X-Contentful-Webhook-Tag'); if (!tag) { return new Response('Missing X-Contentful-Webhook-Tag header', { status: 400, }); } revalidateTag(tag); return new Response('Revalidated', { status: 200, }); } ``` -------------------------------- ### Server-side Loader with Data Manipulation Issue Source: https://github.com/contentful/live-preview/blob/main/examples/remix/README.md This example demonstrates a common issue where data manipulation in a server-side loader prevents live preview updates. Client-side changes are not reflected because the loader executes only once on the server. ```javascript export async function loader({ context }: LoaderArgs) { const contentfulItems = data ? data?.entryCollection?.items[0]?.pageContentCollection?.items : undefined; return { contentful: contentfulItems, }; } ``` -------------------------------- ### Enable Draft Mode and Content Preview API in Next.js Source: https://github.com/contentful/live-preview/blob/main/README.md Configure draft mode in Next.js and set up the Content Preview API in Contentful for the best live preview experience. A workaround for security settings affecting iframes is available in the examples directory. ```typescript // examples/nextjs-graphql/pages/api/draft.ts#L25 ``` -------------------------------- ### Tagging Fields with Inspector Mode in React Source: https://github.com/contentful/live-preview/blob/main/README.md Example of using the helper function to add data-attributes for inspector mode tagging in React. ```jsx import { ContentfulLivePreview } from '@contentful/live-preview'; ...

{title}

``` -------------------------------- ### Initialize SDK with Custom Configuration Source: https://github.com/contentful/live-preview/blob/main/README.md Initialize the SDK with advanced configuration options including locale, inspector mode, live updates, debug mode, and target origin. ```jsx import { ContentfulLivePreview } from '@contentful/live-preview'; ... ContentfulLivePreview.init({ locale: 'set-your-locale-here', // This is required and allows you to set the locale once and have it reused throughout the preview enableInspectorMode: false, // This allows you to toggle the inspector mode which is on by default enableLiveUpdates: false, // This allows you to toggle the live updates which is on by default debugMode: false, // This allows you to toggle the debug mode which is off by default targetOrigin: 'https://app.contentful.com', // This allows you to configure the allowed host of the live preview (default: ['https://app.contentful.com', 'https://app.eu.contentful.com']) }); ``` -------------------------------- ### Initialize SDK with Experimental Feature Source: https://github.com/contentful/live-preview/blob/main/README.md Initializes the SDK and enables the experimental feature to hide outlines for covered elements. ```js ContentfulLivePreview.init({ // ... experimental: { hideCoveredElementOutlines: true }, }); ``` -------------------------------- ### Set Up Content Preview URL Source: https://github.com/contentful/live-preview/blob/main/examples/next-pages-router/README.md Configure the Content preview URL in your Contentful space for development. Replace `{CONTENTFUL_PREVIEW_SECRET}` with your actual secret token. ```plaintext http://localhost:3000/api/enable-draft?secret={CONTENTFUL_PREVIEW_SECRET}&slug={entry.fields.slug} ``` -------------------------------- ### Initialize ContentfulLivePreviewProvider in Next.js Source: https://github.com/contentful/live-preview/blob/main/README.md Initialize the SDK with ContentfulLivePreviewProvider in your _app.tsx or _app.js. It accepts the same arguments as the init function. ```tsx import { ContentfulLivePreviewProvider } from '@contentful/live-preview/react'; const CustomApp = ({ Component, pageProps }) => ( ) ``` ```tsx import { ContentfulLivePreviewProvider } from '@contentful/live-preview/react'; const CustomApp = ({ Component, pageProps }) => ( ); ``` -------------------------------- ### Initialize the SDK with Locale Source: https://github.com/contentful/live-preview/blob/main/README.md Basic initialization of the Contentful Live Preview SDK, setting the required locale. ```jsx import { ContentfulLivePreview } from '@contentful/live-preview'; ... ContentfulLivePreview.init({ locale: 'en-US'}); ``` -------------------------------- ### Initialize Contentful Live Preview SDK Source: https://github.com/contentful/live-preview/blob/main/README.md Initialize the live preview SDK with the desired locale. This should be done after fetching data from Contentful. ```html Live Preview Example ``` -------------------------------- ### Run Unit Tests Source: https://github.com/contentful/live-preview/blob/main/CONTRIBUTING.md Execute this command to run the unit tests for the project. ```bash yarn test ``` -------------------------------- ### Initialize Live Preview SDK (React) Source: https://github.com/contentful/live-preview/blob/main/packages/content-source-maps/README.md Initialize the Contentful Live Preview Provider in your React application. This is required for Live Preview Inspector Mode. ```jsx import { ContentfulLivePreviewProvider } from '@contentful/live-preview/react'; const CustomApp = ({ Component, pageProps }) => ( ) ``` -------------------------------- ### Live Preview Script Initialization Source: https://github.com/contentful/live-preview/blob/main/examples/next-app-router-rsc/README.md This script initializes the Contentful Live Preview SDK. It's designed to be a minimal, standalone script that listens for save events and calls the revalidation endpoint. ```typescript import { createClient } from '@contentful/live-preview'; const client = createClient({ // You can find these values in your Contentful project settings // https://app.contentful.com/spaces/{spaceId}/settings/general space: process.env.CONTENTFUL_SPACE_ID as string, environment: 'master', accessToken: process.env.CONTENTFUL_ACCESS_TOKEN as string, previewAccessToken: process.env.CONTENTFUL_PREVIEW_ACCESS_TOKEN as string, // This is the secret that you set up in your Contentful space // https://app.contentful.com/spaces/{spaceId}/settings/webhooks previewSecret: process.env.CONTENTFUL_PREVIEW_SECRET as string, // This is the URL of your revalidation endpoint // https://nextjs.org/docs/app/building-your-application/routing/route-handlers revalidateSecret: '/api/revalidate', // This is the tag that will be used to revalidate the page // https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations revalidateTag: 'contentful', }); export default client; ``` -------------------------------- ### Run ESLint for All Packages Source: https://github.com/contentful/live-preview/blob/main/CONTRIBUTING.md Execute this command from the monorepo root to run ESLint across all packages for code linting. ```bash # at the monorepo root yarn lint ``` -------------------------------- ### Run All Tests for CI Source: https://github.com/contentful/live-preview/blob/main/CONTRIBUTING.md Execute this command to run all tests, typically used in a Continuous Integration environment. ```bash yarn test:ci ``` -------------------------------- ### Enable Content Source Maps via Direct CPA URL Source: https://github.com/contentful/live-preview/blob/main/packages/content-source-maps/README.md When not using the Contentful Client SDK, append `&includeContentSourceMaps=true` to your Content Preview API (CPA) request URL. Ensure the complete `sys` object is retrieved, as excluding it with a `select` operator will cause errors. ```js fetch("https://preview.contentful.com/spaces/:spaceId/environments/:envId/entries&includeContentSourceMaps=true", { method: "GET", headers: { Authorization: "Bearer YOUR_ACCESS_TOKEN", Content-Type: "application/json", }, } ) ``` -------------------------------- ### Run TypeScript Checker for All Packages Source: https://github.com/contentful/live-preview/blob/main/CONTRIBUTING.md Execute this command from the monorepo root to run the TypeScript type checker across all packages. ```bash # at the monorepo root yarn tsc ``` -------------------------------- ### Component-level Data Manipulation for Live Preview Source: https://github.com/contentful/live-preview/blob/main/examples/remix/README.md This corrected approach moves data manipulation to the component level, ensuring that client-side changes are reflected in the live preview. The loader now fetches a simpler data structure. ```javascript export async function loader({ context }: LoaderArgs) { const contentfulItems = data ? data?.entryCollection?.items[0] : undefined; return { contentful: contentfulItems, }; } export default function Homepage() { ... return ( {contentfulData?.pageContentCollection?.items.map((item: IDataItem) => ( ))} ) } ``` -------------------------------- ### Live Updates with GraphQL Query Source: https://github.com/contentful/live-preview/blob/main/README.md Provide your GraphQL query to `useContentfulLiveUpdates` for optimized performance and support for GraphQL features like aliases. Ensure the response is in its original form. ```tsx import gql from 'graphql-tag'; const query = gql` query posts { postCollection(where: { slug: "${slug}" }, preview: true, limit: 1) { items { __typename sys { id } slug title content: description } } } `; // ... const updated = useContentfulLiveUpdates(originalData, { query }); // ... ``` -------------------------------- ### useContentfulLiveUpdates Source: https://github.com/contentful/live-preview/blob/main/README.md Hook for enabling live updates with GraphQL. Provide your GraphQL query to this hook for optimized performance and support for GraphQL features like aliases. ```APIDOC ## useContentfulLiveUpdates ### Description Enables live updates for content when using GraphQL. This hook optimizes update performance and supports GraphQL features such as aliases. ### Usage ```javascript import gql from 'graphql-tag'; const query = gql` query posts { postCollection(where: { slug: "${slug}" }, preview: true, limit: 1) { items { __typename sys { id } slug title content: description } } } `; // ... const updated = useContentfulLiveUpdates(originalData, { query }); // ... ``` ``` -------------------------------- ### Enable Content Source Maps in GraphQL Query Source: https://github.com/contentful/live-preview/blob/main/packages/content-source-maps/README.md Add the `@contentSourceMaps` directive to your GraphQL queries to enable Content Source Maps. This will include metadata in the `extensions` field of the response. ```graphql query @contentSourceMaps { postCollection(preview: true) { items { title } } } ``` -------------------------------- ### ContentfulLivePreview.openEntryInEditor Source: https://github.com/contentful/live-preview/blob/main/README.md Utility function to open a specific entry or asset directly in the Contentful live preview editor. ```APIDOC ## ContentfulLivePreview.openEntryInEditor ### Description Opens an entry or asset in the Contentful live preview editor. This function provides manual control over the editor opening process, allowing integration within custom UI components or event handlers. ### Method Signature `ContentfulLivePreview.openEntryInEditor({fieldId: string, entryId: string, assetId: string, locale: string})` ### Parameters #### Path Parameters - **fieldId** (string): The ID of the field to target within the entry or asset. - **entryId** (string): The ID of the entry containing the field. - **assetId** (string): The ID of the asset containing the field. - **locale** (string): The locale of the content. ### Usage ```javascript ContentfulLivePreview.openEntryInEditor({ entryId: 'entryId', fieldId: 'fieldId', locale: 'en-US', }); ``` ``` -------------------------------- ### Combine Live Updates and Content Source Maps Source: https://github.com/contentful/live-preview/blob/main/packages/content-source-maps/README.md When using both live updates and inspector mode, first encode the full GraphQL response using `encodeGraphQLResponse`, then pass the encoded data to the `useContentfulLiveUpdates` hook. ```jsx import { encodeGraphQLResponse } from '@contentful/live-preview'; import { useContentfulLiveUpdates } from '@contentful/live-preview/react'; export default function Page({ initialGraphQLResponse }) { // 1. Encode the full response first (including extensions): const encoded = encodeGraphQLResponse(initialGraphQLResponse); // 2. Then pass that encoded data to the live updates hook: const updated = useContentfulLiveUpdates(encoded); return

{updated.data?.myEntry?.title}

; } ``` -------------------------------- ### Add Field Tagging and Live Updates to Next.js Component Source: https://github.com/contentful/live-preview/blob/main/README.md Use useContentfulInspectorMode and useContentfulLiveUpdates hooks to enable field tagging and live updates within your components. Ensure the data provided to useContentfulLiveUpdate includes sys.id and __typename for GraphQL. ```tsx export default function BlogPost: ({ blogPost }) { const inspectorProps = useContentfulInspectorMode() // Live updates for this component const data = useContentfulLiveUpdates( blogPost ); return (
{data.heading} {/* Text is tagged and can be clicked to open the editor */} {data.text}
); } ``` ```tsx export default function BlogPost: ({ blogPost }) { const inspectorProps = useContentfulInspectorMode({ entryId: data.sys.id }) return (
{data.heading} {data.text}
) } ``` -------------------------------- ### Enable Content Source Maps with Contentful Client SDK Source: https://github.com/contentful/live-preview/blob/main/packages/content-source-maps/README.md Configure the Contentful client to include Content Source Maps by setting `includeContentSourceMaps: true` within the `alphaFeatures` option. Ensure you are using Contentful.js version v10.11.0 or above. ```jsx export const clientPreview = createClient({ space: process.env.CONTENTFUL_SPACE_ID!, accessToken: process.env.CONTENTFUL_PREVIEW_ACCESS_TOKEN!, host: "preview.contentful.com", alphaFeatures: { includeContentSourceMaps: true } }); ``` -------------------------------- ### Open Entry in Contentful Editor Source: https://github.com/contentful/live-preview/blob/main/README.md Use `ContentfulLivePreview.openEntryInEditor` to manually open an entry in the Contentful live preview editor. This is useful for custom UI components or events. ```javascript ContentfulLivePreview.openEntryInEditor({ entryId: 'entryId', fieldId: 'fieldId', locale: 'en-US', }); ``` -------------------------------- ### Set Up Contentful Webhook for Revalidation Source: https://github.com/contentful/live-preview/blob/main/examples/next-app-router/README.md Configure a webhook in Contentful to trigger revalidation on content changes. Specify the POST URL, secret header, and customize the payload to include the updated blog post's slug. ```url https:///api/revalidate ``` -------------------------------- ### Subscribe to Live Updates Source: https://github.com/contentful/live-preview/blob/main/README.md Subscribe for changes to entries or assets to receive live updates when fields are edited in Contentful. The callback function will be invoked to update the preview. ```html Live Preview Example ``` -------------------------------- ### Override Locale in getProps Source: https://github.com/contentful/live-preview/blob/main/README.md Demonstrates how to override the default locale when fetching properties for an entry using getProps. ```jsx ContentfulLivePreview.getProps({ entryId: id, fieldId: 'title', locale: 'fr' }); ``` -------------------------------- ### Encode Content Preview API Response Source: https://github.com/contentful/live-preview/blob/main/packages/content-source-maps/README.md Use the `encodeCPAResponse` function from the Live Preview SDK to process the Content Preview API response. This function adds the necessary hidden metadata to activate inspector mode. ```jsx import { encodeCPAResponse } from '@contentful/live-preview'; const dataWithAutoTagging = encodeCPAResponse(data); ``` -------------------------------- ### Draft Mode API Route Source: https://github.com/contentful/live-preview/blob/main/examples/next-app-router-rsc/README.md This API route handles draft mode requests, enabling the preview of unpublished content. It uses the Contentful preview secret and slug to set up the draft mode. ```typescript import { draftMode } from 'next/headers'; import { permanentRedirect } from 'next/navigation'; export async function GET(request: Request) { const { searchParams } = new URL(request.url); const secret = searchParams.get('secret'); const slug = searchParams.get('slug'); // Validate the secret if (secret !== process.env.CONTENTFUL_PREVIEW_SECRET) { return new Response('Invalid secret', { status: 401, }); } // Enable draft mode draftMode().enable(); // Redirect to the page with the slug permanentRedirect(`/${slug}`); } ``` -------------------------------- ### Parse Timeline Preview Token Source: https://github.com/contentful/live-preview/blob/main/packages/timeline-preview/README.md Use the parseTimelinePreviewToken utility to extract information from the timeline token in your preview URL. Ensure your preview URL is configured to include the {timeline} token. ```javascript import { parseTimelinePreviewToken } from "@contentful/timeline-preview"; // Assuming your preview URL contains a timeline token const previewUrl = "https://your-preview-url.com?timeline=your-timeline-token"; const timelineToken = parseTimelinePreviewToken(previewUrl); console.log(timelineToken); ``` -------------------------------- ### Disable Manual Tagging with ContentfulLivePreviewProvider Source: https://github.com/contentful/live-preview/blob/main/packages/content-source-maps/README.md To stop using manual tags when working with Content Source Maps, configure the `ContentfulLivePreviewProvider` with the `ignoreManuallyTaggedElements` experimental option set to `true`. ```jsx ``` -------------------------------- ### Enable Experimental Feature: Hide Covered Element Outlines Source: https://github.com/contentful/live-preview/blob/main/README.md Enables an experimental feature to prevent outlines from rendering on overlapped elements in inspector mode. ```jsx ``` -------------------------------- ### Use useContentfulLiveUpdates Hook Source: https://github.com/contentful/live-preview/blob/main/README.md Utilizes the useContentfulLiveUpdates hook to receive real-time content updates on the client-side. Ensure Contentful data is in its original structure. ```tsx import { useContentfulLiveUpdates } from '@contentful/live-preview/react'; // ... const updated = useContentfulLiveUpdates(originalData); // ... ``` -------------------------------- ### Encode GraphQL Response Source: https://github.com/contentful/live-preview/blob/main/packages/content-source-maps/README.md Use the `encodeGraphQLResponse` function from the Live Preview SDK to process the GraphQL response data. This function encodes the response to activate inspector mode automatically when rendering. ```jsx import { encodeGraphQLResponse } from '@contentful/live-preview'; const dataWithAutoTagging = encodeGraphQLResponse(data); ``` -------------------------------- ### Integrate Inspector Mode with Gatsby Source: https://github.com/contentful/live-preview/blob/main/README.md Use the useContentfulInspectorMode hook to enable inspector mode in Gatsby components. Note that live updates may not function as expected due to data transformations by gatsby-source-contentful. ```jsx export default function Hero({ data }) { const inspectorProps = useContentfulInspectorMode(); return (
{/* Text is tagged and can be clicked to open the editor */} {data.text}
); } ``` -------------------------------- ### Tag HTML Elements for Inspector Mode Source: https://github.com/contentful/live-preview/blob/main/README.md Tag HTML elements with data attributes to enable inspector mode for Contentful entries and fields. The `getProps()` helper function can be used to generate these attributes. ```html Live Preview Example

Title

``` -------------------------------- ### Remove Hidden Metadata with splitEncoding Source: https://github.com/contentful/live-preview/blob/main/packages/content-source-maps/README.md When hidden metadata causes issues with CSS values, dates, or URLs, use the `splitEncoding` function from the Live Preview SDK to remove these hidden strings and clean the content. ```javascript You can remove the hidden strings using the `splitEncoding` function from the Live Preview SDK. ``` -------------------------------- ### Clean Encoded Content with splitEncoding Source: https://github.com/contentful/live-preview/blob/main/packages/content-source-maps/README.md Use `splitEncoding` to remove hidden metadata from fields that may display unintended styles due to CSS letter-spacing. This function helps retrieve the clean content. ```jsx import { splitEncoding } from '@contentful/live-preview'; const { cleaned, encoded } = splitEncoding(text); ``` -------------------------------- ### Override Locale in useContentfulLiveUpdates Hook Source: https://github.com/contentful/live-preview/blob/main/README.md Shows how to override the locale when using the useContentfulLiveUpdates hook for real-time content updates. ```tsx import { useContentfulLiveUpdates } from '@contentful/live-preview/react'; // ... const updated = useContentfulLiveUpdates(originalData, { locale }); // ... ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.