Step-by-Step Tutorial to Setup Contentful Preview Mode with Next.js (2024)

Contentful is a leading agile content management platform that is flexible and supports digital experience innovation, at scale. However, with its Headless CMS approach, a key question that is uppermost in the minds of the content management team is whether Contentful supports What-You-See-Is-What-You-Get (WYSIWYG) editing. Not exactly, but it comes very close. You can easily build a Content Preview feature and tie that into the Contentful management interface such that content creators can click one button to preview exactly how their content will appear. This article is a tutorial on how to set up content previews for a Contentful-based website built in Next.js.

Developer: Why Implement a Preview Mode?

Content Editor: Isn’t it obvious? I WANT TO SEE HOW MY CONTENT CHANGES WILL LOOK WITHOUT HAVING TO WAIT ON A WEBSITE BUILD AND WITHOUT PUBLISHING MY CONTENT.

Preview mode allows the content manager to view an entirely new blog post or a modified website page with one click with no risk of breaking existing features, and no need to wait on builds. Yes, in this day and age, with the speed and agility of deployment platforms like Vercel, Netlify, Amplify, or Heroku, your builds are fast but not fast enough for the needs of your content team that wants instant previews. Additionally, as websites begin to scale in size, build times become longer and the need for a preview mode grows exponentially.

What you need to know before you start this Contentful, Nextjs Preview Setup Tutorial?

There is no need to be an expert in either Next.js or Contentful to follow along; however, this article assumes that the project has at least one content type, and the data is being fetched from Contentful by Next as static or server-side props.

It is important to understand the structure of Contentful APIs. Contentful provides four main REST APIs (Content Delivery, Content Management, Content Preview, and Images) and the GraphQL Content API. Both the REST and GraphQL APIs have their advantages and disadvantages depending on the scale and purpose of the project. It is wise to be prepared to implement both to maximize their advantages at different times.

The Setup in Next.js!

The setup process begins in Next. From the beginning of the project, following best practices makes the implementation far smoother. This means that even while a preview mode may not be set up, it can be prepared for with parameter defaults in server-side or static props.

export const getStaticProps = async ({ params, preview = false }) => {// Body.}

It is important to default the parameter “preview” to false to prevent undefined values, or an accidental trigger of preview mode by the client. By default, “getStaticPaths” will not pass any value for preview to “getStaticProps.” This is what is meant by “best practice.” When working with Contentful, this can/should be present from the beginning.

With preview defaulted to false, it is completely safe to pass it into the data call. The function should be imported from a file containing the API calls to Contentful.

import { getPageBySlug } from '@lib/api';export const getStaticProps = async ({ params, preview = false }) => {const page = getPageBySlug(params.slug, preview); return {props: {page,} }}

Which API should I use?

This is the point of the project where one has to decide whether or not it makes sense to use GraphQL. In the case of this example, we are fetching the content of an entire page by its slug. For larger calls like this, it makes the most sense to use Contentful’s Content Delivery API. This was designed by Contentful to be readable and easy to implement quickly.

There are a number of ways to implement this function. The important piece is the logic to tell whether or not we want preview data. This can be done with simple ternary operators, “if” or “switch” statements that route to two different functions, or any other coding method for a two-way decision.

The Call to Contentful

For readability, we can create the calls as two separate variables. The value of “preview” will determine which is used.

const deliveryCall = { space: '<contentful_space_id>',environment: '<defaults_to_master>', accessToken: '<contentful_access_token>'}const previewCall = { space: '<contentful_space_id>',environment: '<defaults_to_master>', accessToken: '<contentful_preview_token>',host: 'preview.contentful.com',}

In the example above, the difference between the calls is that the preview uses the preview token as opposed to the regular access token. The preview call must also specify the “host”, setting the value to “preview.contentful.com”.

As shown in the official Contentful documentation, this can then be used to create the client and get the desired entries from Contentful.

const contentful = require('contentful'); export const getPageBySlug = async (slug, preview) => {const call = preview ? previewCall : deliveryCall;const client = contentful.createClient({ call });const response = await client.getEntries({content_type: 'YOUR_CONTENT_KEY','fields.slug[in]': 'THE_SLUG_YOU_ARE_LOOKING_FOR',})return response;}

Depending on whether or not the preview parameter is set to true, the call will retrieve the draft content from the site. So, how do you set the value of preview from Contentful to true, and how would getStaticProps retrieve data on the client side?

Next.js API Routes!

Next.js found a way to solve these issues with API routes. These can be built with express,js like middleware functions, which are powerful tools for developers. These have many use cases and advantages for the developer building APIs, and in the case of preview mode, they are Next’s solution to the data fetching problem. With a single method, we can set Next.js into a preview mode which makes the “getStaticProps” function act as a server-side function.

Building the preview API

To get started, this step is as simple as adding the file “preview.js” to the pages/api folder in the Next.js project. The name is, of course, completely interchangeable, and there are cases that you may want to make multiple and more specifically named files. For example, it could be called “preview-landing.js” and only be responsible for the landing content type’s middleware.

There are two important query parameters to pass to the preview API endpoint. A “secret”, which is a key that will help ensure only the desired users will reach the preview, and the “slug” used to fetch the correct preview data. These will be destructured in the middleware function and used for verification of data.

Example URL: https://<your-site>/api/preview?secret=<token>&slug=<path>

export default async function handler(req, res) {const { secret, slug = null } = req.query;}

Verifying request parameters

Next.js offers great documentation on how to use these values to verify the content that is being searched for. After destructuring the variables, we will compare the secret passed in to the secret we have created as an environment variable.

Straight from Next.js documentation:

if (secret !== process.env.CONTENTFUL_PREVIEW_SECRET || !slug) { return res.status(401).json({ message: 'Invalid token' });}

The logic is simple: if the secret passed does not match the environment variable, or the slug is not present, the client will receive an “Invalid token” message. This response can and should be customized to provide more information for debugging purposes.

The slug can also be verified. The best way to do this is fetching the slug from Contentful with the same function created earlier:

// Above the handler function:import { getPageBySlug } from "@lib/api";
// Fetch the headless CMS to check if the provided `slug` existsconst page = await getPageBySlug(slug, true)// If the slug doesn't exist prevent preview mode from being enabledif (!page.fields.sections.length) { return res.status(401).json({ message: 'Invalid slug' });}

By checking for the section length in the response from the function, we can be sure that the response is both in Contentful, and has some data added to it. This is also an important step for the security of the site. The user will be redirected to the path from the fetched slug instead of using req.query.slug, as this could lead to open redirect vulnerabilities.

res.setPreviewData({});const url = page.fields.slug;res.setHeader('Content-Type', 'text/html')res.write( `<!DOCTYPE html><html><head​​><meta http-equiv="Refresh" content="0; url=${url}" /> <script>window.location.href = '${url}'</script> </head> </html>`)res.end()

As mentioned before, the use of “res.setPreviewData({})” will add two cookies to the client and set Next into preview mode. The “getStaticProps” function on the page that is fetched will conveniently now retrieve the preview data on the client side.

Exiting the preview API

Building the middleware function to exit preview mode is very similar to entering. Simply add the file “exit-preview.js” to the pages/api folder in the Next.js project. This function will only need to pull the URL from the preview in order to exit to the same page that is being previewed.

The best way to allow the user to exit the preview is by designing a custom banner that informs the user they are in preview mode. This can display responsively when “preview” passed from getStaticProps is set to true. A button should be added to the banner which links to:

import { useRouter } from "next/router";const route = useRouter();// Inside Link:href={`/api/exit-preview?url=${route.asPath}`} 

Inside the exit-preview file, the URL route parameter can be destructured and used to reroute the user to the correct page.

export default function handler(req, res) { const { url } = req.query; // Clear the preview mode cookies res.clearPreviewData() // Redirect the user back to the page they're previewing. res.setHeader('Content-Type', 'text/html) res.write( `<!DOCTYPE html><html><head><meta http-equiv="Refresh" content=​​0; url=${url}"/> <script>window.location.href = "${url}"</script> </head> </html>` ) res.end()}

Enable Preview Mode Inside Contentful!

When running preview mode in the LocalHost, it is enough to add the preview access token and secret token to the .env.local file. If the purpose is to use a live build of the project, whether using Vercel, Amplify, or Heroku, the next step is to add these environment variables there. This will allow the builds to verify the secret and access preview mode.

From here Contentful makes it very easy to add the new preview path into the platform itself. Within the project on Contentful, an administrator can navigate to Settings > Content preview and click “Add Content Preview”.

After giving the content preview a unique name and description, the section below will be populated with all the content types in the space.

Step-by-Step Tutorial to Setup Contentful Preview Mode with Next.js (1)

Each of these can be checked and given a unique preview URL. Contentful has extensive documentation on creating these URLs, but to make it work with the preview API set up in this article, the URL should be structured as follows:

https://<your-site>/api/preview?secret=<token>&slug={entry.fields.slug}

Contentful will automatically replace what is inside the curly brackets with the desired data, and that’s it! As long as the destination URL in Contentful is built with the API route, and the environment variables have been added exactly as they are expected, Contentful can now enter preview mode with one click.

Step-by-Step Tutorial to Setup Contentful Preview Mode with Next.js (2)

Simply navigate to the content entry of a content type that has been enabled for preview mode, and the open preview option will now link to the URL provided.

Summary: Contentful, Nextjs Preview Setup Tutorial

While this article was designed to be a step by step “how to,” do not hesitate to also rely on the Next.js preview mode documentation and the Contentful preview mode documentation.

If you have questions on any step of this process and/or need help with Contentful best practices, please engage with us via comments on this blog post, or reach out to us at http://www.xtivia.com/contact/ or [emailprotected].

Additional Reading

You can also continue to explore Contentful by checking out 17 Contentful Best Practices, Tricks and Tips From The Trenches, or A Step-byStep Tutorial For Building a Custom Contentful App and Building a Custom Contentful App that Invokes an External API from a development perspective.

Step-by-Step Tutorial to Setup Contentful Preview Mode with Next.js (2024)

FAQs

How to setup Contentful Preview? ›

To get started, navigate to the Settings tab and click on the Content preview item. Add a new environment by filling out the required fields. The form for adding a preview will automatically list all the content types found in your space.

What is Nextjs preview mode? ›

Next. js Preview Mode allows you to create sharable URLs where you can see preview content rendered on actual pages. Specifically, Next. js provides a Preview Mode feature that allows you to render pages with draft content at request time instead of build time.

What is Contentful preview? ›

The content preview feature enables space administrators to add default preview environments to spaces. This feature makes it possible to add a single or multiple environments, preview draft and published entries, and select which content types can be previewed.

What is Contentful in next JS? ›

Build your first Next. js starter with Contentful, a composable content platform that extends the capabilities of the headless CMS even further. The combination of Next.

How do I do preview mode? ›

To exit preview mode, click Turn off preview on the landing page of the share preview URL.

How do I upload to preview? ›

To post:
  1. Select the photo you want to post.
  2. Press on the “Share” button (the one on the bottom right corner)
  3. Select “Post on Instagram”
  4. Follow the prompts.
  5. Paste once you are on the Instagram caption screen (Preview automatically copies it for you)
  6. Post.

What enable preview means? ›

Your public group posts can appear off Facebook if your post was shared on another app or website. You can enable or disable previews when your public group posts are shared off Facebook. Previews may include your username, your profile image and any other content from your original post.

What can you see in page preview mode? ›

Within Preview mode, you can scroll down through your page and see how it looks. You'll notice the “+” icons are gone in this view, to show you how your page is going to look to the people viewing it.

How do I run Next.js in production mode? ›

Next. js - Deployment
  1. Prepare Build. Run the following command to prepare production ready build −. npm run build > nextjs@1. ...
  2. Start the server. Run the following command to start production server −. ...
  3. Verify Output. Open localhost:3000/api/user in a browser and you will see the following output.

How do you set up Contentful? ›

The beginner's guide to Contentful
  1. Our example project.
  2. Step 1: Get an account.
  3. Step 2: Create a space.
  4. Step 3: Create the content model.
  5. Step 4: Add information to content model.
  6. Step 6: Add content.
  7. Step 7: Repeat!
  8. Everything is now in place.

What is the limit of Contentful Preview API? ›

API rate limits

By default the Contentful Preview API enforces rate limits of 14 requests per second. Higher rate limits may apply depending on your current plan.

What is a preview link? ›

When you add a URL to an email message in Outlook.com or Outlook on the web, or when you receive an email message with a URL in the body, you'll see a rich preview that includes a link title, thumbnail image, and description of the link. This is called a link preview.

How do I get data from Contentful? ›

To fetch the data stored in Contentful, you can use RESTful APIs (Content Delivery API, Content Management API and Content Preview API) or the GraphQL API. This tutorial uses the GraphQL API. The main advantage of GraphQL is that developers can request and define the data included in the response.

What does Next.js stand for? ›

Next. js is a JavaScript framework that provides an out-of-the-box solution for server side rendering (SSR) of React components. It works with popular React tools such as Create React App. With Next. js, developers can render the JavaScript code on the development server and send simple indexable HTML to the user.

Is Contentful frontend or backend? ›

It's simply a backend delivering content through a RESTful API, so you can make it look and feel however you want.

How do I turn on Preview feature? ›

To enable a Preview feature, you must be an administrator.
  1. Sign in to Power Apps.
  2. Select your environment from the top-right corner, and select Settings ( ...
  3. Select Settings > Administration.
  4. Select System Settings, and then select the Previews tab.
Oct 25, 2022

What is Preview command? ›

Command preview is a productivity tool that provides real-time feedback for the active editing command. A preview of the possible outcome of the command is displayed, allowing you to make changes or correct errors before completing the command.

How do you set Preview pane? ›

Enabling Preview Pane in File Explorer on Windows

Open Explorer's Folder options, go to tab "View", then under "Advanced settings" check Show preview handlers in preview pane.

How to preview image before uploading in JavaScript? ›

There are a couple ways you can do this. The most efficient way would be to use URL.createObjectURL() on the File from your <input>. Pass this URL to img.src to tell the browser to load the provided image. You can also use FileReader.readAsDataURL() to parse the file from your <input>.

How do I open a file with Preview? ›

In the Windows Explorer dialog, click Show the preview pane (H). The Preview pane appears on the right side of the window. Click on a PDF file for the Preview pane to show the contents of the document.

Why do we use preview? ›

A preview gives you a look at something that hasn't been released yet. You see lots of previews at the movies. If you've been to a movie lately, chances are you saw plenty of previews — little highlights of upcoming movies that are designed to make you want to see them.

What is the use of the preview option? ›

Print Preview in MS Word is used to View how the document will appear when printed. Print preview refers to formatting a document for the printer. Print preview is commonly called preview or previewing. Ctrl+P is the short key used to print a document in MS Word.

How do I open preview pages? ›

To open or close the preview pane, press Alt+P.

What is the difference between print preview and layout preview? ›

The Print Preview window contains controls for navigating the document's pages and for zooming (i.e., magnifying) the document. The Double Page Layout check box at the bottom of the Print Preview window is used to show two pages at once in the Print Preview window.

What is the best way to deploy Next.js app? ›

The easiest way to deploy Next.js to production is to use the Vercel platform developed by the creators of Next.js. Vercel is a serverless platform for static and hybrid applications built to integrate with your headless content, commerce, or database.

How do I set up a next JavaScript app? ›

Automatic Setup

Run npm run dev or yarn dev or pnpm dev to start the development server on http://localhost:3000. Visit http://localhost:3000 to view your application. Edit pages/index.js and see the updated result in your browser.

How to deploy Next.js app in production? ›

Deploying Next. js as a Static Site
  1. npm run export. The command generates the files: ...
  2. git add -A. Create a commit:
  3. git commit -m "adding export command" Push the code to GitHub:
  4. git push. Once the code is pushed, go into your DigitalOcean App Platform Dashboard and create a new app by pressing the Create App button.
Sep 29, 2021

How do I create a content model in Contentful? ›

From your space home: Click the Content Model tab, then Add content type. Enter the name of the content type you're creating and a short description. Select the type of field(s) you want to include in your content type.

How do I connect my website to Contentful? ›

How to build your first website with Contentful
  1. Create your free Contentful account.
  2. Clone a sample repo and install a few dependencies.
  3. Create a new “data bucket”, or space, to store content.
  4. Generate a Content Management API access token.
  5. Generate a Content Delivery API access token.
  6. Import data into the space.

What programming language is Contentful? ›

With Contentful you can build highly dynamic JavaScript-based applications in the framework of your choice (Backbone. js, Ember. js, Angular. js, jQuery) or even with pure JS and AJAX requests.

What is the maximum image size for Contentful? ›

To upload images to Contentful, refer here. Note: As per the Technical Limits specifications, size of an image uploaded must not exceed 20MB. Images exceeding the size limit are treated as assets and the transformation features offered by the API are not applicable.

What is the max file size for Contentful? ›

The following file size limits apply: Free tier users: 50 MB maximum file size. Basic and Premium/Enterprise tier users: 1000 MB maximum file size.

What are content types in Contentful? ›

Each content type is made up of fields that denote the type of data that will be included in the entry. For example, the title of a web page or news article would have its own text field, the body would have another, and there would also be fields to include any media files.

How do I create a link preview? ›

Link previews are usually generated by fetching the URL and parsing meta tags of the page for title and description and image tags for thumbnails. This can be done by making basic GET requests to the URL. This method works when we just want to parse the meta tags and the page is rendered on the server.

Is previewing a link the same as opening it? ›

An app or social media platform downloads the link content and generates the preview. The receiving app then shows the preview. It doesn't need to open the link, so potentially malicious content hosted on the linked website doesn't reach the user right away.

How do I make a live preview for my website? ›

Update Stack Settings for the CSR Website
  1. Go to Settings.
  2. Create a new environment if there are no existing environments in your stack.
  3. Add your hosted website URL as the base URL for the environment created.
  4. Navigate to the Live Preview section under stack's "Settings".
  5. Select the Enable Live Preview checkbox.

How do you add a Contentful PDF? ›

Click “Insert media”, then select “Link existing media”. In the dialog, search for the PDF and click OK.

How do I get a preview URL? ›

Here's how you do this:
  1. Open a webpage where you have a link in Chrome on your Android device.
  2. Instead of tapping the link, tap and hold on the link.
  3. From the context menu that appears, choose Preview page.
  4. A pane will open from the bottom covering about 75 percent of your screen.

How do I preview a website without visiting? ›

Bit.ly: Simply add a “+” to the end of the Bit.ly URL, before visiting the link. (This takes you to a preview page to see the site info and full URL before deciding to go on to the site.)

Top Articles
Latest Posts
Article information

Author: Aracelis Kilback

Last Updated:

Views: 5502

Rating: 4.3 / 5 (44 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Aracelis Kilback

Birthday: 1994-11-22

Address: Apt. 895 30151 Green Plain, Lake Mariela, RI 98141

Phone: +5992291857476

Job: Legal Officer

Hobby: LARPing, role-playing games, Slacklining, Reading, Inline skating, Brazilian jiu-jitsu, Dance

Introduction: My name is Aracelis Kilback, I am a nice, gentle, agreeable, joyous, attractive, combative, gifted person who loves writing and wants to share my knowledge and understanding with you.