Integrating Sanity with Next.js


Objectives

Learn how to integrate Sanity with Next.js and how to use Sanity Studio.

Tech Stack

What is Sanity?

Sanity.io is the platform for structured content. With Sanity.io you can manage your text, images, and other media with APIs.

What is Headless CMS?

A headless CMS is a content management system that separates where content is stored (the “body”) from where it is presented (the “head“). Think about headless architecture like this: the main job of a headless CMS is to store and manage your content. It doesn’t really care what you want to do with that content. To learn more on headless CMS, please refer to this article and this article.

CDN v.s. CMS

A CDN is a network of servers that cache data/content, improving load speeds and security. On the other hand, CMS’s are pieces of software that allow users to manage and use their content as needed. A CMS may rely on a CDN to allow its users to access content and data quickly but not vice versa. To learn more on the differences of CDN and CMS, please refer to this article

How Sanity works?

As shown in the figure below, Sanity is a headless CMS. It stores the content in the cloud and provides APIs for developers to access the content. The content can be accessed by any programming languages. In this article, we will use Next.js to access the content.

Integrating with Next.js

Setup a Sanity Project

Follow the setup tutorial to setup your first Sanity project.

Setup Sanity Studio

Run npm run dev to start the Sanity Studio. You should see the following page. However, in your case, there is no content yet.

Create your own schema

In this article, we will create a simple schema to store the information of a pet.

In the index.ts file, add the following code.

After creating the schema, you could head back to the terminal and run npm run dev to restart the Sanity Studio.

Now, you should see the page I shown before. You can now add a new pet. These are the content we will use in the next section.

Check your API mangagement console

In your API management page, you can see the projectID for accessing the content. You should see something like this.

In your Next.js project

Run npm i @sanity/client to install the Sanity client. Then, create a file called index.tsx. In the file, add the following code.

In the code, we first import the Sanity client. Then, we create a client with the projectID we got from the API management page. Then, we query the content from Sanity. In this case, we query the content with type equals to pet. Then, we display the content in the page.

In the browser

Now, you should see the content you created in the Sanity Studio.

Conclusion

In this article, we learned how to use Sanity to create a headless CMS. We also learned how to integrate Sanity with Next.js . It is a 5 minutes setup! It is very easy to use. I hope you enjoy this article. If you have any questions, please leave a comment below.

Resources