How to setup Prismic preview with Gatsby

  • 📖 ~6 mins to read

If you need some help setting up Prismics preview functionality with GatsbyJS, this post is here to help.

Whilst Prismic have their guide on setting up preview I ran into several issues whilst following along – so I wrote this post to help others who might be running into similar issues.

Setting up your project

This post assumes you are using the gatsby-source-prismic-graphql plugin and already have a Prismic repository and GatsbyJS project setup – this can be a fresh install or an existing project.

Install gatsby-source-prismic-graphql plugin

At the time of writing I am using "gatsby-source-prismic-graphql": "^3.6.2" – if you are running into issues try using this version. I had to upgrade and downgrade the plugin several times before I found a version that worked properly.

Or you could just install the latest version by running:

npm install --save gatsby-source-prismic-graphql

Install gatsby-source-graphql-universal plugin (optional)

If you’ve set everything else up in this post and preview still isn’t working, try to install gatsby-source-graphql-universal as a dependency (it’s a dependency of gatsby-source-prismic-graphql).

At the time of writing, I am using "gatsby-source-graphql-universal": "3.3.0".

Or you could just install the latest version by running:

npm install --save gatsby-source-graphql-universal
Never miss out on new articles

Get new articles straight to your inbox. Your information won’t be used for anything besides sharing updates with you.

Configure gatsby-config.js

Next, let’s configure the gatsby-source-prismic-graphql plugin inside gatsby-config.js. You’ll probably already have a bunch of plugins set up in here, but here is a snippet of code for setting up gatsby-source-prismic-graphql:

module.exports = {
	plugins: [
		{
			resolve: 'gatsby-source-prismic-graphql',
			options: {
				repositoryName: process.env.GATSBY_PRISMIC_REPO,
				accessToken: process.env.GATSBY_PRISMIC_ACCESS_TOKEN,
				path: '/preview',
				previews: true,
				pages: [
					{
						component: require.resolve('./src/templates/content.js'),
						match: '/:uid',
						previewPath: '/content-preview',
						type: 'Content_page',
					},
				],
			},
		},
	],
};

Let’s walk through this code block in more detail.

Respository Name

The repositoryName can be found in your Prismic repository, it’s usually the string in the URL before the .prismic.io part of the URL. For example, if the URL is https://myproject.prismic.io then the repositoryName would be myproject.

Access Token

The accessToken can be found in your Prismic repository under Settings > API & Security > Generate an Access Token once setup you’ll want to use the Permanent access tokens which gets generated for you.

You can generate a new access token in Prismic by navigating to Settings > API & Security > Generate an Access Token

Path

You can set path to whatever you want but /preview is a suitable name. It’s important to remember this as you’ll need it later when setting up preview in Prismic.

Previews

Set previews to true, as it initialises all the code to enable preview to work.

Pages

The pages array is used to generate all your different pages based on their typename, component, match and type are all used for generating the page (it’s worth noting type is case sensitive, so if your page isn’t getting created try setting the first letter to a capital.

Pages previewPath

previewPath is used as a placeholder page for unpublished documents for this page type (the key name used to be path but was updated to previewPath to make it clearer).

Create a linkResolve.js file

You’ll want to create a link resolver file in your src directory, src/utils/linkResolver.js is the typical place to put it – but you could put it anywhere.

For more information on link resolvers and their use cases checkout Prismics guide on link resolving.

Here’s some example code for the linkResolver.js file:

export const linkResolver = (doc) => {
	// Depending on the graphql response there may be a _meta object
	const properties = doc._meta || doc;

	// URL for content pages
	if (properties.type === 'content_page') {
		return `/${properties.uid}`;
	}

	// Backup URL for home page
	return '/';
};

The main point I want to pick up here is that the properties.type === 'content_page' the content_page value has a lowercase letter at the start, whereas in the gatsby-config.js file it has a capital letter – so again bare this in mind if pages aren’t redirecting correctly when clicking the preview button in Prismic.

Register linkResolver in gatsby-browser.js

Now we need to tell Prismic to use the link resolver we just created. To do this open up the gatsby-browser.js file in the root of the project and add the following code:

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

Just make sure that you update the linkResolver path if you didn’t put it in the src/utils folder.

Setup preview in Prismic

For the last step, log into your Prismic repository and navigate to Settings > Previews > Create a New Preview.

You can create a new preview by navigating to Settings > Previews > Create a New Preview

The Site Name can be set to anything. Production, Staging etc. might be suitable if you want preview setup for multiple environments. Or you could simply set it to Preview.

Domain for Your Application is the URL you want previews to show up on, this can be a live URL or localhost. You might want to use http://localhost:8000 whilst setting up preview to help debug any issues.

Link Resolver this should match the string you set in your gatsby-config.js file for the path field – in our case, it’s /preview.

And that’s it, preview should be working now, if not you might be running into some issues I’ve not come across or one of the limitations in the following section.

Preview limitations/issues

Whilst I ran into a bunch of issues setting up preview (I resolved most of them by using version ^3.6.2 of the gatsby-source-prismic-graphql plugin), 2 remain to be a limitation/issue as far as I can tell:

  • AWS products like S3 and Amplify have a trailing slash (/) issue which stops previews from working properly
  • There is a limit on how long your graphql queries can be

AWS trailing slash issue

I recently came across this issue on a project that is using AWS S3 for hosting (someone reported the same issue on AWS Amplify).

In short, Prismics preview functionality relies on query strings in the URL to redirect the user to the correct page. However, AWS hosting will remove query strings from the URL if it does not have a trailing slash on the end of the URL; e.g:

  • https://robsimpson.digital/preview/ works
  • https://robsimpson.digital/preview doesn’t work

A simple solution is to set the Link Resolver in Prismic to /preview/ which solves the issue of redirecting the user to the correct page when previewing. But it does not resolve the issue for unpublished documents.

Unpublished documents have an extra page in the URL path e.g. https://robsimpson.digital/preview/content_page but there aren’t any settings to configure this – if you have any ideas message me on Twitter.

I’ve raised this issue on the Prismic community forum if you want to have your say or see if there are any new updates on the issue.

AWS trailing slash workaround

The workaround I had to employ was to have a separate instance of the site running on Netlify purely for preview purposes as Netlify doesn’t have this issue.

GraphQL query limit

If content updates aren’t showing during preview, check your browser console. If you have an error which says 414 Request-URI Too Large, chances are your graphql query is too long.

gatsby-source-prismic-graphql recently rolled out an optimisation for large queries but Prismics API still has a limit.

✌️

I hope this post helps you setting up preview with Prismic and Gatsby, I’ll continue to update this post with new information as I come across it. If you have any info on the limitations listed above, feel free to message me on Twitter.

Rob Simpson

UI/UX Designer & Front-End Developer bridging the gap between user goals and business needs