DEV Community

Cover image for How To Use Sanity with Next.js 13 full Guide
MedCode
MedCode

Posted on

How To Use Sanity with Next.js 13 full Guide

Sanity is a powerful and flexible content management system (CMS) that allows you to create and manage content for websites, applications, and digital experiences. It provides an easy-to-use interface for content creators, while offering developers a robust set of tools and APIs for building dynamic and customizable content-driven applications.

*Key features of Sanity include:
*

  1. Structured Content: Sanity allows you to define the structure and schema of your content using its powerful content modeling system. You can create custom content types, define fields with specific data types, and establish relationships between content entries.

  2. Real-time Collaboration: Sanity enables real-time collaboration among team members working on content. Multiple users can simultaneously edit and preview content, ensuring efficient collaboration and reducing conflicts.

  3. Headless CMS Architecture: Sanity follows a headless CMS architecture, decoupling the content management and presentation layers. This provides flexibility to use any frontend technology, such as React, Vue.js, or Next.js, to consume and display content
    .

  4. Version Control: Sanity automatically tracks and stores revisions of your content, allowing you to review, compare, and revert to previous versions. Thi

s feature ensures content integrity and provides an audit trail for content changes.

  1. Rich Media Support: Sanity supports the management of various media types, including images, videos, and documents. It provides tools for asset management, transformation, and optimization, ensuring seamless integration of media assets into your conten
    t.

  2. Extensibility: Sanity offers an extensible platform with a wide range of integrations and APIs. You can extend Sanity's functionality by creating custom plugins, using webhooks, or integrating with third-party services
    .

  3. Developer-Friendly: Sanity provides a developer-friendly experience with an open-source JavaScript client, APIs, and tooling. It allows you to customize workflows, create custom input components, and implement complex business logic as nee

Sanity with Next.js, you can follow these steps:

1. Create a new Next.js project:
Set up a new Next.js project by running the following command in your terminal:

npx create-next-app my-app
Enter fullscreen mode Exit fullscreen mode

2. Install the Sanity CLI:

Install the Sanity CLI globally by running the following command:

npm install -g @sanity/cli
Enter fullscreen mode Exit fullscreen mode

3. Set up a new Sanity project:

Run the following command to set up a new Sanity project:

sanity init
Enter fullscreen mode Exit fullscreen mode

Follow the prompts to create a new Sanity project. Choose the default options or configure them according to your needs.
This will create a new Sanity project with a basic schema and configuration

4. Connect Next.js with Sanity:
Inside your Next.js project, install the @sanity/client package and the groqpackage by running:

npm install @sanity/client groq
Enter fullscreen mode Exit fullscreen mode

Create a new file called client.js in your Next.js project and add the following code:

import sanityClient from '@sanity/client';

const client = sanityClient({
  projectId: 'your-project-id',
  dataset: 'your-dataset-name',
  apiVersion: '2021-05-21', // Update to the latest API version
  useCdn: true, // Enable CDN caching
});

export default client;
Enter fullscreen mode Exit fullscreen mode

Replace 'your-project-id' with your Sanity project ID and 'your-dataset-name'
with the name of your dataset.

1. Fetch data from Sanity in Next.js:
Create a new file, such as Home.js, in the pagesdirectory of your Next.js project.
Inside Home.js, import the client object from client.js and use it to fetch data from Sanity. Here's an example:

import client from '../path/to/client.js';

const Home = ({ data }) => {
  return (
    <div>
      <h1>{data.title}</h1>
      <p>{data.description}</p>
    </div>
  );
};

export async function getStaticProps() {
  const query = `*[_type == "homePage"][0] {
    title,
    description
  }`;

  const data = await client.fetch(query);

  return {
    props: {
      data,
    },
  };
}

export default Home;
Enter fullscreen mode Exit fullscreen mode

Customize the query according to your Sanity schema to fetch the desired data.
The getStaticPropsfunction is a Next.js function that allows you to fetch data at build time.

1. Start the Next.js development server:
Run npm run dev or yarn dev in your Next.js project's root directory to start the development server.
Open your browser and navigate to http://localhost:3000 to see your Next.js app with Sanity data.
You can now integrate Sanity with Next.js and start fetching data from your Sanity project. Customize the queries and components to display the desired data in your Next.js application.

Top comments (6)

Collapse
 
iamhectorsosa profile image
Hector Sosa

I completely adore Sanity and this is a killer combo with Next 13! Great post! I'd recommend trying to enable syntax highlighting for your posts and including a couple of screenshots to make sure you keep your readers engaged.

We've built a simple OSS tool to help with screenshots. Take a look at it and let us know what you think. github.com/ekqt/screenshot I'd appreciate giving it a Star on GitHub if you find it helpful! Cheers!

Collapse
 
med_code profile image
MedCode

thank u bro ..

Collapse
 
bkpecho profile image
Bryan King Pecho

This article provides a great starting point for developers looking to leverage the power of Sanity and Next.js together. Keep it up!

Collapse
 
med_code profile image
MedCode

thank u

Collapse
 
sirawichdev profile image
SIRAWICH VOUNGCHUY

lucky us. when you do

sanity init

now in Next 13 (app route) projects it will auto binding sanity project and some configurations for us :)

Collapse
 
jingxiangmo profile image
Jingxiang Mo

Signed up to this website just to say thank you. Very clear and concise tutorial, really appreciate it. Thank you!