Previews

Learn how to configure the gatsby-plugin-prismic-previews plugin, which allows you to Integrate live Prismic previews into your Gatsby project.


🕙 Before Reading

The preview plugin explained in this article replaces the preview functionality provided by gatsby-source-prismic. If your site is set up for previews using the source plugin, read the dedicated Previews migration guide.


1. Enable Previews in your repository

Start with setting up previews in your Prismic repository, read the dedicated guide to learn how to do it, then come back.

🗄 Using Amazon S3?

If you are hosting your site with Amazon S3, set the Link Resolver option with a trailing slash (for example, /preview/, not /preview). This ensures URL parameters are sent to the preview page.

Others hosts, like Netlify and Gatsby Cloud, do not require special configuration.

2. Configure the preview plugin

The gatsby-source-prismic plugin provides ready-to-use Higher-Order Components (HOC) so you can wrap your existing pages and templates. If you're interested in learning how these components work in-depth, refer to the dedicated Technical reference.

1. Prerequisites

The installation of this preview plugin requires that you have installed and configured the Source plugin in your project first. Also, you must have set up a Link Resolver function to resolve your URLs and work with Links

If you're missing any of these steps, refer to the dedicated articles to configure them and then return.

2. Install the plugin

  • npm
  • Yarn
Copy
npm install gatsby-plugin-prismic-previews
Copy
yarn add gatsby-plugin-prismic-previews

3. Add environment variables

Make sure you're using Environment variables, as explained in the source plugin installation guide, so secrets and other secured data aren't committed to source control.

4. Configure the plugin

Then, define the plugin configuration in the gatsby-config.js file, like in the next example:

Copy
// Example gatsby-config.js file
require('dotenv').config({
  path: `.env.${process.env.NODE_ENV}`,
})

module.exports = {
  plugins: [
    {
      resolve: 'gatsby-plugin-prismic-previews',
      options: {
        repositoryName: process.env.GATSBY_PRISMIC_REPO_NAME,
      },
    },
   // All other plugins and configurations
  ],
}

The following table indicates all the basic required fields of the plugin:

Plugin option

Description

resolve

string (required)

The name of the plugin. It must be 'gatsby-plugin-prismic-previews'.

options

object (required)

Property that holds all the plugin configuration.

options.repositoryName

string (required)

The name of your Prismic repository. If your prismic.io URL is 'https://my-cool-website.prismic.io/api/v2', your repo name is 'my-cool-website'.

options.accessToken

string

The access token for private APIs. Only needed if the API of your repository is private.

Additionally, the following list of options must be provided if set in both plugins. For example, if a lang option is configured in gatsby-source-prismic, then that option must also be provided to gatsby-plugin-prismic-previews:

  • graphQuery
  • lang
  • imageImgixParams
  • imagePlaceholderImgixParams
  • typePrefix

Read the gatsby-source-prismic configuration guide for details about each option.

3. Configure your project code

Once the plugin is configured in gatsby-config.js, your app will need to be connected to the plugin's system. The following steps explain which files will need to be created or updated.

1. Add a preview resolver page

The preview page helps to redirect to the correct page with preview content. For example, if an editor clicks the preview button for a blog post in the writing room, they will land on the preview resolver page within your app, which then redirects them to the blog post with previewed content.

Inside the ~/src/pages folder, create a preview.js file. This page's name should be the same as the preview Link Resolver field of your repository's Settings > Previews configuration.

Here's an example of a preview resolver page:

Copy
// Example preview.js file

import * as React from 'react'
import { withPrismicPreviewResolver } from 'gatsby-plugin-prismic-previews'

// Update the path to your Link Resolver
import { linkResolver } from '../linkResolver'

const PreviewPage = () => {
  return (
    <div>
      <h1>Loading preview…</h1>
    </div>
  )
}

export default withPrismicPreviewResolver(PreviewPage, [
  {
    repositoryName: process.env.GATSBY_PRISMIC_REPO_NAME,
    linkResolver,
  },
])

☁️ Are you using Gatsby Cloud?

If you are using Gatsby Cloud for previews, you can stop here.

Continue if you are using a different hosting service like Netlify or Vercel.

2. Update content pages and templates

To make our pages previewable, add a _previewable field to the query and declare the withPrismicPreview() function which receives your repository name and Link Resolver. This setup will automatically detect an active preview session and update the content with the preview data.

This example shows a preview-connected page template:

Copy
// Example {PrismicPage.uid}.js file

import * as React from 'react'
import { graphql } from 'gatsby'
import { withPrismicPreview } from 'gatsby-plugin-prismic-previews'

// Update the path to your Link Resolver
import { linkResolver } from '../linkResolver'

const PageTemplate = ({ data }) => {
  const document = data.prismicPage.data

  return (
    <div>
      <h1>{document.title.text}</h1>
    </div>
  )
}

export const query = graphql`
  query PageTemplate($id: String) {
    prismicPage(id: { eq: $id }) {
      _previewable
      data {
        title {
          text
        }
      }
    }
  }
`

export default withPrismicPreview(PageTemplate, [
  {
    repositoryName: process.env.GATSBY_PRISMIC_REPO_NAME,
    linkResolver,
  },
])

3. 404 Not found page

Your app's 404 page is displayed any time a user accesses a page that does not exist. This can be used to our advantage when trying to preview a page that has yet to be published. Because the page is not yet published, a page for it does not exist in your app. As a result, we can override the normal 404 page and render the previewed document instead automatically as needed.

This is what a simple unpublished preview 404 page could look like:

Copy
// Example 404.js file

import * as React from 'react'
import {
  withPrismicUnpublishedPreview,
  componentResolverFromMap,
} from 'gatsby-plugin-prismic-previews'

// Update the path to your Link Resolver
import { linkResolver } from '../linkResolver'

// Update the path to your Pages and Templates
import PageTemplate from './PageTemplate'

const NotFoundPage = () => {
  return (
    <div>
      <h1>Not found</h1>
    </div>
  )
}

export default withPrismicUnpublishedPreview(
  NotFoundPage,
  [
    {
      repositoryName: process.env.GATSBY_PRISMIC_REPO_NAME,
      linkResolver,
      componentResolver: componentResolverFromMap({
         page: PageTemplate,
      }),
    },
  ],
)

4. Wrap your pages with the provider component

Wrap your application with the PrismicPreviewProvider component. Create the following two files at the root of your project:

  1. gatsby-ssr.js
  2. gatsby-browser.js

Then, paste the following code in each of the new files (It is the same for both files, following Gatsby's recommendation).

Copy
import * as React from 'react'
import { PrismicPreviewProvider } from 'gatsby-plugin-prismic-previews'
import 'gatsby-plugin-prismic-previews/dist/styles.css'

export const wrapRootElement = ({ element }) => (
  <PrismicPreviewProvider>{element}</PrismicPreviewProvider>
)

5. Merge preview data when using useStaticQuery

If your components use Gatsby's useStaticQuery, they must be followed by the plugin's useMergePrismicPreviewData hook. This will merge previewed content into the static query's data.

When using this hook, queries must have a _previewable field and the page must still be wrapped in withPrismicPreview as described in the Update content pages and templates section.

This is what a simple useStaticQuery could look like:

Copy
import * as React from 'react'
import { useStaticQuery, graphql } from 'gatsby'
import { useMergePrismicPreviewData } from 'gatsby-plugin-prismic-previews'

const NonPageComponent = () => {
  const staticData = useStaticQuery(graphql`
    query NonPageQuery {
      prismicSettings {
        _previewable
        data {
          site_title {
            text
          }
        }
      }
    }
  `)
  const { data, isPreview } = useMergePrismicPreviewData(staticData)

  return (
    <h1>
      {data.prismicSettings.data.site_title.text}
    </h1>
  )
}

export default NonPageComponent

Note that the component is not wrapped in withPrismicPreview. The page which contains this component, however, must use the withPrismicPreview higher-order component.

Technical reference

If you'd like to get more in-depth information about how the gatsby-plugin-prismic-previews plugin options works refer to the dedicated article:


Was this article helpful?
Not really
Yes, Thanks

Can't find what you're looking for? Get in touch with us on our Community Forum.