Building a Blog with Sanity IO and Gatsby

5 min. read

Now more than ever people are telling you to start your own blog but not a lot of people necessarily know where is the best place. While there's so many places to start writing with tools like Substack and Medium, I wanted to ensure that I had full control and ownership of my own content without any platform restrictions using other CMS tools like Wix, Wordpress, or Squarespace which is why I wanted to build my own.

Building and self-hosting your own blog comes with it's own share of challenges such as how to set up hosting, knowing which framework to use, and how to maintain it in a seamless way. I had been thinking about hosting my own blog for awhile and I was open to trying new frameworks that would give me the ownership, but would also have a low barrier to entry when it comes to deployment. I wanted to try something new while also mixing it with something I was familiar with so I decided to use Gatsby and Sanity IO to build my own personal blog. This guide will detail my initial and final thoughts of using Sanity IO and different elements that came into play.

Why Sanity IO + GatsbyJS?

Sanity IO is a platform that allows you to manage text, images, and other media with APIs. You have the ability to have one place to store your content to use across whatever platform you choose. GatsbyJS is a React based static site generator. I wanted to test out Sanity IO because I had been hearing about it through the tech community so I saw this as a challenge for myself and I was already familiar and really enjoy Gatsby (you can see another site that I build with Gatsby here). Pairing these two together seemed like the perfect solution, and while it was, it was a huge learning curve.

First Thoughts

Sanity and Gatsby both provide incredible documentation. I went through Sanity IO docs first used their starter template and felt that I was ready to go. That wasn't the case for me. I was able to deploy the site no problem but then started having tons of errors when trying to make changes. After a couple of days of beating my head against the wall and trying to get help from the Sanity IO community, I was honestly ready to give up. However I found a starter template on GatsbyJS and followed their instructions in the README.md file and I was good to go! Through this, I learned I would need to check both Gatsby JS and Sanity IO documentation in order to find the best solution.

GraphQL

GraphQL is how you access the data stored in Sanity IO, I was somewhat familiar with GraphQL when using Gatsby in the past, but when using GraphQL with just Gatsby, if it was too confusing to me, I just added the content I needed myself. With Sanity IO, GraphQL was inevitable so I had to get up to speed on GraphQL.

Understanding Schemas

Schemas are used to define the different object types that can be stored and referenced in Sanity IO. All schemas should live in your schema directory. If you want your object to appear as an object that you can create different ones for within the studio, you need to specify the type as a document:

export default {
    name: 'category',
    type: 'document',
    title: 'Category',
    fields: [
      {
        name: 'title',
        type: 'string',
        title: 'Title'
      },
      {
        name: 'description',
        type: 'text',
        title: 'Description'
      }
    ]
  }

You can also reference other object types in other objects as well:

export default {
    name: 'post',
    type: 'document',
    title: 'Blog Post',
    fields: [
		//	...
      {
        name: 'categories',
        type: 'array',
        title: 'Categories',
        of: [
          {
            type: 'reference',
            to: {
              type: 'category'
            }
          }
        ]
      },
    //  ...
    ],
//	...
}

All objects need to be imported in the schema.js file in order to be used within the studio.

//Schema.js File
import schemaTypes from 'all:part:@sanity/base/schema-type'
import createSchema from 'part:@sanity/base/schema-creator'

import category from './category'
import post from './post'

export default createSchema({
  // We name our schema
  name: 'default',
  types: schemaTypes.concat([
    post,
    category,
  ])
})

Dynamically Adding New Pages

For objects types that generate new pages (blog posts, projects, etc.). You need to reference them in the gatsby-node.js


const createContentPages = async (graphql, actions, reporter) => {
  const { createPage } = actions
  const getContentResult = await graphql(`
    {
      allSanityPost {
        nodes {
          id
          slug {
            current
          }
        }
      }
    }

  `)
  if (getContentResult.errors) {
    throw getContentResult.errors
  }

  const posts = getContentResult.data.allSanityPost.nodes || []
  posts.forEach((node) => {
    const path = `/blog/${node.slug.current}`
    createPage({
      path,
      component: require.resolve("./src/templates/post/post.tsx"),
      context: { id: node.id },
    })
  })
}

exports.createPages = async ({ graphql, actions, reporter }) => {
  await createContentPages(graphql, actions, reporter);
}

In your template directory code the styling that will be used for those pages.

Continuous Deployment

If you're using the starter that I used before, the studio and the website live in two different places on the internet. I deployed my website using Netlify which allows you to quickly deploy your site (literally in a few minutes). I love the fact that when I make a change in the code and run git push it will trigger the site to deploy those changes. That being said, the website doesn't update automatically if you make changes to the studio. This can easily be resolved with hooks

In Gatsby, you need to:

  1. Go to your site → settings
  2. Click to the Build and Deploy Tab
  3. Go to the Build Hooks section
  4. Add a Build Hook
  5. Copy the URL generate

For Sanity IO, you need to,

  1. Select the project
  2. Go to settings
  3. Click the API tab
  4. Add new webhook
  5. Paste the URL from Gatsby in the URL sec

All in all, I love using Sanity IO and I'm excited to build new websites with it and Gatsby in the future. The possibilities for storing data within Sanity are endless and I can wait to try new things in the future. There's also an amazing Slack Community that people across the world are friendly and willing to answer any and all questions. I hope the tricks that I learned will help you get started on your own blog or portfolio!