DEV Community

Cover image for Making New Projects with Gatsby & Sanity
Ryan Doyle
Ryan Doyle

Posted on • Edited on

Making New Projects with Gatsby & Sanity

Why Gatsby & Sanity?

As I've spent more time developing, one thing I have been doing more often is building personal sites for other people. It's an easy way to keep practicing new frontend skills and techniques, as well as build up a portfolio that shows what you can do. One of the most annoying things about this, however, is creating an easy and custom way to manage content for those websites. There are tons of options out there like WordPress, but one of my favorite tools is Gatsby.

Why I like Gatsby

Gatsby is a super-fast static site builder with arguably the best documentation I've ever encountered. As a dev, it's an incredible platform. Gatsby is essentially data agnostic, meaning you can use nearly any data type to provide it with content. It could be a WordPress API, markdown, RSS feeds, it's great. Lately, my choice is for managing content easily is Sanity.

Why I Like Sanity

Sanity is essentially a super slick headless CMS/backend service. What's great about Sanity is that it comes with the Sanity Studio, a React application that you can run locally or host on a service such as Netlify. The beauty of it is that it allows you to define your own data types. The best way I can imagine explaining how it works (and why you would use it) is to compare it to a CMS such as Wordpress. With WordPress, you have pages and posts, and you can add tags and categories, but beyond that, you would essentially have to massage those types of data in an effort to create a site. That's confusing because the end-user could ultimately be dealing with having to manage data for their website that doesn't really describe their data appropriately. For example, if my wife (an actor) was using a platform such as Wordpress as a CMS and wanted to add a recent show that she performed to her resume, she might be making a new "Post" with a category. It works, but with Sanity, you could make your own data type called "Show" in the schema and that automatically creates a document type that could be edited by her (the end-user). For another example, I'm currently working on a site for a woodworker. They might want an area of their website that catalogs the different types of wood along with the wood properties for their readers. Using Sanity, I can make my own data-type for that. The great thing about Sanity is that you have the flexibility to create custom ways to store your data and manage your content (you can even edit the Sanity Studio itself because it's just a React app) all without having to set up your own database and manage all of that. For me, it's a happy space of having a custom CMS I can make for a particular client while not actually having to develop everything from scratch.

What We're Doing

In this post, I am going to be going over how to create a brand new, clean project in Gatsby and connecting it to Sanity as it's the primary data source. The Sanity site actually has a few starters you can use with just a few clicks, but it comes with a lot of pre-defined CSS, as well as the clutter of all the sample files that I don't necessarily want to deal with when starting a new project. Following these steps, you can grasp the basics of how Sanity and Gatsby work together and have a clean setup for both so you can use whatever you want for development, such as styling, file structure, etc. Here we go!

Steps

1 - Create Directory

So first we are going to create a directory for our project. I do this first because the CLI tools for Gatsby and Sanity are a little different and I also prefer to have both under a single git repo, so go ahead and make a directory named whatever, wherever you want. I named mine gatsby-sanity-starter.

2 - Create Sanity Studio

First, you need to install the Sanity CLI, so using npm run npm install -g @sanity/cli to install the CLI globally. After that, make a new directory in your root directory and name it studio. From the studio directory, run sanity init. The first time you do this you'll need to log in, create an account, and when prompted for a project, you are going to select Create a New Project and then for the project template you want to select Clean project with no defined schamas. This is going to create a brand new Sanity Studio inside the /studio directory.

3 - Create a Gatsby Site

If you have not already, install the Gatsby CLI with npm install -g gatsby-cli. Next, you're going to go to your root directory and run gatsby new web, which creates a new Gatsby project within the /web directory.

4 - Remove git from the Gatsby site

Next, we are going to remove git from the Gatsby site in the /web directory. This can be done by running rm -rf .git from within the /web directory. I prefer to do this because I like having a single git repo for both the studio (in /studio) and the actual website (in /web). Alternatively, you could run git init from within the /studio directory and have two separate repos for the studio and the website.

5 - Install gatsby-source-sanity

If you're new to Gatsby, a basic principle is that it uses plugins to incorporate various features. The plugin gatsby-source-sanity allows you to run GraphQL queries in your Gatbsy app against a GraphQL API route created by Sanity. You install this in a few steps.

  • From within the /web directory, run npm i gatsby-source-sanity --save.
  • Add the plugin config to the file gatsby-config.js
// in your gatsby-config.js
module.exports = {
  // ...
  plugins: [
    {
      resolve: 'gatsby-source-sanity',
      options: {
        projectId: 'abc123',
        dataset: 'blog',
        // a token with read permissions is required
        // if you have a private dataset
        token: process.env.MY_SANITY_TOKEN,
      },
    },
  ],
  // ...
}
Enter fullscreen mode Exit fullscreen mode
  • Within the plugin config, you need to replace the projectId and dataset with your Sanity project id and dataset name. You can find this in the /studio/sanity.json file.

6 - Create Your Schema

At this point, in order to check everything is up and running properly in terms of the connections between your Gatsby site and Sanity you'll need to create some type of basic Schema. When we created a new Sanity site, it is 100% void of any schema, so there isn't a way to see anything getting pulled into you Gatsby site. We will do this in 2 steps.

  • Create the file blogPost.js and sponsor.js *in the schemas directory so you have */studio/schemas/blogPost.js and /studio/schemas/sponsor.js with the following.
// in blogPost.js
export default {
  name: 'blogPost',
  title: 'Blog post',
  type: 'document',
  fields: [
    // ... other fields ...
    {
      name: 'name',
      title: 'Name',
      type: 'string'
    },
    {
      name: 'sponsor',
      title: 'Sponsor',
      type: 'sponsor'
    }
  ]
}

// in sponsor.js
export default {
  name: 'sponsor',
  title: 'Sponsor',
  type: 'object',
  fields: [
    {
      name: 'name',
      title: 'Name',
      type: 'string'
    },
    {
      name: 'url',
      title: 'URL',
      type: 'url'
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode
  • Import blogPost and sponsor into the types in schema.js.
import createSchema from 'part:@sanity/base/schema-creator'
import schemaTypes from 'all:part:@sanity/base/schema-type'

import blogPost from './blogPost';
import sponsor from './sponsor';

export default createSchema({
  name: 'default',
  types: schemaTypes.concat([
    /* Your types here! */
    blogPost,
    sponsor
  ])
})

Enter fullscreen mode Exit fullscreen mode

If you want to check out more about creating schemas in Sanity, the docs are here.

7 - Deploy GraphQL API

Anytime you modify your schema, you have to deploy your schema again so that your GraphQL API knows what's available to query. Since we just added a blogPost type and a sponsor type we need to deploy the API. We do this from /studio with the command sanity graphql deploy.

8 - Make Sample Blog Post

From /studio go ahead and run sanity start, and you can open up the Studio from localhost:3000. Here you should see the "Blog post" under Content, and you can click on that, and then the + button to create your first post. Just type in some filler info and move to the next step.

9 - Build Gatsby Site

Gatsby is a static site builder, so we need to build the site. Do this from /web with gatsby develop.

Once the site is built, you should be able to see the generic Gatsby starter page from localhost:8000, but if you head over to localhost:8000/__graphql you can see the graphQL playground. If all went well, there should be a few queries on the left that have Sanity in it, such as allSanityBlogPost. At this point, you can try running the query below and you should get data returned containing your blog post data you made.

query MyQuery {
  allSanityBlogPost {
    totalCount
    edges {
      node {
        _id
        name
      }
    }
  }
}

Enter fullscreen mode Exit fullscreen mode

That's It!

Hopefully, now you have a clean Gatsby site hooked up to a Sanity Studio! From here, you can develop a Gatsby site however you normally would while you have new custom headless CMS through Sanity. Let me know how it goes!

success

You can read more about Gatsby and Sanity from the source.

Top comments (10)

Collapse
 
wispyco profile image
Wispy • Edited

Thanks needed a reminder on what I did to get this setup with Gatsby before. One thing to note in your instructions sanity graphQL deploy needs to be lowercase sanity graphql deploy. And finally your importing import sp from './sponsor'; but your referencing it is sponsor lower down so it should be import sponsor from './sponsor'; Also I think you should be running gatsby develop not build, that's generally left for when your hosting your site, or if you need to check specific build things like lighthouse tests.

Collapse
 
doylecodes profile image
Ryan Doyle

Yes thanks! I made these changes

Collapse
 
guthries profile image
Guthrie • Edited

If anyone is getting issues on step 9 when running "gatsby develop" (such as Gatsby, React, or Sanity Types not found or missing) this is related to step 5 when the gatsby-source-sanity is installed. Some users have been having issues with NPM, but running the same via yarn seems to resolve and produce working builds for now.

More info here: github.com/gatsbyjs/gatsby/issues/...

Collapse
 
stu profile image
Stu Finn

This is exactly what I needed. Thanks!

Collapse
 
peterwitham profile image
Peter Witham

Thanks for this, I was looking for a simple explanation of how to mess with Sanity and you checked all the right boxes!

Collapse
 
abetoots profile image
abe caymo

The time it took me to read this and get it set up and running vs. the days I spent configuring WordPress to be a headless CMS. I'm kinda pissed.

Collapse
 
kmelve profile image
Knut Melvær

Thanks for this excellent guide Ryan!

Collapse
 
doylecodes profile image
Ryan Doyle

Of course! Love Sanity. Hope others can benefit.

Collapse
 
saiafonua profile image
Saia Fonua

Thanks Ryan! I appreciate the article!

Collapse
 
bayuangora profile image
Bayu Angora

What about Gatsby build time benchmark compared to Hugo?