Introduction
In this article, we will explore how to integrate Next.js, a popular React framework, with Sanity CMS to build dynamic and content-rich websites. We’ll leverage the power of Next.js for server-side rendering (SSR) and combine it with Sanity CMS’s flexible content management capabilities.
Prerequisites
Before we begin, make sure you have the following prerequisites in place:
- Node.js and npm installed on your machine.
- A basic understanding of Next.js and React.
- A Sanity CMS account and a project set up.
Table of Content
Through this article I’ll be highlighting seven steps towards achieving our goal for this session with appropriate code snippets.
Step 1: Setting Up the Next.js Project
Step 2: Installing Sanity Client
Step 3: Creating Sanity Schema
Step 4: Fetching Data from Sanity CMS
Step 5: Connecting to Sanity CMS
Step 6: Displaying Dynamic Content
Step 7: Styling the Component
Conclusion
Talk is cheap let’s delve into coding.
Step 1: Setting Up the Next.js Project:
Let’s start by creating a new Next.js project. Open your terminal and run the following commands:
npx create-next-app my-sanity-app
cd my-sanity-app
This will create a new Next.js project named my-sanity-app and the second line of code navigates you into your newly created my-sanity-app directory.
Step 2: Installing Sanity Client:
Next, we need to install the Sanity client package to interact with our Sanity CMS project. Run the following command in your terminal
npm install @sanity/client
Step 3: Creating Sanity Schema
To define the structure of your content, you'll need to create a schema in Sanity CMS. Login to your Sanity CMS dashboard and navigate to your project.
Create a new file named schema.js in the root of your project and define your schema using the Sanity schema language. For example:
// schema.js
export default {
name: 'post',
type: 'document',
title: 'Post',
fields: [
{
name: 'title',
type: 'string',
title: 'Title',
},
{
name: 'content',
type: 'text',
title: 'Content',
},
],
};
This schema defines a post document type with title and content fields.
Step 4: Fetching Data from Sanity CMS:
In your Next.js project, create a new file named pages/index.js. Import the Sanity client and fetch data from Sanity CMS using the following code:
// pages/index.js
import client from '../lib/sanity';
export default function Home({ posts }) {
return (
<div>
<h1>Latest Posts</h1>
<ul>
{posts.map((post) => (
<li key={post._id}>
<h2>{post.title}</h2>
<p>{post.content}</p>
</li>
))}
</ul>
</div>
);
}
export async function getServerSideProps() {
const query = `*[_type == "post"]`;
const posts = await client.fetch(query);
return {
props: {
posts,
},
};
}
This code fetches all the post documents from Sanity CMS and passes them as props to the Home component.
Step 5: Connecting to Sanity CMS:
In your Next.js project, create a new file named lib/sanity.js. Add the following code to establish a connection with Sanity CMS:
// lib/sanity.js
import sanityClient from '@sanity/client';
const client = sanityClient({
projectId: 'your-project-id',
dataset: 'your-dataset',
useCdn: true, // Enable this for production
});
export default client;
Replace 'your-project-id' and 'your-dataset' with your actual Sanity project ID and dataset name.
Step 6: Displaying Dynamic Content:
Now that we have fetched the data from Sanity CMS, let’s update the Home component to display the dynamic content.
// pages/index.js
import client from '../lib/sanity';
export default function Home({ posts }) {
return (
<div>
<h1>Latest Posts</h1>
<ul>
{posts.map((post) => (
<li key={post._id}>
<h2>{post.title}</h2>
<p>{post.content}</p>
</li>
))}
</ul>
</div>
);
}
export async function getServerSideProps() {
const query = `*[_type == "post"]`;
const posts = await client.fetch(query);
return {
props: {
posts,
},
};
}
The posts array received as props is then mapped to render the title and content of each post.
Step 7: Styling the Component:
To make the posts look visually appealing, you can apply some CSS styling. Create a new file named styles/Home.module.css and add the following styles:
/* styles/Home.module.css */
.container {
max-width: 600px;
margin: 0 auto;
padding: 20px;
}
h1 {
font-size: 24px;
margin-bottom: 20px;
}
ul {
list-style-type: none;
padding: 0;
}
li {
margin-bottom: 20px;
}
h2 {
font-size: 20px;
margin-bottom: 10px;
}
p {
font-size: 16px;
}
Conclusion
Congratulations! You have successfully integrated Next.js with Sanity CMS to build a dynamic website. You learned how to fetch data from Sanity CMS using the Sanity client, display the content on your Next.js pages, and style the components for a better user experience.
Feel free to explore more features of Sanity CMS, such as image management, rich text editing, and content relationships, to enhance your website further.
If you also want me to write on any of these topics above comment about it. So I can get on it.
Remember to customize the schema and queries according to your specific requirements, and keep building amazing web experiences with Next.js and Sanity CMS!
References
Next.js Documentation: https://nextjs.org/docs
Sanity CMS Documentation: https://www.sanity.io/docs
That concludes the article on integrating Next.js with Sanity CMS.
Thank you for your time to consume this knowledge. Hit like button and comment if this helps.