Gasby | Issues implementing previews

Context (Environment)

I am trying to integrate previews on a Gatsby blog set up on Netlify. We were using gatsby-source-prismic before. I followed this guide and requested support to enable GraphQL for the repository. We had custom page creation set up from the old plugin, so I removed that code and set up automatic page creation. Relevant code sections are attached.

Expected Behavior

  1. Opening a published article and pressing preview should open the site configured in preview settings with the path '/article/my-published-article. Pressing save on prismic when working on this published article should update the article.
  2. Opening a draft article and pressing preview should open the site configured in prevew settings with the path ‘/article-preview?uid=my-draft’. Pressing save on prismic when working on this draft article should update the article.

Current Behavior

  1. Opening a published article works. I press on preview in Prismic’s dashboard and the page opens up, shows a prismic preview overlay and redirects to the correct article with the correct path. Then I make a change on prismic, and press save. The article refreshes but still shows the old data. I logged the props coming in and they show old data.
  2. Opening a draft article works. I press on preview and the page opens up, showing a prismic preview overlay. I am then redirected to the correct path but the page is blank, with only a toolbar showing on the bottom left corner. Logs show no errors.

Possible Solution

  1. Could it be a caching issue? Logs show the service worker workbox serving data from the cache. I applied the hot reload fix for Gatsby but it does not seem to update the data (refreshes page as expected though).
  2. I have no idea why drafts arent working. I can see the /article-preview page being created during build.

Relevant code

package.json

    "gatsby": "^2.15.21",
    "prismic-reactjs": "^1.3.0",
    "gatsby-source-prismic-graphql": "^3.5.0",

gatsby-config.js

    {
      resolve: 'gatsby-source-prismic-graphql',
      options: {
        repositoryName: 'repo-name',
        defaultLang: 'en-gb',
        accessToken: `${process.env.PRISMIC_API_KEY}`,
        path: '/preview',
        previews: true,
        pages: [
          {
            type: 'Article', // TypeName from prismic
            match: '/article/:uid', // Pages will be generated under this pattern (optional)
            path: '/article-preview', // Placeholder page for unpublished documents
            component: require.resolve('./src/templates/article.js'),
          },
        ],
      },
    },

gatsby-browser.js

import wrapPageElementWithTransition from 'helpers/wrapPageElement';

const { registerLinkResolver } = require('gatsby-source-prismic-graphql');
const { linkResolver } = require('./src/utils/linkResolver');

registerLinkResolver(linkResolver);

export { wrapRootElement } from './src/apollo/wrap-root-element';

import 'typeface-source-serif-pro';
import 'typeface-source-sans-pro';

// Page Transitions
export const wrapPageElement = wrapPageElementWithTransition;

// auto-reload when new content available
export const onServiceWorkerUpdateReady = () => {
  const answer = window.confirm(
    `This application has been updated. ` +
      `Reload to display the latest version?`
  );

  if (answer === true) {
    window.location.reload();
  }
};

linkResolver.js

exports.linkResolver = function linkResolver(doc) {
  // Route for blog posts
  if (doc.type === 'article') {
    return '/article/' + doc.uid;
  }

  // Homepage route fallback
  return '/';
};

article.js

const Post = ({ data: { prismic }, location }) => {
  const doc = prismic.article;
  if (!doc) return null;

  const books = prismic.allChapts.edges.slice(0, 1).pop();
  if (!books) return null;

  // return layout
}

export const pageQuery = graphql`
  query ArticleByUid($uid: String!) {
    prismic {
      allChapts {
        edges {
          node {
            title
            articles {
              article {
                ... on PRISMIC_Article {
                  _meta {
                    uid
                  }
                }
              }
            }
          }
        }
      }
      article(lang: "en-gb", uid: $uid) {
        _meta {
          uid
        }
        title
        meta_title
        meta_description
        subtitle_summary
        draft
        body {
          ... on PRISMIC_ArticleBodyText {
            primary {
              text
              section_anchor
            }
          }
        }
      }
    }
  }
`;

Article.query = pageQuery;
export default Article;
2 Likes

Hi Osama!

There has been some known issues with the plugin and previews. We are currently working on fixing an improving these feature to work better with the plugin.

I can suggest clearing the cache every time you update content to always have the updated API GraphQL schema.

1 Like

Hey @osama.aamer95,

Can you give us access to a public repository so that we can see / reproduce the error and provide you the best answer possible ?

Thanks,
Renaud

I will try and copy the main bits over to a public repo. Thanks for the prompt response! :slight_smile:

1 Like

Here is a dead simple version of my own personal site: https://github.com/osamaaamer95/my-site
It is deployed here on Netlify: https://lucid-almeida-5e66fc.netlify.app/

I hope this helps. I have the exact same issues on this new site that I was experiencing on the original one. Clicking preview opens up the site fine, but I cannot see any changes or preview drafts.

1 Like

Hey!

I’ve tested and ran your project and i didn’t found any issues on my side. Which browser are you using?

I’m using Chrome, but I tested on Firefox too.

:wave: we’re also facing this issue on our project. Currently blocking any further development for us since clients need previews. In the prismic preview side bar I can see the change, e.g. new draft title, but does not have any effect on the actual article - either current published data or white screen.

Already had to change our prismic API to open to have any chance of previews working (currently no support for that)

Hi @osama.aamer95 thanks or the example project recreating the issue, unfortunately I’m getting this error Cannot query field "body" on type "PRISMIC_Homepage"
and Unknown type "PRISMIC_HomepageBodyList_of_articles". Did you mean "PRISMIC_ArticleBodyList_of_articles", "PRISMIC_ArticleBodyList_of_articlesFields", "PRISMIC_ArticleBodyList_of_articlesPrimary", "PRISMIC_HomepageConnectionEdge", or "PRISMIC_HomepageConnectionConnection"?

Could you send us the custom types you are using so we can recreate the repository and access the preview feature?

I have also been having a similar issue. When I set up previews it only displays my header and footer and not the content I’m trying to preview. Would you be able to explain how the previews are working under the hood? Our Gatsby layout component is rendering both the header and footer and is very simple. Does the project need to be set up in a specific way so that live previews work? Here is our layout.js

import React from 'react';
import PageHeader from './pageHeader';
import PageFooter from './pageFooter';



function Layout({ children }) {
  return (
    <div className="wrapper">
      <main className="main">
        <PageHeader />

        {children}

        <PageFooter />
      </main>
    </div>
  );
}

export default Layout;

Thanks so much!

Can we please get an ETA on when previews will work again using gatsby-source-prismic-graphql and Gatsby Image? Our content team is getting pretty frustrated by the lack of previews. I think the main issues with previews seems to be summed up in these two github issues:


Neither has had any activity from the maintainers in quite some time. Is the gatsby-source-prismic-graphql plugin still being actively developed?

I’m sorry for the delay. I’ve brought this up with the Prismic dev team and asked if someone there can take a look and follow up with you. They will let you know when they’ve picked this up from their queue.

Hello @teamgi,

From what i understand and my in experience previews are working fine. The problem seem to be when using gatsby-image.

I don’t use it myself and prefer to use imgix in order to make the build process faster. I realised that gatsby images is the process that is taking most of my build time.

I looked at the issues and all seemed to converge to the same problem.

If you want to use imgix you can look at this component that will offer a big set of options.

If you really want to make it work with gatsby-image feel free to do a pull request in order to solve this problem.

Thanks for the response. I think we’d happily use Imigix, but I was told by the Prismic staff there is no way to map my own domain for the image urls. This is a deal breaker for us since we need our client’s photo’s SEO to contribute to their main domain. Are custom domains for imigix urls a feature that is on the horizon?

I teamgi,

There is away to map your own domain names to the image-urls from prismic.

You’ll have to edit your dns record to redirect from your custom image domain to ours, and re-rewrite all of the image-urls in the api response your site receives from prismic to use that domain.

Also this could be a good feature request :slight_smile:

Best,

Marc

I think I might’ve found a solution to the Gatsby preview issue.

If you use the gatsby-node.js lifecycle hook onCreatePage to introduce a isProduction boolean, you can use a directive in your graphql query like this:

export const query = graphql`
  query PageQuery($isProduction: Boolean!, $lang: String!, $uid: String!) {
    prismic {
      page(lang: $lang, uid: $uid) {
        content
        page_title
        image
        imageSharp @include(if: $isProduction) {
          childImageSharp {
            id
            main: fixed(width: 1200) {
              ...GatsbyImageSharpFixed
            }
          }
        }
      }
    }
  }
`

This way, you can use the image source from Prismic in preview mode, and the Sharp-image in production:

{page.imageSharp 
    ? (<Img fixed={page.imageSharp.childImageSharp.main} />) 
    : (<img src={page.image.url} alt={page.image.alt} />)
}

However, I need to validate the fix, but I’m experiencing some trouble when saving my documents.

My GraphQL query resolves to an older version of my document for some reason, even in the Prismic GraphiQL interface.

Can anyone help me figure that out?

However, I need to validate the fix, but I’m experiencing some trouble when saving my documents.

What kind of trouble?

My GraphQL query resolves to an older version of my document for some reason, even in the Prismic GraphiQL interface.

That’s unusual, can you DM me the repository name so I can take a look?

Best,

Marc