Skip to content

Custom Sanity Image Types

Corey Ward edited this page Jan 29, 2021 · 1 revision

In Sanity it's possible to define custom types on top of the provided image type, like this:

{
  name: "myImage",
  type: "image",
}

When your GraphQL schema is generated by Sanity, this will become a MyImage type, but it will not implement a common interface with the SanityImage type. This means that the Image and ImageWithPreview fragments provided by this plugin will not work on MyImage out of the box.

To resolve this, we need to modify the GraphQL schema in Gatsby to declare SanityImage and MyImage as implementing a common type that the fragments can be declared on. Starting with v0.3.0, this can be achieved using the customImageTypes option when configuring gatsby-plugin-sanity-image in your gatsby-conf.js file. For example:

// gatsby-conf.js
module.exports = {
  plugins: [
    // your other plugins here
    {
      resolve: "gatsby-plugin-sanity-image",
      options: {
        projectId: process.env.SANITY_PROJECT_ID,
        dataset: process.env.SANITY_DATASET,
        customImageTypes: ["SanityMyImage"],
      },
    },
  ],
}

After adding this configuration directive, restart your local development server and you should see warnings like this in your terminal:

warn Plugin gatsby-plugin-sanity-image has customized the GraphQL type SanityImage, which has already been defined by the plugin gatsby-source-sanity. This could potentially cause conflicts.

warn Plugin gatsby-plugin-sanity-image has customized the GraphQL type SanityMyImage, which has already been defined by the plugin gatsby-source-sanity. This could potentially cause conflicts.

This is expected. Gatsby is simply warning that gatsby-source-sanity might not be expecting gatsby-plugin-sanity-image to be modifying the GraphQL types it has defined.

In the unlikely event that you encounter issues with a specific version of gatsby-source-sanity, please open an issue in this repository (not gatsby-source-sanity) with detailed information.

Clone this wiki locally