Skip to content

A Gatsby source plugin for building websites using Strapi as a data source

License

Notifications You must be signed in to change notification settings

relate-app/gatsby-source-strapi-graphql

Repository files navigation

Gatsby

Strapi Source Plugin

npm (version) npm (downloads)

Source plugin for pulling documents into Gatsby-v4 from the Strapi-v4 graphql API.

This plugin depends on Strapi's GraphQL introspection, which enables a lot of missing features in the plugin released by Strapi (i.e. grapqhl unions, builds failing due to missing data in fields, etc), but it also requires introspection to be enabled in production (read below how to enable it).

  • Deep nesting and dynamic zones
  • Relationships with other collection types (all types, one-way, two-way)
  • Supporting incremental builds using cache
  • Build caching and only fetching changes since last build
  • Support for images in markdown / richtext fields
  • No more failing builds do to missing content in fields
  • Optionally download images from Strapi: { download: true }

🚀 Installing the plugin

This version of gatsby-source-strapi-graphql is only compatible with Strapi v4+ and uses the graphql api of Strapi.

# Using Yarn
yarn add gatsby-source-strapi-graphql

# Or using NPM
npm install --save gatsby-source-strapi-graphql

🔥 Setting up the plugin

You can enable and configure this plugin in your gatsby-config.js file.

Basic usage

// In your gatsby-config.js
plugins: [
  {
    resolve: 'gatsby-source-strapi-graphql',
    options: {
      apiURL: 'http://localhost:1337',
      collectionTypes: ['Article', 'User'],
      singleTypes: ['Home Page', 'Contact'],
      // Extract images from markdown / richtext fields.
      inlineImages: {
        typesToParse: {
          Article: ['body'],
          ComponentBlockBody: ['text'],
        },
      },
      // Only include specific locales.
      locale: ['en', 'sv'], // defaults to 'all'
      // Include drafts in build.
      preview: true, // defaults to false
      // Use application token.
      token: 'xxx',
      // Add additional headers.
      headers: {},
      // Enable/disable cache.
      cache: false,
      // Only download specific file types when sourcing (don't add option if all should be downloaded).
      download: ['svg', 'pdf'], // defaults to all,
    },
  },
];

Production Requirements

Enable introspection of the schema in Strapi on the server by adding this snippet in ./config/plugins.js:

module.exports = ({ env }) => ({
  // ...,
  graphql: {
    config: {
      endpoint: "/graphql",
      apolloServer: {
        introspection: true,
      },
    },
  },
});

Internationalization support

Strapi now supports internationalization. But by default, this plugin will only fetch data in the default locale of your Strapi app. If your content types are available in different locales, you can also pass an entity definition object to specify the locale you want to fetch for a content type. Use the all value to get all available locales on a collection type, an array or comma separated list of locale codes will fetch only these locales.

Relationship support

Relationships to other collections both in collection fields and components are automatically connected to each other and included as a field if the node being linked to is included in the collectionTypes in your gatsby-config.

Draft content

Strapi now supports Draft and publish, which allows you to save your content as a draft and publish it later. By default, this plugin will only fetch the published content.

But you may want to fetch unpublished content in Gatsby as well. To do so, find a content type that has draft & publish enabled, and add an entity definition object to your config. Then, set preview to true in gatsby-config.

Authenticated requests

Strapi's Roles & Permissions plugin allows you to protect your API actions. If you need to access a route that is only available to a logged in user, you can provide your credentials (token) so that this plugin can access to the protected data.

Refresh content locally

Set ENABLE_GATSBY_REFRESH_ENDPOINT=true in your node env for gatsby, then you can add the a webhook in Strapi pointed towards http://localhost:8080/__refresh and see content update when saving it locally.

See more about this feature here: https://www.gatsbyjs.com/docs/refreshing-content/

Be aware there is a bug in v5 gatsby locally when this is enabled.

Parent relationship

You can now add a relationship in Strapi and have it hook up parent relationship automatic in Gatsby, make sure it's a singular relationship and using the field name "parent" for it to work. This feature can be used to build tree structured url patterns.

Querying data

You can query Document nodes created from your Strapi API like the following:

{
  allStrapiArticle {
    edges {
      node {
        id # Gatsby uuid
        strapiId # all types get this field
        title
        content
      }
    }
  }
}

You can query Document nodes in a chosen language:

{
  allStrapiArticle(filter: { locale: { eq: "en" } }) {
    edges {
      node {
        id
        title
        content
      }
    }
  }
}

To query images you can do the following:

{
  allStrapiArticle {
    edges {
      node {
        id
        singleImage {
          uri # remote url in strapi
          file {
            publicURL # local downloaded url
          }
        }
        multipleImages {
          uri # remote url in strapi
          file {
            publicURL # local downloaded url
          }
        }
      }
    }
  }
}

To query inline images for a markdown / richtext field named "text" you can do the following:

To replace in markdown / richtext use the base returned from the file and create a custom renderer to match the url on the image with the base.

{
  allStrapiArticle {
    edges {
      node {
        id
        text
        text_images {
          uri # remote url in strapi
          file {
            base
            publicURL # local downloaded url
          }
        }
      }
    }
  }
}

This version also adds support for union types (most commonly used on dynamic component fields). All types in the gatsby schema gets prepended with the Strapi namespace. To query for dynamic field types you can do the following:

{
  allStrapiArticle {
    edges {
      node {
        id
        blocks {
          ... on StrapiComponentBody {
            body
          }
          ... on StrapiComponentImage {
            image {
              uri # remote url in strapi
              file {
                publicURL # local downloaded url
              }
            }
          }
        }
      }
    }
  }
}

About

A Gatsby source plugin for building websites using Strapi as a data source

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors 4

  •  
  •  
  •  
  •