Skip to main content

Command Palette

Search for a command to run...

Next.js 14 Meets Sanity: Integrating Next.js 14 with Sanity

Published
10 min read
Next.js 14 Meets Sanity: Integrating Next.js 14 with Sanity
O

I am a Frontend Developer position. With a solid background in web development (3+ years of experience) and a passion for creating exceptional user experiences, I am excited about the opportunity to contribute my skills to your team.

Throughout my career, I have honed my expertise in ensuring that I can craft responsive and visually appealing websites. I am well-versed in modern frontend frameworks and libraries, allowing me to stay at the forefront of industry trends and best practices.

Collaboration is a cornerstone of my work ethic, and I thrive in team environments. I enjoy turning design concepts into functional, user-friendly interfaces and have a keen eye for detail when it comes to optimizing for performance and accessibility.

The Perfect Duo: Next.js 14 Project with Sanity

Before we embark on this journey, let's set the stage with a quick glimpse into Sanity

what is Sanity?

Sanity is like a digital toolbox for creating and managing content on the internet. It's a special toolkit that helps people build and organize websites or apps without having to struggle with complicated technical stuff.

With Sanity, you don't need to be a coding wizard to make changes. It's designed to be friendly, so even if you're not a tech expert, you can easily add new articles, change the layout, or update pictures without feeling lost

Imagine you're creating a blog, and you want it to look and feel just the way you imagine. Sanity is like a set of easy-to-use tools that allows you to decide how your blog should be structured, what it should look like, and how you want your content to be presented

now, let's dive into how to integrate next js 14 with sanity.

Setting up Next.js Project

npx create-next-app@latest

If you're stepping into the world of Next.js and find yourself in need of a comprehensive guide on how to install it, I've got you covered. Check out my detailed walkthrough on Next.js installation at my other blog: Next.js Installation Guide.

It's the perfect starting point for newcomers, providing clear and step-by-step instructions to help you seamlessly set up Next.js for your projects. Dive in and let's make your journey into Next.js a smooth and enjoyable one!

let's proceed

In this tutorial, we're building a Job Info website with TypeScript. The twist? All the important data comes straight from a Sanity backend. Join me for a swift journey into creating a seamless job board! 🚀

Run this command in your project folder to set up Sanity within your existing Next.js project. It'll handle all the needed setup behind the scenes, making sure Sanity integrates smoothly with your Next.js project. Easy peasy!

$ npm -y create sanity@latest

Note : Before you run the command, make sure to have a Sanity account. If you already have one, just log in and then go ahead to create a new project. Simple as that!

When you run npm -y create sanity@latest, you'll be prompted with some questions. Just say "yes" to all of them. Easy peasy!

sanity project configuration

After the installation, keep an eye out for a new folder named "sanity." To access the studio, simply go to "/studio" (the default path), but feel free to change it later in the "sanity.config.ts" file according to your liking. Navigate to your app directory, and voila, you'll spot the shiny new "/studio" path.

Now, here's the cool part – your project is not only visible in your Sanity account but also on Sanity’s website. To be extra sure, match the "project_id" in your ".env" file with the one in your Sanity account.

And don't miss the pre-set schema.ts file! It's like a blank canvas where you can define all your content structures

Setting up the schemas

in the sanity folder, create a schemas folder. in this tutorial, we will display a single type which is a job list.
create a simple file job.ts inside the schemas folder and define the fields.

//schemas/job.ts/
const job = {
    name: "job",
    title: "Job",
    type: "document",
    fields: [
      {
        name: "name",
        title: "Company Name",
        type: "string",
        description: "What is the name of the company?"

        },
      {
        name: "jobTitle",
        title: "Job Title",
        type: "string",
        description: "Enter the job title. E.g: Software Developer",
      },
      {
        name: "logo",
        title: "Company Logo",
        type: "image",
      },
      {
        name: "url",
        title: "Company Website",
        type: "url",
      },
      {
        name: "description",
        title: "Job Description",
        type: "text",
        rows: 3,
        description: "Write a brief description about this role",
      },
      {
        name: "startDate",
        title: "Start Date",
        type: "date",
      },
      {
        name: "endDate",
        title: "End Date",
        type: "date",
      },
    ],
  };

  export default job;

The provided code contains seven distinct sections/fields

Now, go to the "schema.ts" file inside the "sanity" folder. In there, bring in the schemas you made. For instance, if you created a file named "donaldTrumpSuck.ts," that's the one you'll be importing.

in my case, i will be importing job.ts

import { type SchemaTypeDefinition } from 'sanity'
import job from './schemas/job'
export const schema: { types: SchemaTypeDefinition[] } = {
  types: [job],
}
  • Add your imported schema types inside the types array.

  • navigate to your project directory

  • Run your app with following command:

npm run dev
  • Now, type /studio at the end of your website address in the browser

  • Be sure to log in to your Sanity account.

  • If it's your first visit, it might request you to add CORS origin to your Sanity project.

  • Once you've done that, your handy Sanity studio will be live, and your Job List type will be all set up for you to explore

The studio updates itself automatically...Cool right?

Next, Proceed to define the schema for the Job document within the Sanity Studio interface.

Feel free to add as many Jobs as needed for the Job document in the Sanity Studio

When you publish a document in Sanity Studio, it means you are making the content officially visible and accessible on your website or application. The act of publishing essentially takes the content from a draft or preview state to a live state, making it available for public consumption.

Publishing a document in Sanity Studio transforms it from a behind-the-scenes draft to a live and visible piece of content on your website or app. It's the moment when your carefully crafted work officially goes public for everyone to see.

When you return after two days to edit and publish a document in Sanity Studio, it's like stepping back into your content workshop with a fresh perspective. You can refine, update, or add new information to ensure your document stays current and relevant. After making your edits, hitting the publish button is akin to unveiling the latest version of your creation, making it live for your audience to see. It's a simple yet powerful way to keep your content dynamic and up-to-date over time....

Super cool right??
This is a significant and effortless performance boost that Sanity brings to the table.

Fetching data from the Studio

Given our use of TypeScript, let's kick things off by establishing types for the data we'll retrieve from Sanity. To house these essential data types, craft a file named jobType.ts at the root of your project. This file will serve as the home for all the data structures we'll be fetching.

Pro tip: This is the perfect spot to neatly organize and consolidate your TypeScript types, ensuring a seamless integration with Sanity data throughout your project.

Organizing your types in a clear and maintainable folder structure is crucial for the scalability and readability of your Next.js projects. Here's a recommended folder structure for types in a Next.js project.

src/
|-- types/
|   |-- common.ts
|   |-- jobTypes.ts
|   |-- userTypes.ts
|-- components/
|-- pages/
|-- styles/
|-- ...

In our project, I've created specific types that perfectly match the details we use to describe job information. here is the type below:

export type JobType = {
    _id: string;
    name: string;
    jobTitle: string;
    logo: string;
    url: string;
    description: string;
    startDate: Date;
    endDate: Date;
  };

Next, we can move on to querying the data

Query data using GROQ

Querying data using GROQ is like asking your database for specific information. Imagine you have a massive library of books, and you want to find all books written by a certain author. GROQ is the language that helps you communicate this request to the library system. It's a way to say, "Hey, database, give me exactly what I'm looking for." So, querying with GROQ is your tool to sift through data and get just the information you need, much like asking a librarian for the perfect book on a specific shelf.

inside our sanity folder, create a file called sanity.query.ts
Paste this code :

import {client} from "./lib/client"
import { groq } from 'next-sanity'
export async function getJob() {
    return client.fetch(
      groq`*[_type == "job"]{
        _id,
        name,
        jobTitle,
        "logo": logo.asset->url,
        url,
        description,
        startDate,
        endDate,
      }`
    );
  }

the imported client is gotten from the lib frolder in our sanity folder

Now, let's display the data on our Frontend

For this tutorial, instead of creating a separate job.tsx file in the components folder and importing it into the home page, we'll streamline the process. I'll guide you through making direct changes to your home page component. This way, we keep things straightforward and focused on the task at hand. Let's dive into enhancing your home page together!

paste the following code to your home page:

//app/page.tsx/
import Image from 'next/image'
import { getJob } from "../../sanity/sanity.query"
import { JobType } from '@/type'
import Link from "next/link"
export default async function Home() {
  const job : JobType[] = await getJob()

  return (
    <>
    <section className="mt-20">
      <div className="mb-16">
        <h2 className="font-semibold text-[2rem] mb-4 text-center">Work Experience </h2>
      </div>

      <div className="flex flex-col gap-y-3  items-center ">
      {job.map((data) => (
  <div key={data._id} className="flex flex-col lg:flex-row items-start gap-x-4 max-w-[700px] w-[100%] border p-4 rounded-md hover:shadow-lg transition duration-300 ease-in-out transform hover:scale-105">
    <Link
      href={data.url}
      rel="noreferrer noopener"
      className="min-h-[60px] max-w-[60px] w-[100%] rounded-md "
    >
      <Image
        src={data.logo}
        className="object-cover w-full h-full rounded-md"
        alt={`${data.name} logo`}
        width={100}
        height={100}
      />
    </Link>
    <div className="flex flex-col items-start mt-4 lg:mt-0">
      <h3 className="text-xl font-bold mb-2">{data.name}</h3>
      <p className="text-gray-600">{data.jobTitle}</p>
      <div className="flex items-center mt-2">
        <span className="text-gray-500 text-sm">
          {data.startDate.toString()} - {data.endDate.toString()}
        </span>
        <div className="h-2 w-2 bg-gray-500 rounded-full mx-2"></div>

      </div>
      <p className="text-base text-gray-700 mt-4">{data.description}</p>
    </div>
  </div>
))}


      </div>
    </section>
    </>
  )
}

feel free to make changes to the above styles

Here's the resulting output:

Our application is now complete, showcasing the seamless integration of Next.js with embedded Sanity CMS 🚀🚀🚀

  • Installation:

    • Installed Sanity.io CLI and created a new project.
  • Studio Setup:

    • Configured the Sanity Studio, defining schemas for data.
  • Data Creation:

    • Populated the Sanity Studio with job-related content.
  • Next.js Integration:

    • Embedded Sanity CMS into a Next.js project.
  • Type Definitions:

    • Defined TypeScript types for structured data.
  • Data Display:

Displayed job data on the Next.js home page.

In conclusion, we've embarked on a journey from setting up Sanity to witnessing the harmonious fusion of Next.js and Sanity CMS in action. It's not just about building an application; it's about crafting a dynamic, user-friendly experience that effortlessly blends the power of Next.js with the versatile content management capabilities of Sanity. As we wrap up this adventure, remember: the synergy of these technologies opens a world of possibilities for creating compelling, efficient, and delightful web applications. Now, armed with this newfound knowledge, go forth and create digital wonders! 🚀✨

They call me Kingsley, the Lonely/Weird Frontend web developer🚀.

With a solid background in web development (3+ years of experience) and a passion for creating exceptional user experiences, I am excited about the opportunity to contribute my skills to your team.

Throughout my career, I have honed my expertise in ensuring that I can craft responsive and visually appealing websites. I am well-versed in modern frontend frameworks and libraries, allowing me to stay at the forefront of industry trends and best practices.

Collaboration is a cornerstone of my work ethic, and I thrive in team environments. I enjoy turning design concepts into functional, user-friendly interfaces and have a keen eye for detail when it comes to optimizing for performance and accessibility.

I am committed to delivering high-quality code and meeting project deadlines. My adaptability, problem-solving abilities, and dedication to continuous learning make me a valuable asset in fast-paced development environments.

I would welcome the opportunity to discuss how my skills and experience align with your company's goals and how I can contribute to the success of your projects.

In the big world of making websites, I'm Kingsley—the kinda quirky, but really into it, frontend developer. While figuring out how to use Sanity and mix it up with Next.js, my solo coding sessions got a cool vibe.

Being a "lonely" coder isn't about feeling alone; it's about having fun with code. In this digital world, doing my own thing turned into a way to be super creative. So here's to all the weird and solo coders out there—finding joy in playing with code and pixels. Embrace the quirks because, in web development, being a bit weird is awesome, and the loneliest lines of code can create the coolest stuff. 🌐💻

If you find yourself eager to explore further, have specific questions, or seek additional guidance on Integrating Next.js with Sanity.io, I'm here to help! Feel free to drop your queries in the comments section or reach out through Github, Linkedin, Twitter. Feel free to follow me on any of these platforms.. or you can email me on okezekingsley18@gmail.com . Your curiosity and engagement contribute to the collaborative spirit of the web development community, and I'm excited to be part of your journey. Happy coding!