Sourcing Data: Bringing External Content In
3 min read
Sourcing Data: Bringing External Content In Bringing in external material is referred to as "sourcing data" in Gatsby. Even though your Gatsby site is a frontend React application, you can incorporate data from a variety of sources, such as files on your computer, APIs from other parties, or headless content management systems (CMS).
The Role of Source Plugins and gatsby-config.js
Think of your Gatsby site as a chef and the data as the ingredients. To prepare a meal, the chef needs to know where to find the best ingredients. In the world of Gatsby, 'source plugins' are your trusted suppliers, and gatsby-config.js is your recipe book that tells you which suppliers to use.
Source Plugins: These are npm packages that fetch data from various sources. Whether your data resides in a local folder, a database, or a CMS, there's likely a source plugin for it.
gatsby-config.js: This file is the heart of your Gatsby project's configuration. It's where you list the plugins you want to use and provide any necessary options for them.
Here is an example of a gatsby-config.js file:
module.exports = {
plugins: [
'gatsby-plugin-react-helmet',
{
resolve: `gatsby-source-filesystem`,
options: {
name: `src`,
path: `${__dirname}/src`,
},
},
],
}In this example, we're telling Gatsby to use the gatsby-plugin-react-helmet and gatsby-source-filesystem plugins.
Reading Local Files: gatsby-source-filesystem
The gatsby-source-filesystem plugin is your go-to tool for reading files from your local file system. This is incredibly useful for a blog, a portfolio, or any site where you want to manage your content as files.
Installation:
npm install gatsby-source-filesystemConfiguration in gatsby-config.js:
module.exports = {
plugins: [
{
resolve: `gatsby-source-filesystem`,
options: {
name: `pages`,
path: `${__dirname}/src/pages`,
},
},
],
}With this configuration, Gatsby will source all the files in the src/pages directory. You can then use GraphQL to query these files and their contents.
Consuming External APIs and JSON Data
Your data might not always be in local files. Often, you'll need to fetch it from an external API. Gatsby makes this process straightforward.
Using an Existing Source Plugin
If there's a source plugin for the API you're using, that's the easiest way to go. For example, to source data from a GraphQL API, you can use gatsby-source-graphql.
Creating a Custom Source Plugin
If a source plugin doesn't exist for your data source, you can create your own. This gives you complete control over how the data is fetched and transformed.
Connecting a Headless CMS (Contentful, Sanity, or Strapi)
A headless CMS is a content management system that provides a way to author content, but instead of having an attached "head" (the presentation layer), it provides an API to deliver that content to any device or application.
Contentful
Contentful is a popular headless CMS. To connect it to your Gatsby site, you can use the gatsby-source-contentful plugin.
Installation:
npm install gatsby-source-contentfulConfiguration in gatsby-config.js:
require('dotenv').config()
module.exports = {
plugins: [
{
resolve: `gatsby-source-contentful`,
options: {
spaceId: process.env.CONTENTFUL_SPACE_ID,
accessToken: process.env.CONTENTFUL_ACCESS_TOKEN,
},
},
],
}Make sure to replace the spaceId and accessToken with your own from your Contentful account. For security, it's best to use environment variables to store these sensitive keys.
Strapi
Strapi is another powerful open-source headless CMS. The gatsby-source-strapi plugin allows you to seamlessly integrate your Strapi content into your Gatsby site.
Installation:
npm install gatsby-source-strapiConfiguration in gatsby-config.js:
module.exports = {
plugins: [
{
resolve: `gatsby-source-strapi`,
options: {
apiURL: `http://localhost:1337`,
queryLimit: 1000, // Default to 100
contentTypes: [`article`, `user`],
},
},
],
}By understanding how to source data, you unlock the full potential of Gatsby to build dynamic, data-driven websites with the performance benefits of a static site generator.
References:
- Gatsby Source Plugins Documentation
- Using gatsby-config.js
- gatsby-source-filesystem
- gatsby-source-contentful
- gatsby-source-strapi
By understanding how to source data, you unlock the full potential of Gatsby to build dynamic, data-driven websites with the performance benefits of a static site generator.
References:
Challenge
Challenge: Configure Multi-Source Data Fetching in Gatsby
Your task is to correctly configure a gatsby-config.js file for a project that needs to source content from local files, a Contentful CMS, and a Strapi CMS.
Update the plugins array in the provided initialCode to meet the following requirements:
Local Filesystem Source: Configure
gatsby-source-filesystemto source content from two distinct directories:- Markdown files for blog posts located in the path
__dirname + '/src/posts'. This source instance should be namedblog. - JSON files for portfolio projects located in the path
__dirname + '/src/portfolio'. This source instance should be namedportfolio.
- Markdown files for blog posts located in the path
Contentful CMS Source: Configure
gatsby-source-contentfulto fetch data from a Contentful space. The configuration must use environment variables for security.- Your Contentful Space ID is available at
process.env.CONTENTFUL_SPACE_ID. - Your Contentful Content Delivery API access token is at
process.env.CONTENTFUL_ACCESS_TOKEN.
- Your Contentful Space ID is available at
Strapi CMS Source: Configure
gatsby-source-strapito fetch data from a self-hosted Strapi instance.- The API URL for the Strapi instance is
process.env.STRAPI_API_URL. - The content types to be fetched are
articleandauthor. - Set the query limit for API requests to
1000.
- The API URL for the Strapi instance is
Assume all required npm packages (gatsby-source-filesystem, gatsby-source-contentful, gatsby-source-strapi, dotenv) are already installed and the .env file is set up correctly.
Expected result
Your gatsby-config.js file should correctly export a configuration object. The plugins array within this object must contain four new entries:
- Two separate configuration objects for
gatsby-source-filesystem.- The first should have its
nameoption set to'blog'andpathoption set to__dirname + '/src/posts'. - The second should have its
nameoption set to'portfolio'andpathoption set to__dirname + '/src/portfolio'.
- The first should have its
- One configuration object for
gatsby-source-contentful. Theoptionsobject should correctly mapspaceIdandaccessTokento their respectiveprocess.envvariables. - One configuration object for
gatsby-source-strapi. Theoptionsobject should have theapiURLproperty set toprocess.env.STRAPI_API_URL,queryLimitset to1000, andcontentTypesset to an array containing the strings'article'and'author'.
Each plugin configuration should be an object with a resolve property holding the plugin's name as a string, and an options property holding that plugin's specific configuration object.