gatsby-plugin-prismic-previews Technical Reference - v4

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

withPrismicPreview

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

This higher-order component (HOC) is used to connect 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.

In order 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. An example of this is provided 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.

repositoryConfigs[n].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'.

repositoryConfigs[n].linkResolver

function (required)

The Link Resolver used for the Prismic repository. This should be the same Link Resolver provided to gatsby-source-prismic in your app's gatsby-config.js.

repositoryConfigs[n].htmlSerializer

function

The optional HTML Serializer used for the configured Prismic repository. This should be 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

An optional boolean that determines if previewed content should be automatically merged into the page's data prop. This option defaults to true. If this option is set to 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 written as a standard Gatsby page without any special preview-specific code. In most cases, you can simply 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. This tells the HOC to replace the document's data with preview content if available. This special field should be included any time a document is queried, including querying for 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'

import { linkResolver } from '../linkResolver'

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

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

export default withPrismicPreview(PageTemplate, [
  {
    repositoryName: 'my-repository-name',
    linkResolver,
  },
])

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) is used to redirect an editor 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. This page should be configured 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.

repositoryConfigs[n].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'.

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.

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 written as a standard Gatsby page without any special preview-specific code. In most cases, you can simply add withPrismicPreviewResolver() around the default export to a simple placeholder page to enable preview support.

Copy
// src/pages/preview.js

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

import { linkResolver } from '../linkResolver'

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

export default withPrismicPreviewResolver(PreviewPage, [
  {
    repositoryName: 'my-repository-name',
    linkResolver,
  },
])

withPrismicUnpublishedPreview

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

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

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.

repositoryConfigs[n].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'.

repositoryConfigs[n].linkResolver

function (required)

The Link Resolver used for the Prismic repository. This should be the same Link Resolver provided to gatsby-source-prismic in your app's gatsby-config.js.

repositoryConfigs[n].htmlSerializer

function

The optional HTML Serializer used for the configured Prismic repository. This should be 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 an easy 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 simple 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 set of document types and their matching components to render. The first node's type in the list is used to select 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,
  componentResolverFromMap,
} from 'gatsby-plugin-prismic-previews'

import { linkResolver } from '../linkResolver'

import PageTemplate from './PageTemplate'

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

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

export default withPrismicUnpublishedPreview(PageTemplate, [
  {
    repositoryName: 'my-repository-name',
    linkResolver,
    componentResolver: componentResolverFromMap({
      page: PageTemplate,
    }),
  },
])

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.

useMergePrismicPreviewData() can also be used manually if needed. A common use case is to update data from Gatsby's useStaticQuery() hook. Because useStaticQuery() runs within a component, withPrismicPreview() is not able to automatically update the data with previewed contented. 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.

Just like page queries, that any nodes that should be updated with previewed content must include the _previewable field.

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? Get in touch with us on our Community Forum.