Mastering Sanity: A Comprehensive Guide to Building Modern Web Projects with a Headless CMS

Mastering Sanity: A Comprehensive Guide to Building Modern Web Projects with a Headless CMS


Sanity is a versatile headless content management system (CMS) designed to provide developers with an API-first approach to building and managing content. Its flexibility and extensibility make it an excellent choice for modern web development projects, whether you're building websites, mobile applications, or complex web applications. In this article, we'll explore Sanity in-depth, covering its features, how to get started, and how to create custom schemas and integrate with your frontend applications.

What Sets Sanity Apart?

Sanity offers a unique set of features that sets it apart from other headless CMS options:

  1. Real-time Content Collaboration: Sanity provides real-time collaboration capabilities, allowing multiple team members to work on content simultaneously and see each other's changes instantly.
  2. Customizable Content Schemas: Sanity allows you to create custom content schemas using JavaScript, providing complete control over your content model and validation.
  3. GraphQL and GROQ: Sanity supports both GraphQL and its own query language, GROQ (Graph-Relational Object Queries), giving you powerful and flexible ways to query your content.
  4. Extensibility: Sanity is highly extensible, with a plugin system that enables you to add custom functionality to your CMS or integrate with third-party services.
  5. Portable Text: Sanity's Portable Text format allows you to store rich text as structured data, making it easy to transform and display in various output formats.

Getting Started with Sanity

To get started with Sanity, follow these steps:

1. Install the Sanity CLI: First, ensure you have Node.js installed on your system. Then, run the following command to install the Sanity CLI globally:

  1. npm install -g @sanity/cli

2. Create a Sanity Project: Run the following command to create a new Sanity project:

  1. sanity init

Follow the prompts to set up your project. This will create a new folder with the necessary files to begin building your Sanity project.

3. Start the Sanity Studio: Navigate to your project folder and run the following command to start the Sanity Studio, a web-based editing interface for your content:

  1. sanity start

Open your browser and navigate to http://localhost:3333 to access the Sanity Studio.

4. Deploy your Sanity Studio: To make your Sanity Studio accessible to other team members, you can deploy it to Sanity's hosting platform. Run the following command to deploy:

  1. sanity deploy

Creating Custom Schemas in Sanity

Sanity's content schemas are written in JavaScript, allowing you to define your content structure and validation rules. To create a custom schema, follow these steps:

1. Create a schema file: In your Sanity project folder, navigate to the `schemas` folder and create a new JavaScript file for your schema (e.g., `post.js`).
2. Define your schema: In the schema file, import the required Sanity schema types and define your schema using JavaScript objects. For example:

  1. import { FaFileAlt as icon } from 'react-icons/fa';
  2. import { format } from 'date-fns';
  4. export default {
  5. name: 'post',
  6. title: 'Blog Post',
  7. type: 'document',
  8. icon,
  9. fields: [
  10. {
  11. name: 'title',
  12. title: 'Title',
  13. type: 'string',
  14. validation: (Rule) => Rule.required(),
  15. },
  16. {
  17. name: 'slug',
  18. title: 'Slug',
  19. type: 'slug',
  20. options: {
  21. source: 'title',
  22. maxLength: 96,
  23. },
  24. },
  25. {
  26. name: 'author',
  27. title: 'Author',
  28. type: 'reference',
  29. to: { type: 'author' },
  30. },
  31. {
  32. name: 'mainImage',
  33. title: 'Main Image',
  34. type: 'image',
  35. options: {
  36. hotspot: true,
  37. },
  38. },
  39. {
  40. name: 'body',
  41. title: 'Body',
  42. type: 'blockContent',
  43. },
  44. ],
  45. preview: {
  46. select: {
  47. title: 'title',
  48. author: '',
  49. media: 'mainImage',
  50. },
  51. prepare(selection) {
  52. const { author } = selection;
  53. return {
  54. ...selection,
  55. subtitle: author && `by ${author}`,
  56. };
  57. },
  58. },
  59. };

3. Register your schema: In the `schemas/schema.js` file, import your custom schema and add it to the `types` array:

  1. import createSchema from 'part:@sanity/base/schema-creator';
  2. import schemaTypes from 'all:part:@sanity/base/schema-type';
  3. import post from './post';
  4. import author from './author';
  5. import blockContent from './blockContent';
  7. export default createSchema({
  8. name: 'default',
  9. types: schemaTypes.concat([post, author, blockContent]),
  10. });

Integrating Sanity with Frontend Applications

Sanity provides APIs to interact with your content from your frontend applications. You can use either the REST API or the GraphQL API, depending on your preference. Here's an example of how to query your Sanity content using GraphQL and integrate it into a React application:

1. Enable the GraphQL API: In your Sanity project folder, run the following command to enable the GraphQL API and deploy a schema based on your content:

  1. sanity graphql deploy

2. Install the required packages: In your React application, install the `@sanity/client` and `@apollo/client` packages:

  1. npm install @sanity/client @apollo/client

3. Configure the Sanity client: Create a new file in your React application (e.g., `sanity.js`) and configure the Sanity client with your project ID and dataset:

  1. import { createClient } from '@sanity/client';
  3. export default createClient({
  4. projectId: 'your-project-id',
  5. dataset: 'your-dataset',
  6. useCdn: true,
  7. });

4. Query your content: In your React component, use the `@apollo/client` package to query your content using GraphQL:

  1. import React from 'react';
  2. import { useQuery, gql } from '@apollo/client';
  3. import sanityClient from './sanity';
  5. const POSTS_QUERY = gql`
  6. query {
  7. allPost {
  8. title
  9. body
  10. }
  11. }
  12. `;
  14. const BlogPosts = () => {
  15. const { loading, error, data } = useQuery(POSTS_QUERY, {
  16. context: { clientName: 'sanity' },
  17. });
  19. if (loading) return <p>Loading...</p>;
  20. if (error) return <p>Error: {error.message}</p>;
  22. return (
  23. <div>
  24. { => (
  25. <div key={post.title}>
  26. <h2>{post.title}</h2>
  27. <p>{post.body}</p>
  28. </div>
  29. ))}
  30. </div>
  31. );
  32. };
  34. export default BlogPosts;

5. Configure the Apollo Client: In your `index.js` file or a separate configuration file, set up the Apollo Client to use the Sanity client for GraphQL queries: 

  1. import React from 'react';
  2. import ReactDOM from 'react-dom';
  3. import { ApolloClient, InMemoryCache, ApolloProvider, HttpLink } from '@apollo/client';
  4. import sanityClient from './sanity';
  5. import App from './App';
  7. const link = new HttpLink({
  8. uri: sanityClient.clientConfig.url + '/graphql/' + sanityClient.clientConfig.dataset + '/default',
  9. headers: {
  10. 'Content-Type': 'application/json',
  11. 'Authorization': `Bearer ${sanityClient.config().token}`,
  12. },
  13. });
  15. const client = new ApolloClient({
  16. link,
  17. cache: new InMemoryCache(),
  18. name: 'sanity',
  19. });
  21. ReactDOM.render(
  22. <ApolloProvider client={client}>
  23. <App />
  24. </ApolloProvider>,
  25. document.getElementById('root')
  26. );

Now you're ready to fetch data from Sanity and display it in your React application using GraphQL. You can adapt this approach to other frontend frameworks and libraries as well.


Sanity is a powerful and flexible headless CMS that provides developers with the tools to create, manage, and deliver content efficiently. Its customizable schemas, real-time collaboration, and API-first approach make it an excellent choice for modern web development projects. By following this guide, you can harness the power of Sanity to build robust and scalable applications.

We use cookies to improve your browsing experience. By continuing to use this website, you consent to our use of cookies. Learn More