Blog

How To Build a Gatsby Blog with Sanity

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 sanity-blog.

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.

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.

Create Your Schema

Create the file blogPost.js and sponsor.js *in the schemas directory so you have */studio/schemas/blogPost.js and /studio/schemas/category.js with the following. **These are the namesI chose.You can choose depending on what you are creating

Make Sample Blog Post

Anytime you modify your schema, you have to deploy your schema again so that your GraphQL API knows what's available to query. 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.

Build Gatsby Site

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.

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!

© 2022, Built by

@TJ