Published on Sunday, December 29, 2024
Setting Up Next.js with Sanity
Posted by

Video Tutorial
Prerequisites
Before you begin, ensure the following requirements are met:
- Sanity Account: You have an active account on Sanity.io.
- Sanity Project: A Sanity project is already set up and configured.
Step 1: Create a Next.js Project
Run the following command to create a new Next.js project:
npx create-next-app@latest sanity-next-app
Step 2: Install Dependencies
Add the Sanity client to your project:
npm install @sanity/client
You're all set to interact with your Sanity backend!
Step 3: Add Environment Variables
Create a .env.local file and add your Sanity credentials:
NEXT_PUBLIC_SANITY_PROJECT_ID=your-project-id
NEXT_PUBLIC_SANITY_DATASET=your-dataset-name
Replace your-project-id and your-dataset-name with the corresponding values from your Sanity project.
Step 4: Setup Sanity Client
Create a lib/sanity/index.ts file in the src directory of your project:
import { createClient } from '@sanity/client'
export const sanityClient = createClient({
projectId: process.env.NEXT_PUBLIC_SANITY_PROJECT_ID!,
dataset: process.env.NEXT_PUBLIC_SANITY_DATASET!,
useCdn: true, // Use the CDN for faster read operations
apiVersion: '2023-01-01', // Set your API version
})
Step 5: Fetch Data From Sanity
Fetch posts from Sanity using a GROQ query:
import { sanityClient } from '../sanity';
type Post = {
slug: string;
title: string;
}
export default async function Home() {
const query = `*[_type == "post"]{ title, slug }`;
const posts = await sanityClient.fetch<Post[]>(query);
return (
<main>
<h1>Posts</h1>
<ul>
{posts.map((post) => (
<li key={post.slug}>{post.title}</li>
))}
</ul>
</main>
);
}
We assume you have a post schema set up in your Sanity app. If not, adjust the query and fields according to your schema.
Step 6: Test Your Application
Start the development server:
npm run dev
Conclusion
You’ve successfully set up a Next.js app with Sanity! With the @sanity/client package, you can easily fetch and display dynamic content from Sanity while maintaining complete control over your app’s structure and design.