Getting started overview

Getting started with Sanity involves setting up a local development environment, creating a Sanity project, and interacting with the Sanity Content Lake. The process typically begins with the Sanity Command Line Interface (CLI), which facilitates project initialization and deployment of the Sanity Studio. The Studio is a customizable content editing environment built with React, where content schemas are defined using JavaScript. Once content is added through the Studio, it resides in the Content Lake, a real-time data store. Developers then retrieve this structured content using either the GROQ (Graph-Relational Object Queries) query language or GraphQL endpoints.

The core components for a functional Sanity setup include:

  • Sanity CLI: A command-line tool for project management, Studio deployment, and data interaction.
  • Sanity Project: Contains the Studio's configuration, including content schemas and API settings.
  • Sanity Studio: A web-based interface for content creators, built on React, allowing for real-time collaborative editing.
  • Sanity Content Lake: The cloud-based data store for all structured content, accessible via APIs.

This guide will walk through the initial steps: setting up your account, installing the necessary tools, creating a new project, and performing a basic query to retrieve content.

Create an account and get keys

To begin using Sanity, an account is required. Sanity offers a Starter (Developer) free tier that includes access for up to three users, 10,000 document reads, and 100,000 API CDN requests per month. This tier provides enough resources for initial development and small projects.

Account creation

1. Navigate to the main Sanity website and locate the sign-up or get started option. 2. You can sign up using an existing GitHub account, Google account, or by creating a new account with your email address. 3. Follow the on-screen prompts to complete the registration process. This typically involves email verification if using the email option.

Project ID and API Tokens

Upon creating an account and initializing your first project (often guided through the CLI setup process), Sanity will assign a unique projectId to your project. This ID is essential for all API interactions, as it identifies which Content Lake your requests are targeting.

For most read operations against the Content Lake, no explicit API token is needed if the dataset is public. However, for write operations, authenticated reads against private datasets, or advanced features, you will need to create API tokens. These tokens are generated within the Sanity project settings in the Sanity management interface. When generating a token, you can define its scope (e.g., read, write, deploy) and associate it with specific datasets. It is critical to treat API tokens as sensitive credentials and store them securely, particularly in server-side environments or using environment variables in client-side applications.

Your first request

This section outlines the steps to make your first interaction with the Sanity Content Lake, starting with local setup and schema definition.

1. Install the Sanity CLI

The Sanity CLI is the primary tool for managing your Sanity projects. Install it globally using npm or Yarn:

npm install -g @sanity/cli
# or
yarn global add @sanity/cli

2. Create a new Sanity project

Initialize a new Sanity project in your desired directory. This command will prompt you to log in (if not already), select a project template, and define your project's dataset and deploy the Studio.

sanity init

During the sanity init process, you will be asked to:

  • Log in/Sign up: If not already logged in via the CLI.
  • Select a project template: Choose a starter template (e.g., "Clean project with no predefined schemas" or "Blog (with Next.js app)").
  • Create a new project or select an existing one: For a first-time setup, create a new project.
  • Project name: A human-readable name for your project.
  • Dataset name: The default is production.
  • Deploy Sanity Studio: This publishes your content editing environment to a URL.

3. Define a content schema

After initialization, navigate into your new project directory to define your content schema. Schemas are JavaScript objects that describe the structure of your content. For example, to define a post type:

// In your-project/schemas/post.js
export default {
  name: 'post',
  title: 'Post',
  type: 'document',
  fields: [
    {
      name: 'title',
      title: 'Title',
      type: 'string',
    },
    {
      name: 'slug',
      title: 'Slug',
      type: 'slug',
      options: {
        source: 'title',
        maxLength: 96,
      },
    },
    {
      name: 'body',
      title: 'Body',
      type: 'array',
      of: [{ type: 'block' }],
    },
  ],
};

Then, ensure this schema is imported into your sanity.config.js or sanity.cli.js file (depending on your project setup) to be registered with the Studio.

// In your-project/sanity.config.js (or sanity.cli.js)
import { defineConfig } from 'sanity';
import { deskTool } from 'sanity/desk';
import { schemaTypes } from './schemas'; // Assuming schemas is a directory with index.js exporting schemaTypes

export default defineConfig({
  name: 'default',
  title: 'My Sanity Project',

  projectId: 'YOUR_PROJECT_ID',
  dataset: 'production',

  plugins: [deskTool()],

  schema: {
    types: schemaTypes,
  },
});

Start the Sanity Studio locally:

sanity start

This will open your Studio at http://localhost:3333 (or another port if 3333 is in use). You can then create new documents based on your defined post schema.

4. Query the Content Lake

Once you’ve created and published some content in the Sanity Studio, you can retrieve it using the API. You'll need your projectId and dataset name (usually production). The example below uses GROQ to fetch all posts.

Example using JavaScript (Node.js or browser)

Install the Sanity client library:

npm install @sanity/client

Then, make a query:

import { createClient } from '@sanity/client';

const client = createClient({
  projectId: 'YOUR_PROJECT_ID',
  dataset: 'production',
  useCdn: true, // `false` if you want to ensure fresh data
  apiVersion: '2023-05-03', // use current date (YYYY-MM-DD)
});

const query = `*[_type == "post"]{_id, title, "slug": slug.current, body}`;

client.fetch(query)
  .then((posts) => {
    console.log('Fetched posts:', posts);
  })
  .catch((error) => {
    console.error('Error fetching posts:', error.message);
  });

Example using a direct HTTP request (cURL)

You can also query the Content Lake directly via HTTP. Replace YOUR_PROJECT_ID and production with your actual values. The apiVersion is required for all API requests to ensure a consistent response from the Content Lake as documented by Sanity.

curl 'https://YOUR_PROJECT_ID.api.sanity.io/v2023-05-03/data/query/production?query=*%5B_type%20%3D%3D%20%22post%22%5D%7B_id%2C%20title%2C%20%22slug%22%3A%20slug.current%2C%20body%7D'

The URL above decodes to https://YOUR_PROJECT_ID.api.sanity.io/v2023-05-03/data/query/production?query=*[_type == "post"]{_id, title, "slug": slug.current, body}. Ensure the query string is URL-encoded when making direct HTTP requests.

Common next steps

Once you have successfully made your first request, consider these common next steps to further develop your Sanity-powered application:

Explore GROQ and GraphQL

Sanity's Content Lake supports two primary query languages: GROQ and GraphQL. GROQ is Sanity's purpose-built query language, optimized for traversing and shaping graph-like data structures. It offers powerful filtering, projection, and aggregation capabilities. GraphQL provides an alternative for developers already familiar with its syntax and ecosystem. You can learn more about GROQ query language fundamentals or how to use the GraphQL API directly within Sanity's documentation.

Customize the Sanity Studio

The Sanity Studio is built with React and is fully customizable. You can extend its functionality by creating custom input components, adding plugins (e.g., for image editing, translation), or even rebuilding parts of the UI to fit specific content workflows. This flexibility allows for a tailored content authoring experience. Explore the Sanity Studio documentation for customization guides.

Integrate with a frontend framework

Sanity is a headless CMS, meaning it focuses solely on content management and delivery, leaving the presentation layer to frontend frameworks. Integrate your Sanity project with popular frameworks like Next.js, React, Vue, Svelte, or others to build your public-facing website or application. You can use client libraries or direct API calls to fetch content into your frontend components. For an example of how a headless CMS like Sanity integrates with frontend experiences, consult general discussions on headless CMS architecture on MDN Web Docs.

Implement authentication and authorization

For applications requiring secure access to content or personalized experiences, implement authentication and authorization. Sanity's API tokens can be used for authenticated access to the Content Lake. For user-facing applications, this typically involves setting up an authentication provider (e.g., Auth0, Firebase Auth, or a custom solution) and then using server-side logic to fetch content with appropriate API permissions.

Set up webhooks

Webhooks allow external services to be notified when changes occur in your Sanity Content Lake. You can configure webhooks to trigger builds on your CI/CD pipeline, invalidate CDN caches, or send notifications. This is crucial for maintaining real-time updates and efficient deployments. Sanity provides detailed webhook configuration options within its project settings.

Troubleshooting the first call

When making your first API call to Sanity, you might encounter issues. Here are common problems and their solutions:

Issue Description Solution
404 Not Found The API endpoint or resource does not exist.
  • Verify your projectId and dataset are correct.
  • Ensure the apiVersion is correctly specified in the URL or client configuration (e.g., v2023-05-03).
  • Check for typos in your query path or document types.
401 Unauthorized The request lacks valid authentication credentials.
  • If accessing private content or performing write operations, ensure you are using a valid API token.
  • Verify the API token has the correct permissions (read, write) for the dataset.
  • Check if the dataset is public or private. Public datasets generally do not require tokens for read.
Empty array [] or no data returned The query executed successfully, but no matching content was found.
  • Confirm content exists in your Sanity Studio and is published.
  • Double-check your GROQ or GraphQL query syntax.
  • Ensure the _type in your query matches the schema definition (e.g., post vs. Post).
  • If useCdn: true, it might be serving stale data. Try useCdn: false for fresh data during development, but be mindful of rate limits.
CORS errors (browser only) Cross-Origin Resource Sharing policy blocking requests from your frontend.
  • Add your frontend's origin (e.g., http://localhost:3000, https://yourdomain.com) to the CORS origins list in your Sanity project settings.
Sanity CLI not recognized The sanity command does not execute.
  • Ensure the Sanity CLI is installed globally: npm install -g @sanity/cli or yarn global add @sanity/cli.
  • Verify your system's PATH environment variable includes npm's global bin directory.