Back to Blog
Next.jsSanity CMSNext.js+SanityWeb DevelopementTutorial

How to Set Up Next.js with Sanity CMS: A Beginner's Complete Guide

January 4, 2026

How to Set Up Next.js with Sanity CMS: A Beginner's Complete Guide

Everything you need to install, configure, and connect before writing your first line of code

Who Is This Guide For?

If you've heard about Next.js and Sanity but feel overwhelmed by where to start, this guide is for you. We won't build a complete project here—instead, we'll focus on getting your development environment ready so you can confidently start coding.

By the end, you'll have:

  • A working Next.js project
  • Sanity CMS installed and connected
  • Your content studio accessible in the browser
  • Everything linked and talking to each other

Think of this as the foundation. Once this is solid, building blogs, portfolios, or any content-driven site becomes much easier.

What You'll Need Before Starting

Let's make sure your computer is ready.

1. Node.js (version 18.17 or higher)

Node.js runs JavaScript outside the browser. Both Next.js and Sanity need it.

Check if you have it:

bash
node --version

If you see something like v18.17.0 or higher, you're good. If not, download it from nodejs.org. Pick the LTS (Long Term Support) version—it's more stable.

2. A Code Editor

You can use any editor, but VS Code is popular for good reasons:

  • Free and lightweight
  • Great extensions for React and Sanity
  • Built-in terminal

Download it from code.visualstudio.com if you don't have it.

Helpful VS Code extensions to install:

  • ES7+ React/Redux/React-Native snippets
  • Sanity.io (adds syntax highlighting for GROQ queries)
  • Tailwind CSS IntelliSense (if you'll use Tailwind)

3. A Sanity Account

Sanity is free to start. You'll create an account during setup, but you can also sign up beforehand at sanity.io.

4. Basic Terminal Knowledge

You don't need to be a command line expert. Just know how to:

  • Open a terminal (Command Prompt, PowerShell, or Terminal app)
  • Navigate folders using cd folder-name
  • Run commands by typing them and pressing Enter

Step 1: Create Your Next.js Project

Open your terminal and navigate to where you keep your projects. Then run:

bash
npx create-next-app@latest my-first-sanity-project

You'll see several questions. Here's what to choose and why:

✔ Would you like to use TypeScript? → Yes

TypeScript catches errors before they break your site. Sanity works beautifully with it.

✔ Would you like to use ESLint? → Yes

ESLint points out code problems. Helpful for beginners learning best practices.

✔ Would you like to use Tailwind CSS? → Yes (recommended) or No

Tailwind makes styling faster. Not required, but pairs well with this stack.

✔ Would you like your code inside a `src/` directory? → Yes

Keeps your project organized. Your main code lives in src/, config files stay in root.

✔ Would you like to use App Router? (recommended) → Yes

The App Router is Next.js's modern routing system. All new tutorials use it.

✔ Would you like to use Turbopack for next dev? → No

Turbopack is still experimental. Stick with the stable option for now.

✔ Would you like to customize the import alias? → No

The default @/* alias works perfectly. It lets you write @/components instead of ../../../components.

After answering, wait for installation to complete. Then enter your project:

bash
cd my-first-sanity-project

Quick test—make sure Next.js works:

bash
npm run dev

Open http://localhost:3000 in your browser. You should see the Next.js welcome page. Press Ctrl + C in terminal to stop the server.

Step 2: Install Sanity in Your Project

Here's where the magic happens. Sanity has a CLI (Command Line Interface) that sets up everything for you.

Run this command inside your project folder:

bash
npx sanity@latest init

The CLI will guide you through setup. Let me walk you through each prompt:

Prompt 1: Login or Create Account

? Login type
❯ Sign in with your Sanity account
Create a new Sanity account

If you have an account, sign in. Otherwise, create one. A browser window will open for authentication.

Prompt 2: Create or Select a Project

? Select project to use
❯ Create new project
existing-project-1
existing-project-2

Choose Create new project for fresh starts.

Prompt 3: Name Your Project

? Your project name: my-first-sanity-project

Use something descriptive. This appears in your Sanity dashboard.

Prompt 4: Dataset Configuration

? Use the default dataset configuration? Yes

Say Yes. This creates a "production" dataset where your content lives. You can add more datasets later (like "staging" for testing).

Prompt 5: Add Configuration Files

? Would you like to add configuration files for a Sanity project in this Next.js folder? Yes

Important: Say Yes! This creates the files needed to connect Next.js with Sanity.

Prompt 6: TypeScript

? Do you want to use TypeScript? Yes

Since we chose TypeScript for Next.js, keep it consistent.

Prompt 7: Embedded Studio

? Would you like an embedded Sanity Studio? Yes

Say Yes. This lets you access Sanity Studio at a route like /studio instead of hosting it separately. Super convenient during development.

Prompt 8: Studio Route

? What route do you want to use for the Studio? /studio

The default /studio works great. Your CMS will be at localhost:3000/studio.

Prompt 9: Project Template

? Select project template to use
❯ Clean project with no predefined schema types
Blog (schema)
E-commerce (schema + sample data)

Choose Clean project with no predefined schema types. Starting from scratch teaches you more than using templates.

Prompt 10: Environment Variables

? Would you like to add the project ID and dataset to your .env file? Yes

Say Yes. This creates a .env.local file with your credentials—essential for connecting to Sanity.

Step 3: Understand What Just Happened

After installation, several new files appeared in your project. Let's understand each one:

New Folders and Files

markdown
my-first-sanity-project/
├── src/
│ ├── app/
│ │ └── studio/
│ │ └── [[...tool]]/
│ │ └── page.tsx ← Makes /studio route work
│ └── sanity/
│ ├── env.ts ← Reads environment variables
│ ├── lib/
│ │ └── client.ts ← Connects to Sanity's API
│ └── schemaTypes/
│ └── index.ts ← Your content models go here
├── sanity.config.ts ← Studio configuration
├── sanity.cli.ts ← CLI configuration
└── .env.local ← Your secret credentials

The Important Files Explained

.env.local — Contains your project credentials:

NEXT_PUBLIC_SANITY_PROJECT_ID="abc123xyz"
NEXT_PUBLIC_SANITY_DATASET="production"

Never share this file publicly. It's already in .gitignore so Git won't track it.

src/sanity/lib/client.ts — The connection to Sanity:

typescript
import { createClient } from 'next-sanity'
import { apiVersion, dataset, projectId } from '../env'
export const client = createClient({
projectId,
dataset,
apiVersion,
useCdn: true,
})

This "client" is what you'll use to fetch content. Think of it as a phone line to your Sanity database.

src/sanity/schemaTypes/index.ts — Where you define content structure:

typescript
import { type SchemaTypeDefinition } from 'sanity'
export const schema: { types: SchemaTypeDefinition[] } = {
types: [],
}

Right now it's empty. You'll add "schemas" here to define what your content looks like (blog posts, products, pages, etc.).

sanity.config.ts — Studio settings:

typescript
import { defineConfig } from 'sanity'
import { structureTool } from 'sanity/structure'
import { schema } from './src/sanity/schemaTypes'
export default defineConfig({
projectId: process.env.NEXT_PUBLIC_SANITY_PROJECT_ID!,
dataset: process.env.NEXT_PUBLIC_SANITY_DATASET!,
schema,
plugins: [structureTool()],
})

This tells Sanity Studio how to behave—which project to connect to, what schemas to use, which plugins to load.

Step 4: Test That Everything Works

Let's verify the connection is working.

Start the Development Server

bash
npm run dev

Check Next.js

Open http://localhost:3000 — you should see the Next.js welcome page.

Check Sanity Studio

Open http://localhost:3000/studio — you should see Sanity Studio loading.

The first time, you might need to log in again. Once authenticated, you'll see an empty studio (because we have no schemas yet). That's expected!

If you see the Sanity Studio interface, congratulations—your setup is complete!

Step 5: Create Your First Schema (Quick Test)

Let's add a simple schema to confirm everything is connected properly.

Create a new file at src/sanity/schemaTypes/post.ts:

typescript
import { defineType, defineField } from 'sanity'
export const postType = defineType({
name: 'post',
title: 'Blog Post',
type: 'document',
fields: [
defineField({
name: 'title',
title: 'Title',
type: 'string',
}),
defineField({
name: 'content',
title: 'Content',
type: 'text',
}),
],
})

Now register it in src/sanity/schemaTypes/index.ts:

typescript
import { type SchemaTypeDefinition } from 'sanity'
import { postType } from './post'
export const schema: { types: SchemaTypeDefinition[] } = {
types: [postType],
}

Restart your dev server (Ctrl + C, then npm run dev) and go back to http://localhost:3000/studio.

You should now see "Blog Post" in the sidebar! Click it, create a test post, and hit Publish.

Step 6: Fetch Your Content in Next.js

Let's make sure Next.js can read what you just created in Sanity.

Create a simple test page at src/app/test/page.tsx:

typescript
import { client } from '@/sanity/lib/client'
export default async function TestPage() {
// This query fetches all posts
const posts = await client.fetch(`*[_type == "post"]`)
return (
<div style={{ padding: '2rem' }}>
<h1>Posts from Sanity</h1>
{posts.length === 0 ? (
<p>No posts yet. Create one in the studio!</p>
) : (
<ul>
{posts.map((post: any) => (
<li key={post._id}>
<strong>{post.title}</strong>
<p>{post.content}</p>
</li>
))}
</ul>
)}
</div>
)
}

Visit http://localhost:3000/test — you should see the post you created!

If you see your content, everything is connected and working perfectly.

Common Setup Issues and Fixes

"Module not found" errors

Run npm install again. Sometimes packages don't install completely.

Studio shows blank screen

Check browser console for errors. Usually it's a missing environment variable. Make sure .env.local has both NEXT_PUBLIC_SANITY_PROJECT_ID and NEXT_PUBLIC_SANITY_DATASET.

"Unauthorized" errors when fetching

Your dataset might be private. Go to sanity.io/manage, select your project, click "API" in settings, and check if your dataset is public. For testing, you can make it public. For production, you'll want to use tokens.

Changes not showing up

If you edit content in Sanity but don't see changes on your site, you might be hitting a cached version. During development, you can disable caching by changing useCdn: true to useCdn: false in your client configuration.

Port 3000 already in use

Another app is using that port. Either close it, or run Next.js on a different port:

bash
npm run dev -- -p 3001

Quick Reference: Useful Commands

Keep these handy as you build:

Command What it does

npm run dev Start development server

npx sanity@latest Access Sanity CLI commands

npx sanity docs Open Sanity documentation

npx sanity manage Open project settings in browser

npx sanity schema extract Extract schema for type generation

npx sanity typegen generate Generate TypeScript types

What's Next?

Your development environment is ready! Here's what to explore:

Learn GROQ — Sanity's query language for fetching exactly the data you need. It's like SQL but for JSON.

Build more schemas — Define content types for your project (authors, categories, pages, etc.)

Add TypeScript types — Run npx sanity typegen generate for autocomplete and error checking.

Set up image handling — Install @sanity/image-url for optimized images.

Build your pages — Now that data flows between Sanity and Next.js, start building!

Recap: What We Did

Let's review everything:

✅ Installed Node.js (the engine that runs everything)

✅ Created a Next.js project (our frontend framework)

✅ Initialized Sanity (our content management system)

✅ Connected them via environment variables and the Sanity client

✅ Tested the connection by creating and fetching content

You now have a solid foundation. The hard part—getting everything installed and connected—is done. From here, you're building features, not fighting configuration.

Your Setup Checklist

Before moving on, confirm:

  • [ ] npm run dev starts without errors
  • [ ] localhost:3000 shows Next.js
  • [ ] localhost:3000/studio shows Sanity Studio
  • [ ] You can create content in the studio
  • [ ] Your Next.js pages can fetch that content

All boxes checked? You're ready to build something amazing.

Got stuck during setup? Drop a comment below with the error message—I'll help you troubleshoot.