Next JS Sanity Starter: Code Examples Galore

published on 06 December 2023

Most website owners would agree that showcasing code examples effectively is critical, yet often challenging.

Luckily, the Next JS Sanity Starter makes presenting code snippets incredibly simple, while enabling rich content capabilities.

Dive into this extensive collection of live code samples demonstrating the versatility and ease-of-use of the Next JS Sanity Starter for rapidly building feature-rich sites.

Introduction to the Next JS Sanity Starter

The Next JS Sanity Starter is a robust boilerplate that integrates the headless CMS Sanity with Next.js framework. This powerful combination allows developers to build blazing-fast, SEO-friendly web applications with React and manage content easily through Sanity.

Some key benefits of using the Next JS Sanity Starter include:

  • Accelerated Development: The starter code has Next.js best practices built-in already like server-side rendering and optimized images. You can focus on creating features instead of project setup.

  • Powerful Content Management: Sanity CMS provides intuitive, customizable authoring tools for editors. And content is accessed through a GraphQL API for endless flexibility.

  • Stellar Performance: Get lightning fast page loads leveraging Next.js Incremental Static Regeneration and Sanity's real-time content preview.

  • SEO Ready: Dynamic pages are pre-rendered so content is immediately indexable by search engines. And editable metadata improves discoverability.

  • Responsive Design: The starter includes responsive UI layouts optimized for desktop, tablet and mobile. Customize styles or bring your own.

With just a few keystrokes, developers can initialize a new project equipped with these capabilities to start cranking out features and content for a production-ready web app. Let's explore some code examples of implementing and customizing the Next JS Sanity Starter.

Getting Started with Your Sanity Next JS Example

Integrating Sanity as a backend CMS with Next.js offers developers a robust fullstack solution to build dynamic JAMstack applications. By combing Sanity's flexible content models and powerful querying with Next.js' server-side rendering and routing, you can rapidly develop sites that are scalable, secure, and SEO-friendly.

In this section, we'll walk through the key steps to get up and running with a Next Sanity starter template.

Installing required packages with next-sanity npm

To integrate Sanity into an existing or new Next.js project, you'll need to install some essential NPM packages:

npm install next react react-dom @sanity/client @sanity/image-url

This includes:

  • next - The core Next.js library
  • react - React library
  • react-dom - Enables React to interact with the DOM
  • @sanity/client - Sanity SDK for querying content
  • @sanity/image-url - Helper for generating Sanity image URLs

In addition, you may want to install next-sanity which includes preset configurations for Sanity and Next.js:

npm install -D @next-sanity/css @next-sanity/preset

This will configure Babel, ESLint, PostCSS etc. with Next and Sanity defaults.

Configuring environment variables for Sanity io starters

It's best practice to manage your Sanity project IDs, datasets, and API tokens using environment variables rather than hardcoding them.

Add a .env.local file to your Next.js project and set variables like:

NEXT_PUBLIC_SANITY_PROJECT_ID=abc123 
NEXT_PUBLIC_SANITY_DATASET=production
SANITY_API_TOKEN=sk123YOUR_TOKEN

You can then reference these in your application using process.env.NEXT_PUBLIC_SANITY_PROJECT_ID for example.

Having them set as NEXT_PUBLIC_ variables means they'll be accessible from browser code. Other variables like the API token should be kept private.

Structuring the folder architecture for a Next sanity template

A typical structure for a Next + Sanity application could be:

/pages
  _app.js
  _document.js
  index.js
  about.js
  blog.js
  blog/[slug].js

/components
  layout.js
  header.js 
  footer.js
  post.js
  post-preview.js  

/lib
  sanity.js

/studio
  // Sanity Studio files  

package.json
.env.local

Key points:

  • /pages - Next.js page routes
  • /components - Reusable React components
  • /lib - Shared utility functions like sanity.js helper
  • /studio - Sanity Studio with schema types

This setup separates concerns across a clean, modular architecture making it easy to navigate and maintain code.

By leveraging Sanity as a headless CMS with Next.js handling the frontend, you can build complex apps rapidly with a small footprint. Configuring the integration is straightforward when following these guidelines.

Designing Pages and Components with Next-Sanity

The Next JS Sanity Starter provides a robust foundation for building dynamic websites and web applications with reusable page templates, customizable components, and managed content models.

Creating dynamic page templates with Sanity

The starter includes conventions for designing page templates that can be reused across multiple pages. For example, you can define a BaseLayout component with shared header and footer elements, then extend it into PageLayout templates for blog posts, products, docs pages, etc. Pages can then render the appropriate template based on their content type.

Some key benefits of this pattern:

  • Consistent layouts and branding across all site pages
  • Reduce code duplication - change one template to update multiple pages
  • Customize partials like headers/footers across templates
  • Dynamic page titles, meta tags, OpenGraph from Sanity document

Here is an example page template:

// PageLayout.js
import BaseLayout from 'components/BaseLayout';

export default function PageLayout({title, children}) {

  return (
    <BaseLayout>
      <Head>
        <title>{title}</title>
      </Head>
      
      <h1>{title}</h1>
        
      {children}
    
    </BaseLayout>
  );
}

And here is how to use it in pages:

// page.js

import PageLayout from 'components/PageLayout';

export default function Page({data}) {
   return (
     <PageLayout title={data.title}>
       <ArticleBody content={data.content} />
     </PageLayout>
   )
}

export async function getStaticProps() {
  // Fetch data from Sanity
 }

This approach streamlines page development by eliminating repetitive code. It also allows global header/footer updates by editing a single BaseLayout component.

Displaying Sanity content with live examples

The Next JS Sanity Starter makes it simple to query content from Sanity and display it in your pages and components with React.

Some key ways to render Sanity data:

  • Use getStaticProps to fetch content at build time
  • Call usePreviewSubscription for realtime preview updates
  • Display images via urlFor() helper
  • Render Portable Text markup

For example:

// Page.js
import {urlFor} from 'lib/api'

export default function Page({data}) {
  const {title, coverImage, body} = data;

  return (
    <article>
      <h1>{title}</h1>
      <img src={urlFor(coverImage)} />

      <PortableText blocks={body} />
    </article>
  )
}

// Helper to fetch data
export async function getStaticProps() {
  // Get data from Sanity
}

This handles querying data from Sanity CMS and outputting it using React - no need to learn custom templating languages!

The starter also includes live preview support out of the box, so content editors can view changes in realtime.

Handling menus and navigation via Sanity schemas

Managing menus and navigation links is critical for structured content sites. The Next-Sanity starter allows you to customize menus directly in Sanity Studio.

Some strategies for managing menus with schemas:

  • Define reusable Menu and Link schema types
  • Create singleton doc to manage Menu instances
  • Reference Menu docs from site Header component
  • Menu links populate Navigation component

Sample menu schema:

// schema/menu.js
export default {
  name: 'menu',
  type: 'document',

  fields: [
    {
      name: 'title',
      type: 'string',
      title: 'Title',
    },
    {
      name: 'items',
      type: 'array',
      title: 'Menu Items',
      of: [{type: 'link'}]
    },
  ]
}

This allows editors to manage navigation links in Sanity Studio UI. The data can then be queried from any page or component to populate navigation and menus.

Enhancing User Experience with Advanced Next-Sanity Features

The Next JS Sanity Starter provides unique capabilities to create immersive digital experiences. By connecting the Sanity CMS backend to a Next.js frontend, developers can build editable websites with real-time previews and instant cache invalidation.

Integrating the Sanity Studio into your Next JS project

The Next JS Sanity Starter makes it easy to embed the Sanity Studio directly into your Next.js application. This allows content editors to update content intuitively within the website UI, instead of a separate dashboard.

Here is an example of integrating the Studio editor using the getStaticProps API in Next.js:

export const getStaticProps = async () => {

  return {
    props: {
      preview: true,
      projectId: process.env.SANITY_PROJECT_ID, 
      dataset: process.env.SANITY_DATASET 
    }
  }
}

Then in your page template, you can render the editor conditionally:

import { PortableText } from '@portabletext/react'
import { usePreviewSubscription } from '../lib/sanity'

export default function Page({data}) {

  const {data: previewData} = usePreviewSubscription(data?.query, {
    params: data.queryParams,
    initialData: data.pageData
  })

  return (
    <Layout>
      {previewData && (
        <PortableText blocks={previewData.pageData.body} />
      )}
    </Layout>
  ) 
}

This allows editors to update content in real-time, without ever leaving the page.

Leveraging Next-sanity/preview for real-time content updates

The next-sanity/preview component facilitates seamless previews of drafted content before publishing. This empowers editors to preview changes, ensuring content accuracy:

import {Preview} from 'next-sanity/preview'

export default function Page({preview, content}) {

  return (
    <Preview enabled={preview}> 
      <Component {...content} />
    </Preview>
  )
}

Now content teams can preview changes before they go live. This prevents publishing incomplete or inaccurate content.

Optimizing performance with instant cache invalidation

The Next Sanity Starter automatically invalidates cached requests when content changes. This means updated content gets served instantly without requiring a manual cache reset.

It works by wrapping requests with the sanityCache helper:

export async function getStaticProps() {

  const query = groq`*[_type=="page" && slug.current == $slug][0]{..., "comments": *[_type=="comment" && references(^._id)]}`

  const pageData = await sanityCache(query, {slug: home})

  return { 
    props: {
      data: pageData
    }
  }
}

Now cached requests will automatically update on any content changes related to that query. This optimizes performance by serving fresh data instantly.

The Next JS Sanity Starter simplifies building real-time editable websites with built-in previews, intuitive editing, and automatic cache invalidation. These advanced capabilities create seamless workflows for both developers and content creators.

sbb-itb-5683811

Deploying and Scaling with Vercel Sanity Integration

The Next JS Sanity Starter makes it easy to launch and scale your Next-Sanity applications leveraging Vercel's integration and global infrastructure.

Serverless deployment with Vercel for Next-Sanity apps

Vercel provides optimized serverless deployment for Next.js applications through its edge network. By handling complex infrastructure and routing logic, Vercel allows developers to focus on rapidly building their Next-Sanity apps.

Some key benefits of using Vercel for Next-Sanity projects include:

  • Effortless Scaling: Vercel automatically scales to demand levels without any configuration. It can handle traffic spikes seamlessly due to its serverless architecture.

  • Optimized Performance: Vercel leverages various performance optimizations like automatic compression, component caching, and more out-of-the-box for Next.js apps. This results in lightning-fast end user experiences.

  • Streamlined Workflows: Developers can connect their GitHub repositories to instantly deploy changes made to Next-Sanity projects. This automates the build and deploy process.

  • Global Deployment: Vercel nodes are positioned close to users across the world. It routes traffic in optimal paths resulting in reduced latency.

  • Previews: Vercel Previews provide shareable URLs for testing changes before they are deployed. It's helpful for reviews across teams.

Implementing atomic deploys with next-sanity GitHub CI/CD

The Next Sanity Starter makes continuous integration and delivery simpler by integrating with GitHub Actions workflows.

When developers push code changes to GitHub repos, you can trigger automated builds for Sanity content APIs and Next.js web apps. This enables atomic deployments when content schemas or site source code are updated.

Configuring custom build steps and deploy tasks with GitHub Actions provides flexibility. Some examples include:

  • Run unit and integration tests before deployment
  • Build and deploy Sanity API independently from web app
  • Push built artifacts to various environments e.g. staging, production
  • Run checks before promoting across environments
  • Rollback in case of failures

By implementing atomic deploys using GitHub CI/CD pipelines, teams streamline development workflows safely.

Configuring custom domains for your Sanity-powered sites

Mapping your own custom domain names to Next-Sanity apps deployed on Vercel is straightforward.

There are two approaches:

1. Domain Configuration through Vercel

Vercel provides an intuitive user interface to connect domains purchased from registrars like GoDaddy, Namecheap etc. It automatically provisions SSL certificates and handles renewals.

After linking domains in Vercel and deploying projects, clients will seamlessly reach your site on the custom domains.

2. Domain Delegation to Vercel Name Servers

For greater control and DNS flexibility, domains can be delegated to Vercel's name servers david.ns.cloudflare.com & ellen.ns.cloudflare.com. This handles all DNS resolution and traffic routing automatically.

The second approach prevents relying on external DNS providers. Delegating domains directly allows Vercel to optimize routing based on geo location and other factors.

With custom domains set up, Next-Sanity sites can be uniquely branded while building trust and credibility with visitors. Teams also get more flexibility over site structure changes in the future.

Adding Sanity to an Existing Nextjs Project

Integrating Sanity into an existing Next.js project unlocks robust content management capabilities. The next-sanity npm package streamlines adding Sanity's real-time preview, optimized image CDN, and flexible schemas to turbocharge your Jamstack application.

Let's walk through a code example for integrating Sanity into an existing Next.js and Vercel site.

Prerequisites

To follow along, you will need:

Make sure your Next.js project is deployed on Vercel and your Sanity project has sample schema types and documents created.

Install the next-sanity Package

First, install the next-sanity npm package:

npm install next-sanity

Or with Yarn:

yarn add next-sanity

This will handle integrating the Sanity preview, image CDN, and other APIs with Next.js.

Configure Environment Variables

Next, add your Sanity project ID and dataset name as environment variables in Vercel.

In your Vercel project, navigate to Settings > Environment Variables and add:

SANITY_PROJECT_ID = yourProjectId
SANITY_DATASET = yourDatasetName

This connects your Sanity data with your Next.js frontend.

Import and Initialize the Sanity Client

Inside _app.js, import createClient from next-sanity:

import { createClient } from "next-sanity"; 

export default function App({ Component, pageProps }) {

  const client = createClient({
    projectId: process.env.SANITY_PROJECT_ID,
    dataset: process.env.SANITY_DATASET,
    apiVersion: "2021-10-21",
  });

  return <Component {...pageProps} />
}

This initializes the Sanity client with your project credentials.

Use the Sanity Client in Your Components

You can now query Sanity data from any page or component:

export default function Page({posts}) {

  return (
    <div>
      {posts.map(post => (
        <article>
          <h1>{post.title}</h1>
          {post.body}
        </article>
      ))}
    </div>
  ) 
}

export async function getStaticProps() {

  const posts = await client.fetch(`*[_type=="post"]`);

  return {
    props: {
      posts
    }
  }

}

The client handles preview mode, optimized images, and all other Sanity features out of the box!

Conclusion

By following these steps to add next-sanity to your Next.js project, you unlock a fully-featured headless CMS. The client handles preview mode, CDN image optimizations, real-time data, and more to supercharge your Jamstack application.

What other Sanity integrations would you like to see code examples for? Let me know in the comments!

Next Steps in the Next-Sanity Journey

Bookmark these references and recommendations to continue mastering Next Sanity development.

Exploring the Next-Sanity documentation hub

Expanded guides, API references, and videos on the Next Sanity site provide a wealth of information to level up your skills.

The documentation covers everything from basic setup to advanced configuration of Next. Integrating Sanity opens up additional CMS possibilities like:

  • Managing content with customizable data models
  • Implementing real-time content previews
  • Optimizing content for search engines

Having these CMS capabilities built-in streamlines launching full-stack Jamstack apps.

Browse through the different sections like Next.js fundamentals, data fetching, styling, routing, and more. With each area comes annotated code snippets you can repurpose. For example, here is how to get a Sanity preview working locally:

export const getStaticProps = async ({ params, preview = false }) => {

  if (preview) {
    return getClient(preview)
      .fetch(query)
  }

  return getClient()
    .fetch(query)  
}

export default YourPage

Notice the ternary operator to toggle between preview and production Sanity clients. This gives complete control over content visibility.

Engaging with the Next-Sanity community on GitHub and forums

Beyond static documentation lies a vibrant ecosystem of developers building Next Sanity solutions. Connecting with them can uncover new techniques and troubleshoot blockers.

  • GitHub - All Next.js and Sanity repositories offer issue trackers to ask usage questions and propose enhancements. Review others' comments to find fixes for common problems.

  • Discussions - For open-ended conversations, head to the community forums. Share your app architectures and gather feedback through casual back-and-forth.

  • Twitter - Many principal developers are active tweeters. Send them a message or watch their feeds to stay updated.

Seeing code in action often solidifies concepts faster than reading alone. Here are some great video resources:

  • Next.js Conf - The latest production features and architectural principles discussed by core maintainers.

  • Level Up Tutorials - Beginner-friendly introduction to combining Next, Sanity, and Vercel.

  • Sanity.io - Webinar demonstrating CMS workflows for managing content at scale.

The visual medium helps internalize capabilities like Image Optimization, Incremental Static Regeneration, and Real-time Data Syncing.

Revisiting these videos periodically uncovers optimization opportunities as projects grow. They also preview what advanced integrations may become possible between Next and Sanity.

Wrapping Up: Unleashing the Power of Next JS and Sanity

The next-js-strapi-starter-a-developers-quickstart-guide/">Next JS Sanity starter is a robust and flexible foundation for building scalable web applications with structured content. By integrating the simplicity of Sanity's headless CMS with the performance and SEO optimization of Next.js, developers can create feature-rich sites quickly and efficiently.

Throughout this post, we explored some of the key benefits of using the Next JS Sanity starter, including:

  • Streamlined content modeling with Sanity's intuitive UI
  • Real-time previews and collaboration for managing content
  • Built-in support for incremental static regeneration in Next.js
  • SEO enhancements like automatic sitemaps and metadata optimization
  • Flexible theming and customization with Tailwind CSS
  • Scalable deployment on Vercel's edge network

With code examples for core features like preview mode, image optimization, dynamic routing, and more, it's clear this starter equips developers with a versatile foundation for sites big and small.

Whether you're building a blog, e-commerce store, or SaaS app, the Next JS Sanity starter makes it simple to manage content and focus on creating incredible user experiences. Deploy to Vercel in minutes and unleash the true potential of these powerful Jamstack technologies.

So dive in, customize the theme, model your content, and bring your Next JS visions to life today! This starter has all the ingredients for your next hit web application.

Related posts

Read more

Built on Unicorn Platform