Gatsby Template Preview

I have a custom type in Prismic called article that has over 100 documents. My application is a Gatsby project where within my gatsby-node.js file I make a request for all article documents from Prismic then have a for loop that creates the relevant page for each article based on a template file. I'm trying to get Prismic previews working but so far no luck. Here's all the information:

Prismic


Project Structure
Screen Shot 2021-09-14 at 5.57.05 PM

gatsby-node.js

const path = require('path');
exports.createPages = async ({ graphql, actions }) => {
  const { createPage } = actions;

  const newsPages = await graphql(`
    {
      allPrismicArticle {
        nodes {
          uid
        }
      }
    }
  `);

  newsPages.data.allPrismicArticle.nodes.forEach((node) => {
    createPage({
      path: `/news/${node.uid}`,
      component: path.resolve('src/templates/article.jsx'),
      context: {
        uid: node.uid,
      },
    });
  });
}

gatsby-config.js

const { linkResolver } = require('./src/utils/LinkResolver');
const articleSchema = require('./src/schemas/article.json');

module.exports = {
  plugins: [
    {
      resolve: 'gatsby-plugin-prismic-previews',
      options: {
        repositoryName: process.env.GATSBY_PRISMIC_REPO_NAME,
        accessToken: process.env.PRISMIC_API_KEY
      },
    },
    {
      resolve: 'gatsby-source-prismic',
      options: {
        repositoryName: process.env.GATSBY_PRISMIC_REPO_NAME,
        accessToken: process.env.PRISMIC_API_KEY,
        linkResolver,
        schemas: {
          article: articleSchema,
        },
      },
    },
  ],
};

LinkResolver.js

exports.linkResolver = (doc) => {
  if (doc.type === 'article') {
    return `/news/${doc.uid}`;
  }

  // Backup for all other types
  return '/'
}

404.jsx

import * as React from 'react';
import { withPrismicUnpublishedPreview, componentResolverFromMap } from 'gatsby-plugin-prismic-previews'
import { linkResolver } from '../utils/LinkResolver'
import { Layout } from '../components';
import HomeTemplate from './index'
import NewsTemplate from '../templates/article'

const NotFoundPage = () => (
  <Layout>
    <h1>Empty</h1>
  </Layout>
);

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

preview.jsx

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,
  },
]);

article.jsx

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

const Article = ({ data }) => {
  return (
    <Layout>
      <p>{data.body.raw}</p>
    </Layout>
  );
};

export const articleQuery = graphql`
  query ArticleQuery($uid: String!) {
    prismicArticle(uid: {eq: $uid}) {
      _previewable
      data {
        body {
          raw
        }
      }
    }
  }
`;

export default withPrismicPreview(Article, [
  {
    repositoryName: process.env.GATSBY_PRISMIC_REPO_NAME,
    linkResolver,
  },
]);

And yet when I create a new article document in Prismic, save (without publishing it) and hit preview, I get taken to this Gatsby 404 page:

I see the Prismic preview toolbar, I see the preview page loading text before being rerouted to the right endpoint but still 404. What am I doing wrong?

Hey, @sankar.sundaresan thanks for sending over all the details of your project.
I noticed a couple of things in your setup that need to be updated.

  1. Since you are using a manual setup to declare the schemas, you need to make sure you add all the Custom Types of your repository even if they aren't in use; otherwise, the project might break. In this case, I can see you're missing to add the homepage type
  2. In gatsby.node.js you can use the url field to create the paths. The URLs of the site are automatically created using the Link Resolver that you defined in the plugin config.

Aside from that is important to note that when you're running your project in dev mode, Gatsby's default 404 page will pop up when you're trying to preview an unpublished document. This should not be the case for the version in production.

We've had a similar discussion about this a few days ago in this other thread.

Hi Pau,

  1. I actually changed this to an automatic process via the custom types api!
  2. Updated to use the .url property instead. Thank you for the rec!

Based on this thread, I checked the <PrismicPreviewProvider> in React devtools and it turns out the isBootstrapped is showing up as false. Which means the preview plugin is NOT connecting to our Prismic repository. However, the gatsby-source-prismic is connecting just fine. Any reason this connection would fail? How do I debug this?

One thing I did not provide but here is what my gatsby-ssr.js and gatsby-browser.js look like:

import * as React from 'react'
import { PrismicPreviewProvider } from 'gatsby-plugin-prismic-previews'
import 'gatsby-plugin-prismic-previews/dist/styles.css'

// eslint-disable-next-line import/prefer-default-export
export const wrapRootElement = ({ element }) => (
  <PrismicPreviewProvider>{element}</PrismicPreviewProvider>
)

Have you tried clicking on the Preview custom 404 page link inside of the default 404 page that you saw before?

This link should redirect you to the correct preview page.

Hi Pau, yes I've tried clicking on that link several times and it just keeps taking me to the gatsby not found page.

The conversation for this use case has continued in a direct message.

Below there's additional information in case someone else finds a similar problem.

If your project is hosted on Amazon S3 and you cannot make previews work in the staging server environment, you need to ensure that the preview URL uses a trailing slash at the end. For example /preview/.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.