Skip to content

Latest commit

 

History

History
207 lines (173 loc) · 21.9 KB

File metadata and controls

207 lines (173 loc) · 21.9 KB

gatsby-source-prismic - v4

Overview

The gatsby-source-prismic plugin allows you to pull data from your Prismic repository into a Gatsby site.

Dependencies and requirements

The gatsby-plugin-image plugin helps you adding responsive images to your site and is required to support Gatsby's automatic image optimization component, <GatsbyImage>. And, the prismic-reactjs library helps to render specific structured fields like Rich Text, Dates, and Links.

Also, this plugin works with gatsby-plugin-prismic-previews to configure live previews in your Gatsby project

Installation

Install packages

Add the gatsby-source-prismic plugin and its peer dependencies to your Gatsby project via the command line:

npm:

npm install gatsby-source-prismic@4.2.0 gatsby-plugin-image prismic-reactjs

Yarn:

yarn add gatsby-source-prismic@4.2.0 gatsby-plugin-image prismic-reactjs

Configure the plugin

Define the plugin configuration in the gatsby-config.js file. The following table indicates all the fields that the plugin accepts:

Property Description
Plugin option

Description

resolve
string (required)

The name of the plugin. It must be 'gatsby-source-prismic'.

options
object (required)

Object that holds all the plugin configuration.

options.repositoryName
string (required)

The name of your Prismic repository. If your Prismic URL is 'https://my-cool-website.prismic.io/api/v2&#39;, your repo name is 'my-cool-website'.

options.accessToken
string

The access token for private APIs. Only needed if the API of your repository is private.

options.customTypesApiToken
string

Provide an API token for your Prismic repository to allow your Custom Type schemas to be automatically fetched from The Custom Types APIIf you provide both customTypesApiToken and schemas, the schemas object will take priority.

options.schemas
object (required if customTypesApiToken isn't defined)

Provide an object with all the Custom Type JSON schemas of your repository. If you provide both customTypesApiToken and schemas, the schemas object will take priority.

options.customTypesApiEndpoint
string

Provide the API endpoint used to fetch Custom Types from Prismic. In most cases, you can omit this option unless you require an API proxy or need to mock network responses. By default, your repository's standard endpoint will be used.

options.apiEndpoint
string

Provide the API endpoint used to fetch content from Prismic. In most cases, you can omit this option unless you require an API proxy or need to mock network responses. By default, your repository's standard endpoint will be used.

options.releaseID
string

If you provide a release ID, the plugin will fetch data from your repository's specific release. Note that if you add changes to a release, you'll need to rebuild your website to see them.

options.linkResolver
function

Set a Link Resolver to process links in your documents. You'll use it to process links in your content. Rich Texts, Links, and Content Relationship fields use this to generate the correct link URLs.

options.graphQuery
string with GraphQuery syntax

GraphQuery syntax allows you to fetch linked documents' content fields. Provide GraphQuery if you need to fetch nested content to make it available in your Link Resolver. All top-level fields are fetched for all documents by default.

options.htmlSerializer
function

The HTMLSerializer helps you customize the HTML output of a Rich Text field.

options.lang
string

Set a default language when fetching documents. The default value is '*', which will fetch all languages. Read Multilingual content.

options.pageSize
number

Set the maximum page size used when fetching documents from the Prismic API. If you reach API limits due to large documents, set this to a number less than the maximum (100). By default, the API used the maximum page size of 100.

options.imageImgixParams
object

Provide a default set of Imgix image transformations to your images. These options will override the default Imgix transformations set by Prismic.

options.imagePlaceholderImgixParams
object

Provide a default set of Imgix image transformations applied to the placeholder of your images. These parameters will override those provided in the above imageImgixParams option.

options.typePrefix
string (required when sourcing from more than one repository)

Provide a prefix for all GraphQL types for your Prismic repository. If you have multiple repositories, each plugin should have a unique typePrefix to avoid type conflicts.

options.webhookSecret
string

If you configure your Prismic repository's Webhooks to send a secret, provide the secret here. A secret allows you to confirm the Webhook is from Prismic. This step is optional and only used if you integrate your site with Gatsby Cloud.

options.transformFieldName
function

This option transforms unsupported GraphQL characters into compatible ones. For example, "my-field" will get converted to "myfield". Usually, you won't need to provide a value for this option. By default, fields with "-" will be converted to "".

options.fetch
function

Provide a custom fetch-compliant function for making network requests. This allows for custom request handling, like using an HTTP Agent for working behind a firewall. By default, it will use node-fetch.

Releases

You can provide a releaseID option to the plugin to build a release version of your website. You can get a release ID by using the Prismic REST API:

curl https://my-repository-name.prismic.io/api/v2
# =>
#   {
#     "refs": [
#       {
#         "id": "master",
#         "ref": "XoS0aRAAAB8AmarD",
#         "label": "Master",
#         "isMasterRef": true
#       },
#       {
#         "id": "Xny9FRAAAB4AdbNo",
#         "ref": "Xr024BEAAFNM2PNM~XoS0aRAAAB8AmarD",
#         "label": "My release"
#       }
#       ...
#     ],
#   }

In the refs array of the response, the id property of the refs object is a release ID. The label identifies the release's purpose. Master, for example, is the latest published version of all your documents. Your other Prismic Releases will be listed here with their names.

Note that a release build is totally compatible with live client-side previews. Building with a release is a way to view another version of your website, but it works the same way as the default build under the hood.

Manual Custom Type schemas setup

The manual Custom Type setup is required if you do not provide a value to customTypesApiToken.

Follow these steps to enable the manual setup:

  1. At the root of your project, create a custom_types folder
  2. Open the new folder and create JSON files for each Custom Type that exists in your repository
  3. In your repository, go to each of your Custom Type, click on the JSON editor tab, copy the object and paste it into each file
  4. Import each Custom Type JSON in the schemas of the plugin configuration. Also, provide an empty object for each inactive Custom Type.

In this example, we have one repeatable Custom Type with the API ID of 'Page'. We copy the JSON object from our repository's Custom Type editor > JSON Editor tab and paste it into the file. See how we declare this schema in the custom_types folder and the plugin configuration.

〜/custom_types/page.json:

// Example json schema configuration
{
	"Main": {
		"uid": {
			"type": "UID",
			"config": {
				"label": "uid"
			}
		},
		"title": {
			"type": "StructuredText",
			"config": {
				"single": "heading1, heading2, heading3, heading4, heading5, heading6",
				"label": "Title",
				"placeholder": "Title"
			}
		},
		"description": {
			"type": "StructuredText",
			"config": {
				"multi": "paragraph, preformatted, heading1, heading2, heading3, heading4, heading5, heading6, strong, em, hyperlink, image, embed, list-item, o-list-item, rtl",
				"label": "description",
				"placeholder": "description"
			}
		}
	}
}

〜/gatsby-config.js:

// Example plugin configuration
plugins: [
	{
		resolve: "gatsby-source-prismic",
		options: {
			// ...
			schemas: {
				page: require("./custom_types/page.json"),
			},
			// ...
		},
	},
];

Usage

In this example plugin configuration, we are declaring all the possible available options.

const linkResolver = require("./example-route-to-linkResolver");
const htmlSerializer = require("./example-route-to-htmlSerializer");

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

module.exports = {
	plugins: [
		// ...
		"gatsby-plugin-image",
		{
			resolve: "gatsby-source-prismic",
			options: {
				repositoryName: process.env.GATSBY_PRISMIC_REPO_NAME,
				accessToken: process.env.PRISMIC_ACCESS_TOKEN,
				customTypesApiToken: process.env.PRISMIC_CUSTOM_TYPES_API_TOKEN,
				schemas: {
					example_type: require("./custom_types/example_type.json"),
				},
				apiEndpoint: process.env.PRISMIC_API_ENDPOINT,
				customTypesApiEndpoint: process.env.PRISMIC_CUSTOM_TYPES_API_ENDPOINT,
				releaseID: process.env.PRISMIC_RELEASE_ID,
				linkResolver: (doc) => linkResolver(doc),
				graphQuery: `
          {
            // Your graphQuery
          }
        `,
				htmlSerializer: (type, element, content, children) => {
					// Return HTML for an piece of content.
				},
				lang: "*",
				imageImgixParams: {
					auto: "compress,format",
					fit: "max",
					q: 50,
				},
				imagePlaceholderImgixParams: {
					w: 100,
					blur: 15,
					q: 50,
				},
				typePrefix: "Prefix",
				webhookSecret: process.env.PRISMIC_WEBHOOK_SECRET,
				transformFieldName: (fieldName) => fieldName.replace(/-/g, "_"),
			},
		},
	],
};