gatsby-plugin-prismic-previews - v5

Overview

The gatsby-plugin-prismic-previews plugin allows you to integrate live Prismic Previews into a static Gatsby site.

  • Integrates tightly with the gatsby-source-prismic plugin.
  • Refreshes preview content automatically as changes are saved in Prismic.
  • Adds the Prismic Toolbar with an in-app edit button and preview link sharing.
  • No extra infrastructure or costs are required (specifically, Gatsby Cloud is not required).

This page describes the technical aspects of the plugin which may help you configure it for your needs.

If you are looking for a introduction to adding the plugin to your app, see the Previews guide in the Gatsby documentation.

Dependencies and requirements

This package works along with the gatsby-source-prismic plugin.

Installation

Add the gatsby-plugin-prismic-previews plugin to your Gatsby project via the command line:

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

Configure the plugin

Define the plugin configuration in the gatsby-config.js file. The following table indicates all the fields that the plugin accepts:

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 repository name is 'my-cool-website'.

options.accessToken

string

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

options.toolbar

string

Determines the type of Prismic Toolbar that the plugin will add to your site. It defaults to "new." If your repository uses a past version of the Toolbar, set it to "legacy."

options.typePrefix

string (required when sourcing from more than one repository)

A prefix used for all GraphQL types for your Prismic repository. If you are sourcing from multiple repositories, each plugin should have a unique typePrefix to avoid type conflicts.

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
  • pageSize
  • imageImgixParams
  • imagePlaceholderImgixParams
  • typePrefix

Read the gatsby-source-prismic technical reference for details about each option.

<PrismicPreviewProvider>

import { PrismicPreviewProvider } from 'gatsby-plugin-prismic-previews'

This React context provider serves two purposes:

  1. It stores global state during preview sessions, including preview data.
  2. It provides a central location for preview configuration.

The Preview button from the Prismic writing room redirects to your app. The preview system will then fetch all documents and store them in <PrismicPreviewProvider>'s state

Use the <PrismicPreviewProvider> at the root level of the React tree of your application. It receives a repositoryConfigs object with your repository configuration.

repositoryConfigs

This repositoryConfigs option is used by withPrismicPreview(), withPrismicUnpublishedPreview(), and withPrismicPreviewResolver(). Each of those functions can be provided with a repositoryConfigs object as well, but passing it to the provider only once is easier to maintain.

Note that the configuration provided to the preview functions takes priority over the one given to <PrismicPreviewProvider>.

Copy
type PrismicPreviewProviderProps {
  repositoryConfigs: {
    repositoryName: string
    linkResolver: LinkResolver
    htmlSerializer?: HTMLSerializer
    transformFieldName?: FieldNameTransformer
    componentResolver: (
      nodes: PrismicNode[],
    ) => React.ComponentType | undefined | null
    dataResolver?: (
      nodes: PrismicNode[],
      data: Record<string, unknown>,
    ) => Record<string, unknown>
  }[],
  children?: React.ReactNode
}

Parameter

Description

repositoryConfigs

object (required)

A set of configuration values for each Prismic repository used in your app.

If the preview functions and <PrismicPreviewProvider> are provided with the repositoryConfigs, the config in the preview functions will take priority.

repositoryConfigs[n].repositoryName

string (required)

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

repositoryConfigs[n].linkResolver

function (required)

The Link Resolver should be the same Link Resolver provided to gatsby-source-prismic in your app's gatsby-config.js. The return value of your Link Resolver determines the page to which editors will be directed.

repositoryConfigs[n].htmlSerializer

function

The same HTML Serializer provided to gatsby-source-prismic in your app's gatsby-config.js.

repositoryConfigs[n].transformFieldName

function

The optional field name transformer for the configured Prismic repository. This should be the same transformFieldName function provided to gatsby-source-prismic in your app's gatsby-config.js if used.

Most projects will not need to provide a value for this option.

repositoryConfigs[n].componentResolver

function (required)

A function that determines the component to render during an unpublished preview. This function will be provided a list of nodes that match the URL of the page. Using the list of nodes, the appropriate page template component should be returned

The components returned from this function must be wrapped in withPrismicPreview() in order for the component to properly resolve the preview.

In most cases, the componentResolverFromMap() helper function can be used as a way to map a Prismic document type to a component.

repositoryConfigs[n].dataResolver

function

A function that determines the data provided to the resolved component's data prop. This function will be provided a list of nodes that match the URL of the page and the wrapped component's original data prop. Using the list of nodes and the original data, an object of data should be returned that matches the shape of the resolved page template's GraphQL query.

In most cases, this can be left empty. The default dataResolver will automatically retrieve the first matching node and add it to the existing data prop using the node's typename.

children

ReactNode

The React child nodes to render with access to the provider. This should be the element argument given by Gatsby's wrapRootElement API.

Typical example

This example adds <PrismicPreviewProvider> to the root of the app using Gatsby's gatsby-browser.js and gatsby-ssr.js. Both files can be setup the same way.

A set of configurations is provided for each Prismic repository used in the app. Other parts of the preview system will read these configuration objects. For a description of the componentResolver option, see the withPrismicUnpublishedPreviews() section.

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>
)

withPrismicPreview

import { withPrismicPreview } from 'gatsby-plugin-prismic-previews'

This higher-order component (HOC) connects the preview content to your app. It automatically updates a page's data prop with content from an active preview session as needed.

If you choose to keep your access token private by not providing it as part of the plugin's options, this HOC will also display a modal allowing an editor to provide it. It will save the token locally within the browser for future preview updates.

For this HOC to add preview content to your existing page data, you must mark documents in your query as "previewable." This involves adding a _previewable field to your query. See an example of this below.

Copy
function withPrismicPreview(
  WrappedComponent: React.ComponentType,
  repositoryConfigs: {
    repositoryName: string
    linkResolver: LinkResolver
    htmlSerializer?: HTMLSerializer
    transformFieldName?: FieldNameTransformer
  }[],
  config: {
    mergePreviewData?: boolean
  },
): React.ComponentType

Parameter

Description

WrappedComponent

React.ComponentType (required)

The page component to which Prismic previews will be connected.

repositoryConfigs

object (required)

A set of configuration values for each Prismic repository used in your app.

If both <withPrismicPreview> and <PrismicPreviewProvider> are provided with the repositoryConfigs, the config in <withPrismicPreview> will take priority.

repositoryConfigs[n].repositoryName

string (required)

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

repositoryConfigs[n].linkResolver

function (required)

The same Link Resolver provided to gatsby-source-prismic in your app's gatsby-config.js.

repositoryConfigs[n].htmlSerializer

function

The same HTML Serializer provided to gatsby-source-prismic in your app's gatsby-config.js.

repositoryConfigs[n].transformFieldName

function

The optional field name transformer for the configured Prismic repository. This should be the same transformFieldName function provided to gatsby-source-prismic in your app's gatsby-config.js if used.

Most projects will not need to provide a value for this option.

config

object

A set of configuration values that determine how the preview data is prepared and provided.

config.mergePreviewData

boolean

A boolean that determines if previewed content automatically blends into the page's data prop. This option defaults to true. If this option is false, the data prop will remain unmodified during previews. In that situation, preview data can be manually merged using useMergePrismicPreviewData().

Typical example

This example uses withPrismicPreview() to automatically update a page template's data to include preview content during a preview session.

The page template component is a standard Gatsby page without any preview-specific code. In most cases, you can add withPrismicPreview() around the default export to an existing page template to enable preview support.

The page's query includes a _previewable field for the queried document that tells the HOC to replace the document's data with preview content if available. You must include this field any time a document is queried, including documents within Content Relationship fields.

Copy
// src/pages/{PrismicPage.url}.js

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

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

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

export default withPrismicPreview(PageTemplate)

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

withPrismicPreviewResolver

import { withPrismicPreviewResolver } from 'gatsby-plugin-prismic-previews'

This higher-order component (HOC) redirects from the Prismic writing room to a previewed document within your app. 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.

Every app must have a preview resolver page to preview content. This page usually will be created as /preview by creating a page at /src/pages/preview.js. You should configure this page as the preview resolver page in your Prismic repository's settings.

For more information on updating this setting within Prismic, see the dedicated guide on setting up previews.

If you choose to keep your access token private by not providing it as part of the plugin's options, this HOC will display a modal allowing an editor to provide it. It will save the token locally within the browser for future preview updates.

Copy
function withPrismicPreviewResolver(
  WrappedComponent: React.ComponentType,
  repositoryConfigs: {
    repositoryName: string
    linkResolver: LinkResolver
  }[],
  config: {
    autoRedirect?: boolean
  },
): React.ComponentType

Parameter

Description

WrappedComponent

React.ComponentType (required)

The page component which will direct editors during preview sessions.

repositoryConfigs

object (required)

A set of configuration values for each Prismic repository used in your app.

If both <withPrismicPreviewResolver> and <PrismicPreviewProvider> are provided with the repositoryConfigs, the config in <withPrismicPreviewResolver> will take priority.

repositoryConfigs[n].repositoryName

string (required)

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

repositoryConfigs[n].linkResolver

function (required)

The same Link Resolver provided to gatsby-source-prismic in your app's gatsby-config.js.

config

object

A set of configuration values that determine how editors are directed during preview sessions.

config.autoRedirect

boolean

An optional boolean that determines if editors should be automatically redirected to the previewed content's page within your app. This option defaults to true. If this option is set to false, editors will remain on the preview resolver page. In that situation, you can set up a redirect manually using the prismicPreviewPath prop.

Typical example

This example uses withPrismicPreviewResolver() to automatically direct an editor from the Prismic writing room to the previewed content's page during a preview session.

The page template component is a standard Gatsby page without any preview-specific code. In most cases, you can add withPrismicPreviewResolver() around the default export to a placeholder page to enable preview support.

Copy
// src/pages/preview.js

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)

withPrismicUnpublishedPreview

import { withPrismicUnpublishedPreview } from 'gatsby-plugin-prismic-previews'

This higher-order component (HOC) previews unpublished pages within your app. It automatically renders a page template component with content from a document that is yet to be published. This HOC relies on being added to your app's 404 page to detect an unpublished page correctly.

If you choose to keep your access token private by not providing it as part of the plugin's options, this HOC will also display a modal allowing an editor to provide it. It will save the token locally within the browser for future preview updates.

Note: When viewing your unpublished preview page during development, Gatsby will display its default development 404 page.

To preview content on the unpublished preview page, click the "Preview custom 404 page" button that appears toward the top of the page. This will hide Gatsby's default development 404 component and render your page instead.

Copy
function withPrismicUnpublishedPreview(
  WrappedComponent: React.ComponentType,
  repositoryConfigs: {
    repositoryName: string
    linkResolver: LinkResolver
    htmlSerializer?: HTMLSerializer
    transformFieldName?: FieldNameTransformer
    componentResolver: (
      nodes: PrismicNode[],
    ) => React.ComponentType | undefined | null
    dataResolver?: (
      nodes: PrismicNode[],
      data: Record<string, unknown>,
    ) => Record<string, unknown>
  }[],
): React.ComponentType

Parameter

Description

WrappedComponent

React.ComponentType (required)

The page component to which Prismic unpublished previews will be connected. This should be your app's 404 page.

repositoryConfigs

object (required)

A set of configuration values for each Prismic repository used in your app.

If both <withPrismicUnpublishedPreview> and <PrismicPreviewProvider> are provided with the repositoryConfigs, the config in <withPrismicUnpublishedPreview> will take priority.

repositoryConfigs[n].repositoryName

string (required)

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

repositoryConfigs[n].linkResolver

function (required)

The same Link Resolver provided to gatsby-source-prismic in your app's gatsby-config.js.

repositoryConfigs[n].htmlSerializer

function

The same HTML Serializer provided to gatsby-source-prismic in your app's gatsby-config.js.

repositoryConfigs[n].transformFieldName

function

The optional field name transformer for the configured Prismic repository. This should be the same transformFieldName function provided to gatsby-source-prismic in your app's gatsby-config.js if used.

Most projects will not need to provide a value for this option.

repositoryConfigs[n].componentResolver

function (required)

A function that determines the component to render during an unpublished preview. This function will be provided a list of nodes that match the URL of the page. Using the list of nodes, the appropriate page template component should be returned

The components returned from this function must be wrapped in withPrismicPreview() in order for the component to properly resolve the preview.

In most cases, the componentResolverFromMap() helper function can be used as a way to map a Prismic document type to a component.

repositoryConfigs[n].dataResolver

function

A function that determines the data provided to the resolved component's data prop. This function will be provided a list of nodes that match the URL of the page and the wrapped component's original data prop. Using the list of nodes and the original data, an object of data should be returned that matches the shape of the resolved page template's GraphQL query.

In most cases, this can be left empty. The default dataResolver will automatically retrieve the first matching node and add it to the existing data prop using the node's typename.

componentResolverFromMap()

import { componentResolverFromMap } from 'gatsby-plugin-prismic-previews'

This helper function is a method to determine which component to display during an unpublished preview. While the componentResolver option from withPrismicUnpublishedPreview() provides you with a list of nodes that match the URL of the previewed document, this list will usually only include one node. componentResolverFromMap() uses this assumption to allow you to provide just a set of document types and their matching components to render. The first node's type in the list selects the component.

Copy
function componentResolverFromMap(
  componentMap: Record<string, React.ComponentType>,
): PrismicRepositoryConfig['componentResolver']

Parameter

Description

componentMap

object (required)

A record mapping a Prismic document type to a React component.

Typical example

This example uses withPrismicUnpublishedPreview() to display an unpublished document's content automatically. The HOC is used on the app's 404 page to allow any non-existent page to be converted into a preview.

The 404 page component is written as a standard Gatsby page without any special preview-specific code. In most cases, you can add withPrismicUnpublishedPreview() around the default export to an existing page template to enable unpublished preview support.

Note that this means your 404 page can still use its own GraphQL query to display Prismic content. When an unpublished preview is active, this data will continue to be accessible within the previewed component.

Copy
// src/pages/404.js

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

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

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

export default withPrismicUnpublishedPreview(NotFoundPage)

export const query = graphql`
  query NotFoundPage {
    prismicPage(id: { eq: "404" }) {
      _previewable
      data {
        title {
          text
        }
      }
    }
  }
`

useMergePrismicPreviewData

import { useMergePrismicPreviewData } from 'gatsby-plugin-prismic-previews'

This React hook merges static data with preview data during a preview session. withPrismicPreview() uses this hook in its implementation to seamlessly update your page's data prop.

You can use useMergePrismicPreviewData() manually if needed. A common use case is to update data from Gatsby's useStaticQuery() hook. Because useStaticQuery() runs within a component, withPrismicPreview() cannot automatically update the data with previewed content. useMergePrismicPreviewData() can be used immediately after useStaticQuery() to do so.

Copy
function useMergePrismicPreviewData(
  staticData: Record<string, unknown>,
  config?: {
    skip?: boolean
  },
): {
  data: Record<string, unknown>
  isPreview: boolean
}

Parameter

Description

staticData

object (required)

Static data from Gatsby's GraphQL layer.

config

object

Configuration that determines how the hook merges preview data.

config.skip

boolean

Determines if preview data is merged during a preview session. This option defaults to false. If this option is set to true, the provided static data will always be returned.

Typical Example

This example uses useMergePrismicPreviewData() to merge data from useStaticQuery() within a component.

Like page queries, include the _previewable field to update any nodes that will have preview content.

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

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.