---
# System prepended metadata

title: 'Sanity: A Lite Introduction'

---

# Sanity: A Lite Introduction
**Sanity is an open-source API-based CMS built with React.js**

[Sanity](https://www.sanity.io) is a headless CMS, this concept we have a content management system that separates where content is stored (the “body”) from where it is presented (the “head“). It separates information and presentation. This enables content reuse and remixing across web, mobile, and digital media platforms as needed. Sanity provider to user a studio panel to manager the database and provides a API can be use in cross-platform.

Sanity enviroments

* [Studio](https://www.sanity.io/studio) the visual CMS
* [Content lake](https://www.sanity.io/docs/datastore), structured content to integrate across organizations and disciplines, assembling your infrastructure from the best components (database).
* [APIs](https://www.sanity.io/developer-experience) to connect external APIs

In this article, I will demonstrate how I used Sanity Studio and [NextJS](https://nextjs.org/) to connect my project using [Jamstack](https://jamstack.org/) approaches.

👉  To create a new project, run the following command line:
```bash
npm create sanity@latest -- --template clean --create-project "Sanity Project" --dataset production
```

The first step is to create a new document inside the schema folder. I created a `pageSchemas` to use in the content pages (e.g. content used in navigation). For example, we can create a schema object like an image. This object type is not used in navigation, but can be inserted in the `pageSchemas`. This concept will become clearer as we proceed with this article.

![](https://i.imgur.com/xBP0trR.png)

The `article` schema has been created with only one field, `title`, in `article.tsx`.

```javascript=
export default {
  name: 'article',
  type: 'document',
  title: 'Article',
  fields: [
    {
      name: 'title',
      type: 'string',
      title: 'Title',
    },
  ],
}
```

**Field structure**

* **name**: 'article' tells the studio to add "_type": "article" to the JSON when creating a new document in the studio.
* **type**: "document" is added to the document when creating a new one in the studio.
* **title**: 'Article' defines the name of this document type in the studio UI.
* **fields**: This array contains objects that describe the available fields for this document type. Each object includes `name`, `type`, and `title` keys. The keys have the same names as the document type. Inside the fields array, there is a JavaScript object with three keys.

Regarding the type field, in the example provided, it is set to string. This informs the Studio to render a single text input. Sanity provides several default types such as `number`, `datetime`, `image`, `array`, and `object`. Additionally, it is possible to create new types or utilize types provided by [plugins](https://www.sanity.io/plugins). Another important `type` is `reference`, referencing other documents, which we will discuss further in this article.

In the file `schemas/pageSchemas/index.ts`, we define the schemas for the content pages using Sanity's schema definition language. The `pageSchemas` folder contains individual schema files for each content page. For example, a page.ts file defines the schema for the content page.

```javascript=
import Article from './articles'

export const pageSchemaTypes = [Article]
```

In the file `schemas/index.ts`, we export all the schemas defined in the `pageSchemas` folder using the `createSchema` function provided by Sanity. This allows us to use the schemas to define the structure of the content in our CMS.
```javascript=
import {pageSchemaTypes} from './pageSchemas'

export const schemaTypes = [...pageSchemaTypes]
```


👉 Run command line on terminal:

```bash!
npm run start
```

Now the magic happens in `http://localhost:3333`, the initial screen

![](https://i.imgur.com/qPIAODI.png)

This is the initial screen of the project. In the sidebar, you can see the available content types, which currently only includes `Article`. When you click on the content name, a new list of created articles is displayed. In the last screen, you can see the "Hello world" article in the content create/edit tab.

The content manager has common options found in other CMS, such as version control, the ability to view modifications, and saving content in draft format.

For the NextJS part, I used Codesandbox, which can be accessed through the following link: https://codesandbox.io/p/github/cristoferespindola/hello-sanity-and-next/master


I started the project with the initial structure provided by Next.js, which includes several default directories and files.
![](https://i.imgur.com/FSuSWTx.png)
In the pages directory, there is an `index.tsx` file, which serves as the entry point for the home page of the application.

```javascript=
import React from "react";

import { createClient } from "next-sanity";
const client = createClient({
  projectId: "vjmznsrb",
  dataset: "production",
  apiVersion: "2022-03-25",
  useCdn: false,
});

export default function IndexPage({ articles }) {
  return (
    <>
      <header>
        <h1>Sanity + Next.js</h1>
      </header>
      <main>
        <h2>Articles</h2>
        {articles.length > 0 && (
          <ul>
            {articles.map((article) => (
              <li key={article._id}>{article?.title}</li>
            ))}
          </ul>
        )}
        {!articles.length > 0 && <p>No articles to show</p>}
        {articles.length > 0 && (
          <div>
            <pre>{JSON.stringify(articles, null, 2)}</pre>
          </div>
        )}
        {!articles.length > 0 && (
          <div>
            <div>¯\_(ツ)_/¯</div>
            <p>
              Your data will show up here when you've configured everything
              correctly
            </p>
          </div>
        )}
      </main>
    </>
  );
}

export async function getStaticProps() {
  const articles = await client.fetch(`*[_type == "article"]`);

  return {
    props: {
      articles,
    },
  };
}
```

To connect the Sanity content lake with Next.js, we use the `next-sanity` package along with the `createClient` function.

The `createClient` function is used to initialize a new client instance for connecting to the Sanity content lake. This function takes an object as its argument, which contains information about the Sanity project and its configuration, such as the `projectId` and `dataset` name.

Once the client has been initialized, it can be used to fetch data from Sanity and render it on the Next.js application.

```javascript=
import { createClient } from "next-sanity";
const client = createClient({
  projectId: "vjmznsrb",
  dataset: "production", 
  apiVersion: "2022-03-25",
  useCdn: false,
});
```

The `createClient` function takes an object with configuration properties that are used to initialize a new client instance for connecting to the Sanity content lake. The properties required by this function are as follows:

* **projectId**: This is the unique identifier for your project that contains all your users, datasets, and other settings. It’s not a secret, as it’s part of the URL for your content APIs. You can find the `projectId` in the `sanity.json` file located in the root of your Sanity project.
* **dataset**: This is a collection of documents within a project. You can have multiple datasets (for example, staging and production). You can find the `dataset` name in the `sanity.json` file located in the root of your Sanity project.
* **apiVersion**: This is the version of the Sanity API that you want to use. You can usually set this to today's date (in `YYYY-MM-DD` format) to get the newest version of the query API.
* **useCdn**: If you set this to `true`, the client will fetch content from the Sanity cache delivery network. In this case, however, we want updates to be instantly available, so set this to `false`.

![](https://i.imgur.com/hcSLL8K.png)
*projectId is visible on https://www.sanity.io/manage/personal/project*

Inside the `getStaticProps`, line 132, you can see that we’re using a method on the client called fetch(). We’re passing a simple string as its first argument, and the string is a [GROQ](https://www.sanity.io/docs/query-cheat-sheet) query that filters ([]) all (*) your documents down to those with pet as the value for _type. If this query works, it will return an array of documents as objects. Like the one you just removed.

