Effortless automatic content linking in Next.js using Content Source Maps

Published on September 30, 2024

Effortless Automatic Content Linking using Content Source Maps

In this tutorial, we will explore how to implement Contentful's latest feature, Content Source Maps in a Next.js project.

This new feature enhances the live preview experience by automatically providing a link between displayed content and the corresponding fields in Contentful.

By the end of this tutorial, you’ll have a working example of inspector mode with automatic field tagging in a Next.js app router project.

Prerequisites are that you have a basic understanding of npm, React, Next.js, and Contentful SDKs. Familiarity with Contentful and a project setup are also necessary, plus a code editor of your choice.

Automatic content linking in Next.js using Content Source Maps

What are Content Source Maps?

Previously, enabling inspector mode required developers to manually add HTML data attributes to every Contentful element rendered on the page, a tedious and time-consuming process.

With Content Source Maps, this setup is now fully automated. Our APIs now return source maps for fields that link directly to the corresponding field in Contentful. The Live Preview SDK will convert these source maps into hidden metadata on your page, which inspector mode reads to create a seamless connection between your website and its related fields in Contentful.

Please note that Content Source Maps are available exclusively on our Premium plans.

Now, let’s see how to implement this feature in a Next.js project.

Step #1: Set up your Next.js project

If you don’t already have a Next.js project, you can create one by running:

npx create-next-app@latest my-project

cd my-project

npm install

Step #2: Install the Contentful SDKs

To fetch draft data from Contentful using the CPA, we will use the Contentful Client SDK. Additionally, to enable inspector mode and live updates, the Contentful Live Preview SDK is required.

Install both using the following command:

npm install contentful @contentful/live-preview

Step #3: Initialize the Live Preview SDK in your project

Inside your Next.js app, create app/page.tsx. Here, we'll fetch an entry from Contentful and use the CPA to get draft content when draft mode is active. We'll also set up the Live Preview SDK:

The ContentfulLivePreviewProvider wraps your app, enabling features like Inspector Mode and automatic updates during preview. The provider is meant to be enabled only while draft mode is active.

Note that we are initializing the ContentfulLivePreviewProvider in a Next.js client component, this is necessary because client components in Next.js have access to browser APIs, which Live Preview relies on to make a connection between Contentful and your website.

Step #4: Enable Content Source Maps in Contentful API calls

To fetch data from Contentful, you'll need your space ID and CPA access token. Go to Settings > API keys in Contentful and generate a new API key. Your space ID and CPA access token will be listed there. Add these values to your .env.local file.

To enable Contentful’s Content Source Maps with the Contentful's JavaScript SDK, you configure the preview client to include the includeContentSourceMaps option. This client also references the space ID and CPA access token stored in your .env.local file.

When you review the entry returned from the CPA, you'll notice it now includes Content Source Maps in the sys object. These mappings link each field of the entry to its original content source. The Live Preview SDK uses these mappings and converts them into hidden Unicode characters, which remain invisible to humans but are detected by inspector mode in live preview. This method is known as steganography.

The result is clickable links on your page. When content editors click these links, the respective entry opens on the left side next to the preview.

For instructions on how to fetch Content Source Maps using the GraphQL API, please refer to our documentation.

Step #5: Display content in your Next.js application

Next, we will render the content to our page. To enable real-time updates during live preview, use the useContentfulLiveUpdates hook. Keep in mind that this hook must be used in a Next.js client component. We pass the data that we fetch in a server component down through React props to a client component, where the hook is applied to add interactivity and live updates to the page.

Automatic Inspector Mode tagging currently supports specific field types in Contentful, such as Symbol, Long Text, Rich Text, and assets. For a complete list of supported fields, please refer to our documentation.

To enable automatic Inspector Mode tagging for assets, ensure that the alt attribute is populated with either the asset title or description field from Contentful.

Step #6: Setting up preview in Contentful

In your Contentful space, navigate to Settings > Content Preview and create a new content preview platform. You can name it anything you like, such as "Website Preview."

For the Preview URL, select the appropriate content type and set the value to the draft mode URL of your Next.js project (e.g., http://localhost:3000/api/draft?slug={entry.fields.slug}).

Now, when you open an entry of this content type, the live preview button will be enabled in the sidebar. Upon clicking it, you'll see your page with inspector mode automatically activated for all the visual fields on the website. Make sure to also make some updates to the fields, and see them get updated live as you type!

Implementing Content Source Maps

Troubleshooting

While automatic inspector mode tagging typically won't affect your website's functionality, there may be specific scenarios that could lead to issues. For instance, letter-spacing in CSS might cause unexpected styles, or strict string comparisons could fail due to hidden metadata being appended to string values.

In such cases, you can use the functions provided by the Live Preview SDK to extract the content and remove the hidden steganography data.

import { splitEncoding } from '@contentful/live-preview';

const { cleaned, encoded } = splitEncoding(text);

Wrapping up

Implementing Content Source Maps significantly simplifies the process of linking content to its corresponding fields in Contentful.

With the automated source mapping, developers no longer need to manually add data attributes for inspector mode, saving time and development effort. In summary, with just a few lines of code, you can activate live preview inspector mode across your entire site.

You can find Content Source Maps examples hosted on GitHub here.

Subscribe for updates

Build better digital experiences with Contentful updates direct to your inbox.

Related articles

In this post we explore definitions of composability in relation to various fields of digital work, with a useful analogy to show composability in action.
Guides

Understanding composability: Definitions and explanations

August 29, 2023

pancakes
Guides

Contentful makes smart speakers even smarter

January 17, 2023

Pagination is about splitting content into pages for easier display and navigation in a website or app. Learn four ways to implement pagination in React.
Guides

React pagination tutorial: 4 ways with full code examples

September 22, 2024

Contentful Logo 2.5 Dark

Ready to start building?

Put everything you learned into action. Create and publish your content with Contentful — no credit card required.

Get started