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. Read the dedicated Previews migration guide if you set up your site for previews using the source plugin.


1. Enable Previews in your repository

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

🗄 Using Amazon S3 or Gatsby Cloud?

If you are hosting your site with Gatsby Cloud or Amazon S3, set the Link Resolver option with a trailing slash (for example, /preview/, not /preview) to ensure they send the URL parameters to the preview page.

Other hosts, like Netlify do not require particular configurations.

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
npm
Copy
npm install gatsby-plugin-prismic-previews
Yarn
Copy
yarn add gatsby-plugin-prismic-previews

3. Add environment variables

As explained in the source plugin installation guide, ensure you're using Environment variables, 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. 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 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.

Read the plugin's technical reference to learn about all the available plugin options.

Example plugin configuration

In this example plugin configuration, we are declaring the basic setup options of the plugin:

Update your plugin configuration and add only the options that apply to your project configuration. For example, if your repository's API is public, you don't need an accessToken.

If you have multiple repositories, duplicate the plugin configuration for each repository and add the typePrefix plugin option to differentiate the schemas.

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,
        accessToken: process.env.PRISMIC_ACCESS_TOKEN,
      },
    },
   // All other plugins and configurations
  ],
}

Additionally, the following list of options that you must provide to both plugins. For example, if you configure a lang option in gatsby-source-prismic, then you must also provide it to gatsby-plugin-prismic-previews:

  • graphQuery
  • lang
  • pageSize
  • imageImgixParams
  • imagePlaceholderImgixParams
  • typePrefix

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

3. Configure your project code

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

1. Set the preview provider

Wrap your application with the <PrismicPreviewProvider> component. Create the following two files at the root of your project and set them up in the same way, following Gatsby's recommendation:

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

Then, update the values to match your repository information and project details:

Copy
// gatsby-browser.js AND gatsby-ssr.js

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

import { linkResolver } from './path-to-your-linkResolver'
import PageTemplate from './path-to-your-page-templates'

export const wrapRootElement = ({ element }) => (
  <PrismicPreviewProvider
    repositoryConfigs={[
      {
        repositoryName: process.env.GATSBY_PRISMIC_REPO_NAME,
        linkResolver,
        componentResolver: componentResolverFromMap({
          page: PageTemplate,
        }),
      },
    ]}
  >
    {element}
  </PrismicPreviewProvider>
)

2. 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'

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

export default withPrismicPreviewResolver(PreviewPage)

☁️ Are you using Gatsby Cloud?

If you are using Gatsby Cloud for previews, you can stop here and continue with the dedicated guide to configuring Gatsby Cloud.

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

3. Update content pages and templates

Add a _previewable field to the query and declare the withPrismicPreview() function. 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'

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)

4. 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 standard 404 page and render the previewed document instead automatically as needed.

This is what an unpublished preview 404 page could look like:

Copy
// Example 404.js file

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

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

export default withPrismicUnpublishedPreview(NotFoundPage)

5. Merge preview data when using useStaticQuery

If you have components that 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 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? Spot an error in the documentation? Get in touch with us on our Community Forum or using the feedback form above.