Wednesday, June 28, 2023

How to integrate Nextjs project to Sanity with TypeScript

 To integrate a Next.js project with Sanity using TypeScript, you can follow these steps:

Create a new Next.js project with TypeScript by running the following command in your terminal:

npx create-next-app@latest --ts

Install the required packages for integrating Sanity with Next.js:

npm install @sanity/client react-query

Configure Sanity:

Create a new Sanity project or use an existing one. You can sign up for a free account on the Sanity website (https://www.sanity.io/) if you don't have one already.

Set up your Sanity schema and create the necessary data structures for your project.

Create a sanity.ts file in your project's root directory and add the following code:

import { createClient, SanityClient } from '@sanity/client';

const sanityClientOptions = {

  projectId: 'YOUR_PROJECT_ID',

  dataset: 'YOUR_DATASET',

  useCdn: true, // Enable this for production to use the CDN

};

const sanityClient: SanityClient = createClient(sanityClientOptions);


export default sanityClient;

Replace 'YOUR_PROJECT_ID' and 'YOUR_DATASET' with your actual Sanity project ID and dataset name.

Create a utility function to fetch data from Sanity. Create a sanityFetch.ts file in your project's root directory and add the following code:

import sanityClient from './sanity';

export async function fetchSanityData(query: string, params?: Record<string, any>) {

  const response = await sanityClient.fetch(query, params);

  return response;

}

Start building your Next.js pages and components. You can use the fetchSanityData function to fetch data from Sanity and use it in your components.

Here's an example of how you can fetch data from Sanity in a Next.js page:


import { fetchSanityData } from '../path/to/sanityFetch';


export async function getStaticProps() {

  const query = `*[_type == "post"]{title, body}`;


  const data = await fetchSanityData(query);


  return {

    props: {

      posts: data,

    },

  };

}


function Home({ posts }) {

  return (

    <div>

      {posts.map((post) => (

        <div key={post._id}>

          <h2>{post.title}</h2>

          <p>{post.body}</p>

        </div>

      ))}

    </div>

  );

}


export default Home;

This example demonstrates how to fetch a list of posts from Sanity and render them on the homepage. Adjust the query and component code according to your Sanity schema and data structure.

Start your Next.js development server by running the following command in your terminal:

npm run dev

Your Next.js project should now be integrated with Sanity, and you can start fetching and displaying data from Sanity in your Next.js pages and components.

Remember to replace 'YOUR_PROJECT_ID' and 'YOUR_DATASET' with your actual Sanity project ID and dataset name in the sanity.ts file.

Note: Make sure you have the necessary access tokens and permissions set up in your Sanity project to allow API access.

No comments:

Post a Comment

How AI (Artifical Inteligence) is Revolutionizing Grief Support: The Story of Digital Legacies and Memory Preservation

When James Vlahos learned his father was diagnosed with terminal cancer in 2016, he was heartbroken. Living in Oakland, California, James ch...