### Start Development Servers Source: https://github.com/serge-0v/next-js-sanity-starter/blob/master/README.md This command starts the development servers for both the Next.js application and the Sanity Studio, allowing you to view your changes locally. ```bash pnpm dev ``` -------------------------------- ### Import Sample Data to Sanity Source: https://github.com/serge-0v/next-js-sanity-starter/blob/master/README.md This command imports sample data into your Sanity project's 'production' dataset. It's useful for getting started quickly with pre-defined content. The --replace flag will overwrite existing data. ```bash npx sanity dataset import sample-data.tar.gz production --replace ``` -------------------------------- ### Initialize Next.js Sanity Starter with Sanity CLI Source: https://github.com/serge-0v/next-js-sanity-starter/blob/master/README.md This command initializes the Next.js Sanity Starter template using the Sanity CLI. It sets up a new Sanity project, configures API tokens and CORS, installs dependencies, and clones the repository. ```bash npm create sanity@latest -- --template serge-0v/next-js-sanity-starter ``` -------------------------------- ### Set Up Environment Variables for Sanity and Services (Bash) Source: https://context7.com/serge-0v/next-js-sanity-starter/llms.txt Configures essential environment variables for local development, including Sanity CMS connection details, site configuration, and API keys for third-party services like Resend. ```bash # .env.local NEXT_PUBLIC_SITE_URL=http://localhost:3000 NEXT_PUBLIC_SITE_ENV=development RESEND_API_KEY=re_xxxxxxxxxxxx RESEND_AUDIENCE_ID=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx # Sanity CMS Configuration NEXT_PUBLIC_SANITY_API_VERSION=2024-10-31 NEXT_PUBLIC_SANITY_PROJECT_ID=your-project-id NEXT_PUBLIC_SANITY_DATASET=production SANITY_API_READ_TOKEN=skxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ``` -------------------------------- ### Manage Project with Sanity CLI Commands (Bash) Source: https://context7.com/serge-0v/next-js-sanity-starter/llms.txt Provides essential command-line interface commands for initializing the project, running the development server, importing data, generating TypeScript types, building for production, and performing type checking. ```bash # Initialize template with Sanity CLI npm create sanity@latest -- --template serge-0v/next-js-sanity-starter # Run development server pnpm dev # Import sample data npx sanity dataset import sample-data.tar.gz production --replace # Generate TypeScript types from Sanity schema npx sanity schema extract # Creates schema.json npx sanity typegen generate # Creates sanity.types.ts # Build for production pnpm build # Type checking pnpm typecheck ``` -------------------------------- ### Fetch Data from Sanity with Live Preview Source: https://context7.com/serge-0v/next-js-sanity-starter/llms.txt Provides typed helper functions to fetch pages, posts, navigation, and settings from Sanity. These functions integrate with the live preview mechanism, ensuring real-time updates in the application. They utilize the configured Sanity client and GROQ queries for data retrieval. ```typescript // sanity/lib/fetch.ts import { sanityFetch } from "@/sanity/lib/live"; import { PAGE_QUERY, PAGES_SLUGS_QUERY } from "@/sanity/queries/page"; import { POST_QUERY, POSTS_QUERY } from "@/sanity/queries/post"; // Fetch a single page by slug export const fetchSanityPageBySlug = async ({ slug }: { slug: string }) => { const { data } = await sanityFetch({ query: PAGE_QUERY, params: { slug }, }); return data; }; // Fetch all posts export const fetchSanityPosts = async () => { const { data } = await sanityFetch({ query: POSTS_QUERY, }); return data; }; // Fetch a single post by slug export const fetchSanityPostBySlug = async ({ slug }: { slug: string }) => { const { data } = await sanityFetch({ query: POST_QUERY, params: { slug }, }); return data; }; // Usage in Next.js page component // app/(main)/[slug]/page.tsx export default async function Page({ params }: { params: Promise<{ slug: string }> }) { const { slug } = await params; const page = await fetchSanityPageBySlug({ slug }); if (!page) { notFound(); } return ; } ``` -------------------------------- ### Configure Sanity Client for Next.js Source: https://context7.com/serge-0v/next-js-sanity-starter/llms.txt Sets up the Sanity client for fetching content and enables live preview functionality within a Next.js application. It requires project ID, dataset, and API version, and configures the studio URL for stega integration. ```typescript // sanity/lib/client.ts import { createClient } from "next-sanity"; export const client = createClient({ projectId: "your-project-id", dataset: "production", apiVersion: "2024-10-31", useCdn: false, perspective: "published", stega: { studioUrl: process.env.NEXT_PUBLIC_SITE_URL + "/studio", }, }); // sanity/lib/live.ts - Enable live previews import { defineLive } from "next-sanity/live"; import { client } from "./client"; import { token } from "./token"; export const { sanityFetch, SanityLive } = defineLive({ client, serverToken: token, browserToken: token, }); ``` -------------------------------- ### Configure Sanity Studio with TypeScript Source: https://context7.com/serge-0v/next-js-sanity-starter/llms.txt Sets up the Sanity Studio environment, enabling structure and presentation tools for visual editing. It configures custom document actions for singleton types and integrates essential plugins like `@sanity/vision` and `@sanity/code-input`. Dependencies include `sanity`, `sanity/structure`, `sanity/presentation`, `@sanity/vision`, and `@sanity/code-input`. ```typescript // sanity.config.ts import { defineConfig } from "sanity"; import { structureTool } from "sanity/structure"; import { presentationTool } from "sanity/presentation"; import { visionTool } from "@sanity/vision"; import { codeInput } from "@sanity/code-input"; import { schema } from "./sanity/schema"; import { resolve } from "@/sanity/presentation/resolve"; import { structure } from "./sanity/structure"; const singletonActions = new Set(["publish", "discardChanges", "restore", "unpublish"]); const singletonTypes = new Set(["settings"]); export default defineConfig({ basePath: "/studio", title: "Schema UI", projectId: process.env.NEXT_PUBLIC_SANITY_PROJECT_ID!, dataset: process.env.NEXT_PUBLIC_SANITY_DATASET!, schema: { types: schema.types, templates: (templates) => templates.filter(({ schemaType }) => !singletonTypes.has(schemaType)), }, document: { actions: (input, context) => singletonTypes.has(context.schemaType) ? input.filter(({ action }) => action && singletonActions.has(action)) : input, }, plugins: [ structureTool({ structure }), presentationTool({ previewUrl: { draftMode: { enable: "/api/draft-mode/enable" }, }, resolve, }), visionTool({ defaultApiVersion: "2024-10-31" }), codeInput(), ], }); ``` -------------------------------- ### Configure Sanity Presentation Tool URL Resolver (TypeScript) Source: https://context7.com/serge-0v/next-js-sanity-starter/llms.txt Defines how Sanity's Presentation Tool resolves URLs for visual editing. It maps document types like 'post' to specific routes and sets up main document routing for the application. ```typescript // sanity/presentation/resolve.ts import { defineLocations, defineDocuments, PresentationPluginOptions, } from "sanity/presentation"; export const resolve: PresentationPluginOptions["resolve"] = { locations: { post: defineLocations({ select: { title: "title", slug: "slug.current", }, resolve: (doc) => ({ locations: [ { title: doc?.title || "Untitled", href: `/blog/${doc?.slug}`, }, { title: "Blog", href: `/blog` }, ], }), }), }, mainDocuments: defineDocuments([ { route: "/", filter: "_type == 'page' && slug.current == 'index'", }, { route: "/:slug", filter: "_type == 'page' && slug.current == $slug", }, { route: "/blog/:slug", filter: "_type == 'post' && slug.current == $slug", }, ]), }; ``` -------------------------------- ### Generate SEO Metadata with TypeScript Source: https://context7.com/serge-0v/next-js-sanity-starter/llms.txt Creates SEO metadata for pages and posts, including Open Graph images and indexing controls. It utilizes the `urlFor` utility for image optimization and dynamically sets canonical URLs and robots directives based on environment and page settings. Dependencies include `@sanity/image-url` and Sanity types. ```typescript // sanity/lib/metadata.ts import { urlFor } from "@/sanity/lib/image"; import { PAGE_QUERYResult, POST_QUERYResult } from "@/sanity.types"; const isProduction = process.env.NEXT_PUBLIC_SITE_ENV === "production"; export function generatePageMetadata({ page, slug, }: { page: PAGE_QUERYResult | POST_QUERYResult; slug: string; }) { return { title: page?.meta_title, description: page?.meta_description, openGraph: { images: [ { url: page?.ogImage ? urlFor(page?.ogImage).quality(100).url() : `${process.env.NEXT_PUBLIC_SITE_URL}/images/og-image.jpg`, width: page?.ogImage?.asset?.metadata?.dimensions?.width || 1200, height: page?.ogImage?.asset?.metadata?.dimensions?.height || 630, }, ], locale: "en_US", type: "website", }, robots: !isProduction ? "noindex, nofollow" : page?.noindex ? "noindex" : "index, follow", alternates: { canonical: process.env.NEXT_PUBLIC_SITE_URL + `/${slug === "index" ? "" : slug}`, }, }; } // Usage in page components export async function generateMetadata({ params }: { params: Promise<{ slug: string }> }) { const { slug } = await params; const page = await fetchSanityPageBySlug({ slug }); return generatePageMetadata({ page, slug }); } ``` -------------------------------- ### Build Optimized Image URLs with TypeScript Source: https://context7.com/serge-0v/next-js-sanity-starter/llms.txt Generates optimized image URLs from Sanity assets, automatically converting to WebP format and applying responsive sizing. It handles SVG preservation and integrates with Next.js Image components for efficient image loading. Dependencies include `@sanity/image-url`. ```typescript // sanity/lib/image.ts import { createImageUrlBuilder, type SanityImageSource } from "@sanity/image-url"; import { dataset, projectId } from "../env"; const builder = createImageUrlBuilder({ projectId, dataset }); export const urlFor = (source: SanityImageSource) => { const imageBuilder = builder.image(source); // Check if SVG to preserve format const sourceObj = source as { asset?: { mimeType?: string } }; const isSvg = sourceObj?.asset?.mimeType === "image/svg+xml"; if (isSvg) { return imageBuilder; } return imageBuilder.format("webp").fit("crop"); }; // Usage in components import { urlFor } from "@/sanity/lib/image"; {image.alt // With blur placeholder ``` -------------------------------- ### Hero Block Component Source: https://context7.com/serge-0v/next-js-sanity-starter/llms.txt Implements a hero block component that renders content from Sanity with optimized images and animated elements. ```APIDOC ## Hero Block Component ### Description Implements a hero block component that renders content from Sanity with optimized images and animated elements. ### Usage This component is intended to be used within a Next.js application that integrates with Sanity CMS. ### Props - **tagLine** (string) - Optional - The tagline for the hero section. - **title** (string) - Optional - The main title for the hero section. - **body** (PortableText) - Optional - The rich text content for the hero section. - **image** (SanityImage) - Optional - The main image for the hero section. - **links** (Array) - Optional - An array of links to be displayed as buttons. - **link.title** (string) - The text for the button. - **link.href** (string) - The URL the button links to. - **link.target** (string) - The target attribute for the link (e.g., "_blank"). - **link.buttonVariant** (string) - The visual variant of the button. ### Example ```typescript // components/blocks/hero/hero-1.tsx import { Button } from "@/components/ui/button"; import Link from "next/link"; import Image from "next/image"; import { urlFor } from "@/sanity/lib/image"; import { stegaClean } from "next-sanity"; import PortableTextRenderer from "@/components/portable-text-renderer"; import { PAGE_QUERYResult } from "@/sanity.types"; type Hero1Props = Extract< NonNullable["blocks"]>[number], { _type: "hero-1" } >; export default function Hero1({ tagLine, title, body, image, links }: Hero1Props) { return (
{tagLine && (

{tagLine}

)} {title && (

{title}

)} {body && (
)} {links && links.length > 0 && (
{links.map((link) => ( ))}
)}
{image && image.asset?._id && ( {image.alt )}
); } ``` ``` -------------------------------- ### Define GROQ Queries for Page Data Source: https://context7.com/serge-0v/next-js-sanity-starter/llms.txt Illustrates how to define GROQ queries in Sanity to fetch complete page data, including nested block components. It composes block-specific queries to ensure all necessary content is retrieved efficiently. This approach allows for structured data fetching for dynamic page layouts. ```groq // sanity/queries/page.ts import { groq } from "next-sanity"; import { hero1Query } from "./hero/hero-1"; import { sectionHeaderQuery } from "./section-header"; import { gridRowQuery } from "./grid/grid-row"; import { faqsQuery } from "./faqs"; export const PAGE_QUERY = groq` *[_type == "page" && slug.current == $slug][0]{ blocks[]{ ${hero1Query}, ${sectionHeaderQuery}, ${gridRowQuery}, ${faqsQuery}, }, meta_title, meta_description, noindex, ogImage { asset->{ _id, url, metadata { dimensions { width, height } } }, } } `; export const PAGES_SLUGS_QUERY = groq`*[_type == "page" && defined(slug)]{slug}`; // Example block query - sanity/queries/hero/hero-1.ts export const hero1Query = groq` _type == "hero-1" => { _type, _key, tagLine, title, body[]{ ... }, image{ ..., asset->{ _id, url, mimeType, metadata { lqip, dimensions { width, height } } }, alt }, links[]{ title, href, target, buttonVariant }, } ` ``` -------------------------------- ### Define Sanity Environment Configuration (TypeScript) Source: https://context7.com/serge-0v/next-js-sanity-starter/llms.txt Imports and asserts the presence of critical environment variables required for Sanity CMS integration, such as API version, project ID, and dataset. ```typescript // sanity/env.ts export const apiVersion = process.env.NEXT_PUBLIC_SANITY_API_VERSION || "2024-10-31"; export const dataset = assertValue( process.env.NEXT_PUBLIC_SANITY_DATASET, "Missing environment variable: NEXT_PUBLIC_SANITY_DATASET" ); export const projectId = assertValue( process.env.NEXT_PUBLIC_SANITY_PROJECT_ID, "Missing environment variable: NEXT_PUBLIC_SANITY_PROJECT_ID" ); function assertValue(v: T | undefined, errorMessage: string): T { if (v === undefined) { throw new Error(errorMessage); } return v; } ``` -------------------------------- ### Newsletter Subscription API in TypeScript Source: https://context7.com/serge-0v/next-js-sanity-starter/llms.txt Handles newsletter sign-ups by integrating with the Resend API. This API endpoint receives an email address, adds it to a specified audience list, and returns a success or error response. It requires `RESEND_API_KEY` and `RESEND_AUDIENCE_ID` environment variables. ```typescript // app/api/newsletter/route.ts import { Resend } from "resend"; const resend = new Resend(process.env.RESEND_API_KEY); export const POST = async (request: Request) => { const { email } = await request.json(); try { resend.contacts.create({ email, unsubscribed: false, audienceId: process.env.RESEND_AUDIENCE_ID!, }); return Response.json({ success: true }); } catch (error: any) { return Response.json( { error: "Error subscribing to updates" }, { status: 400 } ); } }; // Client-side usage in components/blocks/forms/newsletter.tsx const handleSend = async ({ email }: { email: string }) => { const response = await fetch("/api/newsletter", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ email }), }); const result = await response.json(); if (response.ok) { toast("Successfully subscribed!"); } else { toast.error(result.error); } }; ``` -------------------------------- ### Draft Mode API Source: https://context7.com/serge-0v/next-js-sanity-starter/llms.txt Enables and disables Sanity's draft mode for previewing unpublished content in the Next.js application. ```APIDOC ## Draft Mode API ### Description Provides endpoints to enable and disable Sanity's draft mode, allowing for the preview of unpublished content within the Next.js application. ### Enable Draft Mode #### Method GET #### Endpoint `/api/draft-mode/enable` #### Usage This endpoint is typically called by the Sanity Studio's presentation tool to enable draft mode. #### Configuration in `sanity.config.ts` ```typescript // sanity.config.ts presentationTool({ previewUrl: { draftMode: { enable: "/api/draft-mode/enable", }, }, resolve, }) ``` ### Disable Draft Mode #### Method GET #### Endpoint `/api/draft-mode/disable` #### Description Disables Sanity's draft mode and redirects the user to the homepage. #### Implementation ```typescript // app/api/draft-mode/disable/route.ts import { draftMode } from "next/headers"; import { NextRequest, NextResponse } from "next/server"; export async function GET(request: NextRequest) { (await draftMode()).disable(); return NextResponse.redirect(new URL("/", request.url)); } ``` ``` -------------------------------- ### Newsletter API Endpoint Source: https://context7.com/serge-0v/next-js-sanity-starter/llms.txt Handles newsletter subscriptions using the Resend API to add contacts to an audience list. ```APIDOC ## Newsletter API Endpoint ### Description Handles newsletter subscriptions by integrating with the Resend API to add contacts to a specified audience list. ### Method POST ### Endpoint `/api/newsletter` ### Request Body - **email** (string) - Required - The email address of the subscriber. ### Request Example ```json { "email": "subscriber@example.com" } ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the subscription was successful. #### Error Response (400) - **error** (string) - A message describing the subscription error. ### Client-side Usage Example ```typescript // components/blocks/forms/newsletter.tsx const handleSend = async ({ email }: { email: string }) => { const response = await fetch("/api/newsletter", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ email }), }); const result = await response.json(); if (response.ok) { toast("Successfully subscribed!"); } else { toast.error(result.error); } }; ``` ``` -------------------------------- ### Hero Block Component in TypeScript Source: https://context7.com/serge-0v/next-js-sanity-starter/llms.txt Implements a reusable hero block component for Next.js applications. It fetches content from Sanity, optimizes images using next/image, and supports animated elements. Dependencies include next-sanity, next/image, and custom UI components. ```typescript // components/blocks/hero/hero-1.tsx import { Button } from "@/components/ui/button"; import Link from "next/link"; import Image from "next/image"; import { urlFor } from "@/sanity/lib/image"; import { stegaClean } from "next-sanity"; import PortableTextRenderer from "@/components/portable-text-renderer"; import { PAGE_QUERYResult } from "@/sanity.types"; type Hero1Props = Extract< NonNullable["blocks"]>[number], { _type: "hero-1" } >; export default function Hero1({ tagLine, title, body, image, links }: Hero1Props) { return (
{tagLine && (

{tagLine}

)} {title && (

{title}

)} {body && (
)} {links && links.length > 0 && (
{links.map((link) => ( ))}
)}
{image && image.asset?._id && ( {image.alt )}
); } ``` -------------------------------- ### Sanity Draft Mode API in TypeScript Source: https://context7.com/serge-0v/next-js-sanity-starter/llms.txt Provides API routes for enabling and disabling Sanity's draft mode within a Next.js application. This allows for previewing unpublished content. It utilizes `next-sanity/draft-mode` and requires configuration in `sanity.config.ts`. ```typescript // app/api/draft-mode/enable/route.ts import { defineEnableDraftMode } from "next-sanity/draft-mode"; import { client } from "@/sanity/lib/client"; import { token } from "@/sanity/lib/token"; export const { GET } = defineEnableDraftMode({ client: client.withConfig({ token }), }); // app/api/draft-mode/disable/route.ts import { draftMode } from "next/headers"; import { NextRequest, NextResponse } from "next/server"; export async function GET(request: NextRequest) { (await draftMode()).disable(); return NextResponse.redirect(new URL("/", request.url)); } // Enable draft mode from Sanity Studio Presentation Tool // Configure in sanity.config.ts: presentationTool({ previewUrl: { draftMode: { enable: "/api/draft-mode/enable", }, }, resolve, }) ``` -------------------------------- ### Define Sanity Page Schema with Typed Fields and Validation Source: https://context7.com/serge-0v/next-js-sanity-starter/llms.txt This TypeScript code defines a Sanity document schema for a 'page' type. It uses Sanity's schema API to define fields with specific types (string, slug, array, image, boolean), assigns them to groups (content, SEO, settings), and includes validation rules and an order rank field for document ordering. Dependencies include 'sanity' and '@sanity/orderable-document-list'. ```typescript // sanity/schemas/documents/page.ts import { defineField, defineType } from "sanity"; import { Files } from "lucide-react"; import { orderRankField } from "@sanity/orderable-document-list"; export default defineType({ name: "page", type: "document", title: "Page", icon: Files, groups: [ { name: "content", title: "Content" }, { name: "seo", title: "SEO" }, { name: "settings", title: "Settings" }, ], fields: [ defineField({ name: "title", type: "string", group: "content" }), defineField({ name: "slug", title: "Slug", type: "slug", group: "settings", options: { source: "title", maxLength: 96 }, validation: (Rule) => Rule.required(), }), defineField({ name: "blocks", type: "array", group: "content", of: [ { type: "hero-1" }, { type: "hero-2" }, { type: "section-header" }, { type: "split-row" }, { type: "grid-row" }, { type: "carousel-1" }, { type: "carousel-2" }, { type: "cta-1" }, { type: "faqs" }, { type: "form-newsletter" }, { type: "all-posts" }, ], }), defineField({ name: "meta_title", type: "string", group: "seo" }), defineField({ name: "meta_description", type: "text", group: "seo" }), defineField({ name: "noindex", type: "boolean", initialValue: false, group: "seo" }), defineField({ name: "ogImage", type: "image", group: "seo" }), orderRankField({ type: "page" }), ], }); ``` -------------------------------- ### Render Sanity Blocks Dynamically with React Components Source: https://context7.com/serge-0v/next-js-sanity-starter/llms.txt This TypeScript code dynamically renders Sanity content blocks within a Next.js application. It maps Sanity block types (e.g., 'hero-1', 'grid-row') to corresponding React components using a 'componentMap'. It handles cases where a component for a block type is not found by logging a warning. Dependencies include React and generated Sanity types. ```typescript // components/blocks/index.tsx import { PAGE_QUERYResult } from "@/sanity.types"; import Hero1 from "@/components/blocks/hero/hero-1"; import Hero2 from "@/components/blocks/hero/hero-2"; import SectionHeader from "@/components/blocks/section-header"; import GridRow from "@/components/blocks/grid/grid-row"; import FAQs from "@/components/blocks/faqs"; import FormNewsletter from "@/components/blocks/forms/newsletter"; type Block = NonNullable["blocks"]>[number]; const componentMap: { [K in Block["_type"]]: React.ComponentType>; } = { "hero-1": Hero1, "hero-2": Hero2, "section-header": SectionHeader, "grid-row": GridRow, "faqs": FAQs, "form-newsletter": FormNewsletter, // ... other block mappings }; export default function Blocks({ blocks }: { blocks: Block[] }) { return ( <> {blocks?.map((block) => { const Component = componentMap[block._type]; if (!Component) { console.warn(`No component for block type: ${block._type}`); return
; } return ; })} ); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.