Serve JSON from a Gatsby site using Contentful

X @urre

Serve JSON from a Gatsby site using Contentful

We recently had the need to serve a JSON file from the website to be consumed by another project. Very simple, but it needed to be possible to create the content from our CMS Contentful and also automatically be served from the website when the site has been built.

Let’s get started!

What’s involved?

  1. The content type on Contentful
  2. The content
  3. Fetching of the data
  4. Creating a JSON file
  5. Building the site

Create a content model on Contentful

Not covered in this post. But a standard Content type with relevant fields.

Fetch the data from Contentful

In gatsby-node.js we add the code to fetch the data from Contentful, and then create the JSON file.

exports.onPostBuild = async ({ graphql, reporter }) => {

The onPostBuild Node API runs after the build has been completed. It is the last extension point called after all other parts of the build process are complete. So this is what we want to use

To get the data we use a graphql query.

await graphql(`
    {
      notifications: allNotifications {
        edges {
          node {
            id
            title
            description
            link
          }
        }
      }
    }
  `).then(result => {
    const notifications = result.data.notifications.edges.map(
      ({ node }) => node
    )
    const data = []

    notifications.map(notification => {
        const notificationData = {
          id: notification.id,
          title: notification.title,
          description: notification.description,
          link: notification.link
        }

        data.push(notificationData)
        reporter.info(
          `Creating a notification: ${notification.title} in notifications.json`
        )
      }
    })
		...

Code in the file gatsby-node.js is run once in the process of building your site. You can use its APIs to create pages dynamically, add data into GraphQL, or respond to events during the build lifecycle.

Read more about Gatsby Node APIs

Create the JSON File

fs.writeFileSync(`public/notifications.json`, JSON.stringify(data))
...

Note: We need to use the fs module in gatsby-node.js to create a JSON file.

Then we save the file in the public folder.

[
  {
    id: "ce36f966-1588-5b30-9cb3-58ed43bca553",
    title: "Lorem ipsum dolor sit",
    description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus quis eros elit. ",
    link: "https://example.com/cool-page/"
  },
  {
    id: "ee45ca7a-3216-5fe5-853b-1d0918dad0b4",
    title: "Lorem ipsum dolor sit",
    description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus quis eros elit. ",
    link: "https://example.com/cool-page/"
  }
]

The JSON file will look like this.

Update the site when new content has been added

We have an automated process with webhooks that will be triggered when we publish or unpublish content in our Contentful space. The webhook triggers an automatic Pull Requst in our CI that builds and publish the site.

How to access the data?

Simple, the file will be served from example.com/notifications.json so just start making requests.

That’s all there is to it!