Previews and Deployment

Welcome to the sixth article in the Prismic and Gatsby tutorial series. We'll be talking about the Preview feature and how to deploy your site.


🕙 Before reading

If you haven't already gone through the first five articles in this series, we recommend starting with the first article and working your way to this one. After that, this article will make much more sense.

Enable Previews in your repository

Read the dedicated guide to learn how to set up the previews in your Prismic repository, then come back.

Configure the preview plugin

This source plugin will help you preview draft documents from your Prismic repository.

1. Install the plugin

Install it with the following command:

Copy
npm i gatsby-plugin-prismic-previews

Then, declare the plugin in your gatsby-config.js file to include the preview plugin. For now, we're just going to set the most basic configuration, adding the name of your repository, which you have already set up in an environment variable.

Copy
// gatsby-config.js file

require('dotenv').config({
  path: `.env.${process.env.NODE_ENV}`,
})

module.exports = {
  siteMetadata: {
    title: 'Gatsby + Prismic Tutorial',
    description: 'Learn how to integrate Prismic into your Gatsby project.',
  },
  plugins: [
    {
      resolve: 'gatsby-plugin-prismic-previews',
      options: {
        repositoryName: process.env.GATSBY_PRISMIC_REPO_NAME,
      },
    },
    {
      resolve: 'gatsby-source-prismic',
      options: {
        repositoryName: process.env.GATSBY_PRISMIC_REPO_NAME,
        linkResolver: require('./src/LinkResolver').linkResolver,
        schemas: {
          homepage: require('./custom_types/homepage.json'),
          navigation: require('./custom_types/navigation.json'),
          page: require('./custom_types/page.json'),
        },
      },
    },
    'gatsby-plugin-image',
    'gatsby-plugin-react-helmet',
    {
      resolve: 'gatsby-plugin-manifest',
      options: {
        icon: 'src/images/favicon.png',
      },
    },
    {
      resolve: 'gatsby-source-filesystem',
      options: {
        name: 'images',
        path: `${__dirname}/src/images`,
      },
    },
    {
      resolve: 'gatsby-plugin-google-fonts',
      options: {
        fonts: [`Lato\:400,400,700,700i,900`, `Amiri\:400,400,700,700i`],
      },
    },
  ],
}

gatsby-plugin-prismic-previews requires a preview page, a 404 page, and a set of high-order components for the previews to work. We will add all the necessary configurations to get this up and running in the following steps.

High-order components and how pages work behind the scenes are beyond the scope of this article. Refer to the technical reference to learn all details about how this plugin works:

1. Set the preview provider

Wrap your application with the <PrismicPreviewProvider> component. Update the following two files:

  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 { Link } from 'gatsby'
import { PrismicProvider } from '@prismicio/react'
import {
  PrismicPreviewProvider,
  componentResolverFromMap,
} from 'gatsby-plugin-prismic-previews'

import './src/styles/reset.css'
import './src/styles/common.css'
import './src/styles/style.css'

import { linkResolver } from './src/LinkResolver'
import HomeTemplate from './src/pages/index'
import PageTemplate from './src/pages/{PrismicPage.url}'

export const wrapRootElement = ({ element }) => (
  <PrismicProvider
    internalLinkComponent={({ href, ...props }) => (
      <Link to={href} {...props} />
    )}
  >
    <PrismicPreviewProvider
      repositoryConfigs={[
        {
          repositoryName: process.env.GATSBY_PRISMIC_REPO_NAME,
          linkResolver,
          componentResolver: componentResolverFromMap({
            homepage: HomeTemplate,
            page: PageTemplate,
          }),
        },
      ]}
    >
      {element}
    </PrismicPreviewProvider>
  </PrismicProvider>
)

2. Add a preview resolver page

The preview page serves as a redirect for previewed documents. For example, if an editor clicks the preview button for a blog post in the writing room, they will land on this preview resolver page, redirecting them to the blog post with previewed content.

Inside 〜/src/pages, create a new preview.js file. Now, copy and paste the following code inside of your new preview file:

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

3. Update the page files

We need to be able to query documents during a preview session. To do it, we're going to use a high-order component called withPrismicPreview(), and add a _previewable field to the query.

Open your 〜/src/pages/index.js and 〜/src/pages/{PrismicPage.url}.js files and update them with the following code:

  • index.js
  • {PrismicPage.url}.js
index.js
Copy
import * as React from 'react'
import { graphql } from 'gatsby'
import { withPrismicPreview } from 'gatsby-plugin-prismic-previews'
import { SliceZone } from '@prismicio/react'

import { Layout } from '../components/Layout'
import { Seo } from '../components/Seo'
import { HomepageBanner } from '../components/HomepageBanner'

import { components } from '../slices'

const HomeTemplate = ({ data }) => {
  if (!data) return null
  const doc = data.prismicHomepage.data

  return (
    <Layout isHomepage={true}>
      <Seo title="Home" />
      <HomepageBanner
        title={doc.banner_title.text}
        description={doc.banner_description.text}
        linkUrl={doc.banner_link.url}
        linkLabel={doc.banner_link_label.text}
        backgroundUrl={doc.banner_background.url}
      />
      <SliceZone slices={doc.body} components={components} />
    </Layout>
  )
}

export const query = graphql`
  query MyQuery {
    prismicHomepage {
      _previewable
      data {
        banner_title {
          text
        }
        banner_description {
          text
        }
        banner_link {
          url
          type
          uid
        }
        banner_link_label {
          text
        }
        banner_background {
          url
        }
        body {
          ... on PrismicSliceType {
            slice_type
          }
          ...HomepageDataBodyText
          ...HomepageDataBodyQuote
          ...HomepageDataBodyFullWidthImage
          ...HomepageDataBodyImageGallery
          ...HomepageDataBodyImageHighlight
        }
      }
    }
  }
`

export default withPrismicPreview(HomeTemplate)
{PrismicPage.url}.js
Copy
import * as React from 'react'
import { graphql } from 'gatsby'
import { SliceZone } from '@prismicio/react'
import { withPrismicPreview } from 'gatsby-plugin-prismic-previews'

import { Layout } from '../components/Layout'
import { Seo } from '../components/Seo'

import { components } from '../slices'

const PageTemplate = ({ data }) => {
  if (!data) return null
  const doc = data.prismicPage.data

  return (
    <Layout>
      <Seo title={doc.document_display_name.text} />
      <SliceZone slices={doc.body} components={components} />
    </Layout>
  )
}

export const query = graphql`
  query PageQuery($id: String) {
    prismicPage(id: { eq: $id }) {
      _previewable
      data {
        document_display_name {
          text
        }
        body {
          ... on PrismicSliceType {
            slice_type
          }
          ...PageDataBodyText
          ...PageDataBodyQuote
          ...PageDataBodyFullWidthImage
          ...PageDataBodyImageGallery
          ...PageDataBodyImageHighlight
        }
      }
    }
  }
`

export default withPrismicPreview(PageTemplate)

4. Add a 404 page

Your site always needs a 404 page to display any time a user accesses a page that does not exist. We can use this to preview unpublished documents. Because the page is not yet published, a page for it does not exist in your app. As a result, we can override the 404 page and render the previewed document instead.

Open the 404 page found in 〜/src/pages/404.js and replace it with this code:

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

And that is it. Now run your project, go to your repository and modify a document. Save and click the eye button. Your preview data will appear on the correct page!

Learn more about Previews

Read the dedicated guides if you'd like to get more details about how the High Order Components of the plugin work.


Deploy your project

You have many options to deploy your Gatsby project. The steps for configuring your project for deployment are beyond the scope of this guide, but we have a dedicated article where you can learn all the details about the services that we recommend: Gatsby Cloud, Vercel, and Netlify.


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.