gatsby-source-prismic Technical Reference - v4

Overview

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

Dependencies and requirements

This plugin works with gatsby-plugin-prismic-previews to configure live previews in your Gatsby project

Also, 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 certain structured fields like Rich Text, Dates, and Links to your templates.

Installation

Install packages

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

  • npm
  • Yarn
Copy
npm install gatsby-source-prismic gatsby-plugin-image prismic-reactjs
Copy
yarn add gatsby-source-prismic 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:

Plugin option

Description

resolve

string (required)

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

options

object (required)

Property that holds all the plugin configuration.

options.repositoryName

string (required)

The name of your Prismic repository. If your prismic.io URL is 'https://my-cool-website.prismic.io/api/v2', 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.schemas

object (required if customTypesApiToken isn't defined)

Provide an object with all the Custom Type JSON schemas of your repository to load into Gatsby. If both customTypesApiToken and schemas are provided, the schemas object will take priority.

options.apiEndpoint

string

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

options.customTypesApiEndpoint

string

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

options.customTypesApiToken

string

An API token for your Prismic repository allows your Custom Type schemas to be automatically fetched from The Custom Types APIIf both customTypesApiToken and schemas are provided, the schemas object will take priority.

options.releaseID

string

If you provide a release ID, the plugin will fetch data from a specific Release in your repository. 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 a 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.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)

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

options.webhookSecret

string

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

options.transformFieldName

function

Transforms unsupported GraphQL characters into compatible ones. For example, "my-field" will get converted to "my_field". 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, node-fetch is used.

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:

Copy
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

This is required only 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

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
  • 〜/gatsby-config.js
Copy
// 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"
      }
    }
  }
}
Copy
// 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.

Copy
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: [
    // ...
    {
      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, '_'),
      },
    },
  ],
}

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.