Sanity Next.js Headless CMS Solution Explained

Author

Reads 594

Close Up of Chart on Board
Credit: pexels.com, Close Up of Chart on Board

Sanity Next.js is a powerful headless CMS solution that's gaining popularity among developers. It's built on top of Next.js, a popular React-based framework for building server-rendered and statically generated websites.

Sanity Next.js allows you to separate presentation and content, making it easier to manage and update your website's content independently of its design and layout. This is a key benefit of using a headless CMS approach.

With Sanity Next.js, you can create a content layer that's decoupled from your presentation layer, giving you more flexibility and scalability. This is particularly useful for large-scale applications where content and presentation need to be managed separately.

Sanity Next.js provides a robust API for managing content, making it easier to integrate with other services and tools.

Recommended read: Nextjs Wordpress

Getting Started

To get started with Sanity Next.js, you'll need to install the Sanity CLI globally. This can be done with the command `npm install -g @sanity/cli`. Once installed, you can create a new project using the Sanity CLI by running `sanity init`. You'll be prompted to select a project template, and for this example, we'll choose "Clean project with no predefined schemas".

Discover more: Install Next Js

Credit: youtube.com, Sanity Crash Course: Learn The Basics in 20 Minutes!

To set up your Sanity Studio, you'll need to run the command `sanity studio` and then visit `localhost:3333` in your browser. You'll be prompted to sign in with your Sanity account, which you can create if you don't already have one.

To configure your project, you'll need to select a login provider and authenticate your account. Once completed, you can configure your project with options such as API version and use of a CDN.

Here are the options you'll need to set for your Sanity Studio:

  • apiVersion: The version of the Sanity API you're using. For the latest API version, use your current date in this format YYYY-MM-DD.
  • useCdn is used to disable edge cases

Once you've completed these steps, you can start your Sanity project by running `npm run dev` and visiting `localhost:3333` in your browser.

Understanding Sanity

Sanity CMS is a headless CMS, which decouples the content authoring backend from the presentation layer or client.

It exposes stored content as data over an API for consumption on different platforms such as websites, mobile applications, and the Internet of Things.

Broaden your view: Next Js Headless Cms

Credit: youtube.com, Sanity Crash Course: Learn The Basics in 20 Minutes!

Sanity CMS takes a structured approach to content authoring, providing a concise number of features.

Its image pipeline allows for efficient management of images, while Portable Text streamlines text management.

Sanity Studio is a fully functional, customizable, and extendable editor built with React, making it a powerful tool for content creation.

Check this out: Nextjs Global State

Creating Schemas

Creating Schemas is a crucial step in building a portfolio site with Sanity Next.js. You'll need to create three schema files: profile, project, and work. These files will define the structure of your data, including personal information, projects, and work experience.

Sanity comes with its own built-in schema types, including number, datetime, image, array, object, string, url, and more. You can check out the full list of schema types in Sanity's documentation.

To create a schema, you'll need to declare a type for the schema, which requires specific properties depending on the schema type. For example, the document type requires a name, title, and input field. The input field is a property that lets you declare the kind of input to expect, and you'll be using the string type input field.

Credit: youtube.com, Sanity export, import documents (tables) create schemas with Typescript and connect Sanity to NextJs

Here are the most common schema types you'll encounter when working with Sanity.io:

  • Object: Defines reusable and nested fields for complex data relationships.
  • String: Represents plain text content.
  • Number: Stores numerical values.
  • Boolean: Represents true or false values.
  • Array: Creates lists or arrays of other schema types.
  • Reference: Establishes relationships between documents.
  • Image: Specifically designed for storing images.
  • Date: Stores date and time values.

In your schema file, you'll need to import and use the schemas you create. This is where all the schemas will be imported and used. You can read the comments provided in the file to get a better understanding of what's going on.

For example, you can create a file called firstSchema.js in the schemas folder and declare a type for the schema. This will allow you to define the kind of input to expect and create a new content schema.

For more insights, see: File Upload Next Js Supabase

Working with Data

To fetch data from Sanity CMS in Next.js, you can use the @sanity/client package, which allows you to interface with Sanity.io from Next.js. This package needs to be installed in the Next.js app with the command `npm install @sanity/client`.

To fetch data from Sanity.io, you need to create a client object and feed it an object of configuration properties, which should be stored and accessed as environmental variables. This is done by creating a new file `sanity.js` in the `lib` folder.

Credit: youtube.com, Content Platforms Explained in 100 Seconds // Build your own with Sanity

Once you have the client object, you can use it to fetch data with Graph-Relational Object Queries (GROQ), Sanity's open source query language. GROQ is designed to query collections of largely schema-less JSON documents, allowing you to describe exactly what information you need from your schema and return only specific elements from your data.

Here are the types you need to define for the data coming from the studio:

  • Profile type: This includes fields like fullName, headline, profileImage, and so on.
  • PortableTextBlock: A unique type coming from Sanity that properly defines the data type for the rich text editor.

You can define these types in a `types/index.ts` file in the root directory, making it easier to visualize the data you're expecting in your studio.

Create the Component

To create the component, you'll need to create a file in the app directory. Create a studio/[[...index]]/page.tsx file.

Inside this file, you'll need to import NextStudio from the next-sanity library. This is the library that will allow you to mount the Sanity studio into your Next.js application.

You'll also need to import the configuration file from sanity.config.ts. This file was created earlier in the process.

If this caught your attention, see: Nextjs Server Actions File Upload

Credit: youtube.com, React Data table Tutorial - Learn to create Data tables in React JS from scratch

To complete this setup, paste the code from the example into the component. This code imports the necessary libraries and sets up the studio route.

Once you've completed this step, run npm run dev and visit localhost:3000/studio. You'll be prompted to add localhost:3000 as a CORS origin to your Sanity project.

Recommended read: Nextjs Code Block

Headless CMS Benefits

Working with Data is a complex task that requires careful consideration of various factors, including content management.

A headless CMS is a great solution for this, as it allows for a decoupled approach to content management.

Headless CMS dutifully embodies this decoupled approach, and one of its key benefits is flexibility in content delivery.

This flexibility is achieved through the ability to serve content to any device or platform, without being tied to a specific CMS interface.

By decoupling content from the presentation layer, developers can focus on building a seamless user experience.

This approach also enables faster development and deployment of content, which is a major advantage in today's fast-paced digital landscape.

Additional reading: Headless Woocommerce Nextjs

Fetch Data with GROQ

Credit: youtube.com, GROQ in 2 - Two ways to view query results

To fetch data from Sanity CMS in Next.js, you'll need to use the @sanity/client package, which allows you to interface with Sanity.io from Next.js. This package is installed with the command `npm install @sanity/client`.

Inside your Next.js project, create a new lib folder with a new file sanity.js, where you'll store the client configuration. You'll need to feed the client an object of configuration properties, which should be stored and accessed as environmental variables.

To fetch data with @sanity/client through getStaticProps with Graph-Relational Object Queries (GROQ), Sanity's open source query language, you'll need to append the following code to your pages/index.js file:

```javascript

import sanityClient from '../lib/sanity.js';

export async function getStaticProps() {

const client = sanityClient();

const data = await client.fetch(`*[_type == "profile"] | order(order asc) { fullName, headline, profileImage }`);

return {

props: {

data,

},

};

}

```

This code uses the client configuration to fetch data from Sanity CMS using a GROQ query. The query returns an array of documents with the specified schema type, ordered by a specific field.

Curious to learn more? Check out: Next Js Debug

Credit: youtube.com, Displaying JSON Data from Sanity to Astro.js using GROQ Queries #6.

By using GROQ, you can describe exactly what information you need from your schema, filter certain data, and return only specific elements from your data. This allows for more efficient and flexible data retrieval.

Here's a summary of the GROQ query syntax:

  • `*[_type == "profile"]` returns all documents with the schema type "profile"
  • `| order(order asc)` orders the results by the "order" field in ascending order
  • `{ fullName, headline, profileImage }` returns only the specified fields from the documents

By mastering GROQ, you can unlock the full potential of your Sanity CMS and Next.js project.

Trigger Hook via Webhooks

To set up webhooks for Sanity Studio updates, you'll need to visit sanity.io/manage and pick your project.

Navigate to the API section and click on the "Create webhook" button.

Fill in the form with the hook's details, including a name, description, URL, dataset, and trigger settings.

Leave filter and projection inputs blank so the hook applies to all documents.

Here's a breakdown of the required fields:

  • Name: A descriptive name for the hook, such as "Portfolio Deployment".
  • Description: A brief explanation of the hook's purpose, like "Trigger rebuild when portfolio content is created, updated, and deleted".
  • URL: Paste the URL endpoint generated by Vercel.
  • Dataset: The dataset to apply the hook to.
  • Trigger on: Check the "create", "update", and "delete" boxes.

Save the hook and visit your hosted studio to update any document. Once you click publish, this should trigger the deploy hook and update your site when completed.

Recommended read: How to Update Nextjs

Optimizing and Enhancing

Credit: youtube.com, Powering Morning Brew's Transformation: How Sanity, Vercel, and Next.js optimize content

Optimizing and Enhancing your Sanity Next.js experience is crucial for a seamless content creation process. You can enhance your Sanity Studio with image thumbnails in SanityPress, improving UX and helping editors quickly create content.

With optimized list previews in Sanity Studio, you can create better visual cues for a more intuitive CMS experience. This can significantly improve content editor workflow and productivity.

What is io?

Sanity.io is a unified content platform that lets you store and manage content for a website or application.

Unlike traditional CMS like WordPress or Wix, Sanity.io stores your content but lets you decide how you want that content to be displayed.

Sanity.io seamlessly integrates with Next.js, a popular React framework used to improve SEO performance by rendering React applications server-side.

Next.js is a great choice for leveraging Sanity.io's capabilities, and it's widely used by developers to build fast and efficient applications.

Sanity.io gives you the flexibility to show your content on different web and mobile applications, making it a versatile solution for content management.

Related reading: Nextjs Socketio

Enhance UX with Schema Thumbnails

Credit: youtube.com, Optimizing AI Thumbnail Generation: Enhancing Media Tools for Content Creators

You can improve the user experience in Sanity Studio with image thumbnails in SanityPress. This feature helps editors quickly create content.

Image thumbnails can make a big difference in the editor's workflow. They provide a visual cue for what the content will look like, making it easier to create and manage.

By enhancing the Studio UX with schema thumbnails, you can optimize the content editor workflow and productivity. This is especially true for list previews, which can be improved to provide better visual cues for a more intuitive CMS experience.

To get started, you'll need to create a separate layout for the studio component. This involves moving files around and creating a new layout file.

SEO Plugin

The Sanity Seo Plugin is a game-changer for simplifying SEO fields for various content types.

It's designed to make the process of generating SEO fields a breeze, saving you time and effort.

This plugin is a must-have for anyone looking to optimize their content and improve search engine rankings.

The Sanity Seo Plugin is specifically designed for various types of content, making it a versatile tool for any content creator or editor.

By using this plugin, you can easily generate SEO fields for your content, making it more discoverable and accessible to your target audience.

Broaden your view: Seo Nextjs

Deployment and Updates

Credit: youtube.com, Personal Website Tutorial with Next.js 13, Sanity.io, TailwindCSS, and TypeScript

After successfully deploying your site, visit the studio route, and you should get a prompt to add the URL to the CORS setting in Sanity.

To see your studio, simply click "continue" and follow the on-screen instructions to do so.

If you're building a large-scale application, a better option for live updates is using Incremental Static Regeneration (ISR), which is an alternative to setting up live updates in your Sanity/Next.js app.

Having to trigger the deployment server each time can be a cumbersome task, especially when building for a client.

To manually deploy your site whenever a change is made to your studio, use Sanity GROQ-powered Web Hooks to trigger a deployment on Vercel.

For more insights, see: Nextjs Generating Static Pages

Deployment

Deployment can be a straightforward process if you know the right steps. To deploy your site, visit the studio route; your-site-name/studio, and follow the on-screen instructions to set up CORS settings in Sanity.

You'll get a prompt to add the URL to the CORS setting in Sanity. Simply click "continue" and follow the instructions.

Consider reading: Next Js Cors

Credit: youtube.com, Deployment Strategies in DevOps | Blue Green Deployment | Canary Deployment | Rolling Updates

After successfully deploying your site, you should be able to see your studio. There's also an alternative to setting up live updates: using Incremental Static Regeneration (ISR) for large-scale applications.

Setting up live updates can be cumbersome, especially when building for a client. Updates made to your site would be triggered only on build time, requiring a manual deployment on Vercel to see changes.

To avoid this, you can manually deploy your site using Sanity GROQ-powered Web Hooks. This will allow you to trigger a deployment whenever a change is made to your studio.

Discover more: Nextjs Usecontext

Setup Webhooks for Updates

Updates made to your site would be triggered only on build time, so you'd have to manually trigger a deployment on Vercel to see the changes.

Sanity Studio is Sanity's open source single-page app for managing your data and operations, where you can create, delete, and update your data within Sanity.

To manually deploy your site whenever a change is made to your studio, you'll need to setup Sanity GROQ-powered Web Hooks.

See what others are reading: Nextjs App Route Get Ssr Data

Credit: youtube.com, How to Set Up Webhooks for Monitoring Real-Time Updates

Visit sanity.io/manage, pick your project, navigate to the API section and click on the "Create webhook" button.

Fill in the form with information about the hook you want to create, including the hook name, description, URL, dataset, and trigger on create, update, and delete boxes.

Here's what you'll need to fill in the form:

Leave filter and projection inputs blank so the hook will be applied to all documents, and for the rest of the fields, leave it as is and hit save.

Once you've saved the hook, visit your hosted studio and update any document, and the deploy hook should trigger and update your site when completed.

Frequently Asked Questions

What is sanity used for?

Sanity is a tool for managing and editing text, images, and other media through APIs and a customizable editing environment. It helps users organize and structure their content with ease.

Is sanity free to use?

Yes, Sanity offers a free tier with basic features. However, for more advanced features and support, you'll need to upgrade to a paid plan starting at $99/month.

Gilbert Deckow

Senior Writer

Gilbert Deckow is a seasoned writer with a knack for breaking down complex technical topics into engaging and accessible content. With a focus on the ever-evolving world of cloud computing, Gilbert has established himself as a go-to expert on Azure Storage Options and related topics. Gilbert's writing style is characterized by clarity, precision, and a dash of humor, making even the most intricate concepts feel approachable and enjoyable to read.

Love What You Read? Stay Updated!

Join our community for insights, tips, and more.