JavaScript is required to view this website properly.

Anik Malik - BlogStep-by-Step Guide: How to Build a Blog with Sanity CMS

Title Image

Introduction

Hey there! 👋
If you've been curious about using a headless CMS for your next project, you're in the right place. Today, I'll walk you through setting up Sanity, a powerful and flexible CMS that lets you easily manage your content. By the end of this guide, you'll have a fully functional blog set up with Sanity. Ready? Let's dive in!

Step 1: Setting Up Your Sanity Project

1.1. Install the Sanity CLI

Before we get started, make sure you have Node.js and npm installed on your machine. Open up your terminal, and let's install the Sanity CLI:

npm install -g @sanity/cli

1.2. Create a New Sanity Project

Now, let's create a new Sanity project. Run the following command in your terminal:

sanity init

You'll be prompted to choose a few options:

  • Project Name: Name your project (e.g., my-sanity-blog).
  • Dataset: Select the default production dataset.
  • Project Template: Choose the "Clean project with no predefined schemas" option for more flexibility.

After this, Sanity will install all the necessary dependencies and set up your project. Once that's done, navigate into your project folder:

cd my-sanity-blog

1.3. Launch Sanity Studio

Let's see what we just created! Run:

sanity start

Open your browser and go to http://localhost:3333. You should see the Sanity Studio interface. 🎉

Step 2: Creating Your First Schema

Sanity uses schemas to define the structure of your content. Think of schemas as blueprints for your data. Since we're building a blog, we'll create a Blog Post schema.

2.1. Create a blogPost.js Schema File

In your project, go to the schemas folder and create a new file called blogPost.js. Add the following code:

export default {
  name: 'blogPost',
  type: 'document',
  title: 'Blog Post',
  fields: [
    {
      name: 'title',
      type: 'string',
      title: 'Title',
    },
    {
      name: 'slug',
      type: 'slug',
      title: 'Slug',
      options: { source: 'title', maxLength: 96 },
    },
    {
      name: 'body',
      type: 'array',
      title: 'Body',
      of: [{ type: 'block' }],
    },
    {
      name: 'mainImage',
      type: 'image',
      title: 'Main Image',
      options: { hotspot: true },
    },
    {
      name: 'author',
      type: 'reference',
      to: [{ type: 'author' }],
    },
    {
      name: 'publishedAt',
      type: 'datetime',
      title: 'Published At',
    },
  ],
};

2.2. Register the Schema

Next, we need to tell Sanity about our new schema. Open schema.js and make it look like this:

import createSchema from 'part:@sanity/base/schema-creator';
import schemaTypes from 'all:part:@sanity/base/schema-type';
import blogPost from './blogPost';

export default createSchema({
  name: 'default',
  types: schemaTypes.concat([blogPost]),
});

Now, save everything and restart your Sanity Studio:

sanity start

You should see Blog Post in the list of document types. Try creating a new blog post to test it out!

Step 3: Connecting Sanity with Your Frontend (Gatsby)

Alright, our Sanity Studio is up and running, but how do we display our blog posts on a website? For that, we'll use Gatsby, a popular React-based framework.

3.1. Set Up a New Gatsby Project

First, make sure you have Gatsby installed:

npm install -g gatsby-cli

Create a new Gatsby project:

gatsby new my-gatsby-blog
cd my-gatsby-blog

3.2. Install the Sanity Source Plugin

We need a way to pull data from Sanity into Gatsby. Let's use the gatsby-source-sanity plugin:

npm install gatsby-source-sanity

3.3. Configure gatsby-config.js

Open up your gatsby-config.js file and add the following configuration:

require('dotenv').config();

module.exports = {
  plugins: [
    {
      resolve: 'gatsby-source-sanity',
      options: {
        projectId: 'your_project_id',
        dataset: 'production',
        apiVersion: '2023-11-12',
        token: process.env.SANITY_TOKEN,
        useCdn: true,
      },
    },
  ],
};

Don't forget to create a .env file in the root of your Gatsby project and add your Sanity token:

SANITY_TOKEN=your_sanity_token

3.4. Querying Sanity Data with GraphQL

Now, let's fetch our blog posts. Create a new page at src/pages/blog.js:

import React from 'react';
import { graphql } from 'gatsby';

export const query = graphql`
  query {
    allSanityBlogPost {
      nodes {
        title
        slug {
          current
        }
        body {
          children {
            text
          }
        }
        publishedAt
      }
    }
  }
`;

const BlogPage = ({ data }) => {
  const posts = data.allSanityBlogPost.nodes;
  return (
    <div>
      <h1>My Blog</h1>
      {posts.map((post) => (
        <div key={post.slug.current}>
          <h2>{post.title}</h2>
          <p>{post.body[0]?.children[0]?.text}</p>
        </div>
      ))}
    </div>
  );
};

export default BlogPage;

3.5. Run Your Gatsby Site

Now let's see everything in action:

gatsby develop

Open your browser and go to http://localhost:8000/blog. You should see your blog posts from Sanity displayed on your Gatsby site! 🚀

Step 4: Deploying Your Site

When you're ready to share your blog with the world, you can deploy it to a platform like Netlify or Vercel.

Deploy to Netlify

  1. Push your code to GitHub.
  2. Go to Netlify, log in, and connect your GitHub repository.
  3. Click "Deploy" and let Netlify handle the rest!

Conclusion

And that's it! 🎉 You've just set up a blog using Sanity as your CMS and Gatsby as your frontend. I hope this guide was helpful and made the process a bit more fun. If you have any questions, feel free to drop a comment below or reach out to me!

Happy Coding! 💻😊