1.2.1 • Published 8 months ago

@skavl-media/next-sanity v1.2.1

Weekly downloads
-
License
MIT
Repository
github
Last release
8 months ago

@skavl-media/sanity

A lightweight Sanity.io client library for making queries and mutations in Next.js applications.

Installation

npm install @skavl-media/sanity

Peer Dependencies

This package requires the following peer dependencies:

npm install next@^15.0.0 next-sanity@^9.0.0

Usage

Initialize Environment Variables

First, set up the required environment variables in your .env file:

NEXT_PUBLIC_SANITY_PROJECT_ID="your-project-id"
NEXT_PUBLIC_SANITY_DATASET="production"
NEXT_PUBLIC_SANITY_API_VERSION="2024-11-21"
NEXT_PUBLIC_SANITY_STUDIO_URL="https://your-studio-url"
SANITY_API_TOKEN="your-api-token" # Required for draft mode

Using sanityFetch

sanityFetch is a server-side function that handles both published and draft content:

import { sanityFetch } from '@skavl-media/sanity';

// In a Server Component
async function getData() {
  const posts = await sanityFetch<Post[]>({
    query: `*[_type == "post"]`,
    // Optional parameters
    params: { limit: 10 },
    // Cache for 60 seconds (default)
    revalidate: 60,
    // Optional tags for on-demand revalidation
    tags: ['posts'],
  });

  return posts;
}

Features:

  • Type-safe queries with generics
  • Automatic draft mode handling
  • Configurable caching with revalidate
  • Tag-based revalidation support
  • Stega-enabled preview mode

Using sanityClient

For direct client access (useful for mutations or client-side queries):

import { sanityClient } from '@skavl-media/sanity';

// Example mutation
async function createPost(data: PostData) {
  return sanityClient.create({
    _type: 'post',
    ...data,
  });
}

// Example query
async function getPosts() {
  return sanityClient.fetch(`*[_type == "post"]`);
}

Caching Behavior

  • Default cache duration: 60 seconds
  • Draft mode: No caching (revalidate: 0)
  • With tags: Infinite cache until manually revalidated
  • Custom cache duration: Set via revalidate parameter

Draft Mode

The package automatically handles draft mode when enabled in your Next.js application. In draft mode:

  • Caching is disabled
  • Preview drafts are visible
  • Stega is enabled for visual editing
  • Requires SANITY_API_TOKEN environment variable

On-Demand Revalidation

When using tags, you can revalidate content on-demand:

License

MIT

Repository

GitHub Repository

Keywords

  • sanity
  • next.js
  • skavlmedia
1.2.1

8 months ago

1.2.0

8 months ago

1.1.1

8 months ago

1.1.0

8 months ago