Previews and Deployment

Welcome to the sixth article in the getting started with 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.

When working in the writing room editor, authors can preview their new content on the website without publishing it. Keep reading to learn how to add it to your Gatsby project.

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/utils/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 properly in your project. In the following steps, we will add all the necessary configurations to get this up and running.

The details about how these high-order components and 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:

2. 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 pass it the repository name and the link resolver, 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
Copy
// index.js file

import * as React from 'react'
import { graphql } from 'gatsby'
import { withPrismicPreview } from 'gatsby-plugin-prismic-previews'
import { RichText } from 'prismic-reactjs'
import { linkResolver } from '../utils/LinkResolver'
import { Layout } from '../components/Layout'
import { Seo } from '../components/Seo'
import { HomepageBanner } from '../components/HomepageBanner'
import { SliceZone } from '../components/SliceZone'

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

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

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

export default withPrismicPreview(HomeTemplate, [
  {
    repositoryName: process.env.GATSBY_PRISMIC_REPO_NAME,
    linkResolver,
  },
])
Copy
// {PrismicPage.url}.js file

import * as React from 'react'
import { graphql } from 'gatsby'
import { withPrismicPreview } from 'gatsby-plugin-prismic-previews'
import { linkResolver } from '../utils/LinkResolver'
import { Layout } from '../components/Layout'
import { Seo } from '../components/Seo'
import { SliceZone } from '../components/SliceZone'

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

  return (
    <Layout>
      <Seo title={page.data.document_display_name.text} />
      <SliceZone sliceZone={page.data.body} />
    </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, [
  {
    repositoryName: process.env.GATSBY_PRISMIC_REPO_NAME,
    linkResolver,
  },
])

3. 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'
import { linkResolver } from '../utils/LinkResolver'

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

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

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 normal 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, componentResolverFromMap } from 'gatsby-plugin-prismic-previews'
import { linkResolver } from '../utils/LinkResolver'
import HomeTemplate from './index'
import PageTemplate from './{PrismicPage.url}'

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

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

5. 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
// gatsby-ssr.js and gatsby-browser.js files

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

import 'gatsby-plugin-prismic-previews/dist/styles.css'

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

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

And that is it. Now, if you go to your repository, make a change to one of your documents, 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? Get in touch with us on our Community Forum.