Skip to content

About

Sanity toolkit for Next.js

Topics

Resources

Code of conduct

Security policy

Stars

955 stars

Watchers

24 watching

Forks

Repository files navigation

next-sanity

The all-in-one Sanity toolkit for production-grade content-editable Next.js applications.

  • Next.js + Sanity quick start: Get a working Next.js + Sanity project running in minutes, from creating a Sanity project to querying your first content.
  • next-sanity overview: Explore everything the next-sanity package has to offer.
  • Configure the next-sanity client: Set up the Sanity client with environment variables, CDN caching, and per-request overrides for different fetching contexts.
  • Query with GROQ: Make type safe queries with GROQ using the included Sanity client.
  • Visual editing and live preview: Enable click-to-edit overlays and real-time content updates in the Presentation Tool using Draft Mode, defineLive, and the <VisualEditing /> component.
  • Caching and revalidation: Control content freshness with time-based, tag-based, and path-based revalidation strategies for applications that need fine-grained cache management.
  • Reference documentation: Browse the full next-sanity API reference for detailed type signatures and configuration options.

Quicklinks: Sanity docs | Next.js docs | Clean starter template | Fully-featured starter template

Table of contents

Quick Start

Instantly create a new free Sanity project – or link to an existing one – from the command line and connect it to your Next.js application by the following terminal command in your Next.js project folder:

npx sanity@latest init

If you do not yet have a Sanity account you will be prompted to create one. This command will create the basic utilities required to query content from Sanity, and optionally embed Sanity Studio — a configurable content management system — at a route in your Next.js application. See the Embedded Sanity Studio guide.

Manual installation

If you do not yet have a Next.js application, you can create one with the following command:

npx create-next-app@latest

This README assumes you have chosen all of the default options, but should be fairly similar for most bootstrapped Next.js projects.

Install next-sanity

Inside your Next.js application, run the following command in the package manager of your choice to install the next-sanity toolkit:

npm install next-sanity @sanity/image-url
yarn add next-sanity @sanity/image-url
pnpm install next-sanity @sanity/image-url
bun install next-sanity @sanity/image-url

This also installs @sanity/image-url for On-Demand Image Transformations to render images from Sanity's CDN.

Optional: peer dependencies for embedded Sanity Studio

When using npm newer than v7, or pnpm newer than v8, you should end up with needed dependencies like sanity and styled-components when you installed next-sanity. In yarn v1 you can use install-peerdeps:

npx install-peerdeps --yarn next-sanity

Rendering images (alpha)

next-sanity/image renders images from the Sanity Image CDN through next/image, preconfigured with a loader that serves right-sized, auto-formatted (AVIF/WebP) images for every srcset candidate.

Pass an image object from a GROQ query directly to src — the shapes generated by sanity typegen are accepted as-is:

import {Image} from 'next-sanity/image'

export function PostCard({post}: {post: {mainImage: SanityImageObject}}) {
  return (
    <Image
      src={post.mainImage}
      projectId="<your-project-id>"
      dataset="production"
      width={800}
      height={400}
      alt=""
    />
  )
}
  • The crop set in the Studio is applied, and when the requested aspect ratio differs, the crop is positioned around the image's hotspot. Partial crop and hotspot projections are filled in by @sanity/image-url (missing crop insets are 0; a hotspot that only has x and y is positioned on that point).
  • With fill, the browser crops the image to its parent. When src is an image object with a hotspot, object-position defaults to that hotspot as percentages of the cropped image (x: 0.75, y: 0.25 becomes 75% 25%, shifted when a Studio crop is set), so object-fit: cover keeps the subject in frame. A hotspot outside the crop is pinned to the nearest edge. queryParams={{flip: 'h'}} (v or hv too) mirrors that default, and queryParams={{or: 90}} (180 or 270 too) rotates it clockwise, so it follows the image the CDN serves. style={{objectPosition: '…'}} and the objectPosition prop override the default.
  • InferImageValue and InferStrictImageValue collect those image shapes from a TypeGen query result, including stega-branded sanityFetch results. isImageWithAsset narrows an image to one that has an asset.
  • width and height are optional: they are inferred from the asset (and adjusted for the crop), and providing only one dimension derives the other from the aspect ratio — like next/image does for static imports.
  • With placeholder="blur", the low-quality image preview is used automatically when the query includes it. Keep the asset's url (or _id) next to the metadata when dereferencing, so the image can still be built: asset->{url, metadata{lqip}}.
  • projectId and dataset can be omitted when the query dereferences the asset URL (asset->{url}): they are read from the URL. Consider wrapping the component once in your app to bind them.
  • URL strings work too: src accepts asset->url values and URLs built with @sanity/image-url, inferring dimensions from the URL's params and filename.
  • Everything else works like next/image: sizes, fill, preload, placeholder, quality (values other than 75 must be listed in images.qualities since Next.js 16), event handlers and refs. Use the queryParams prop for additional image transformations, e.g. queryParams={{blur: 50}}. On image objects and asset ids, fit, the crop mode (crop) and a focal point (fp-x with fp-y) are forwarded to the URL builder so they affect the crop and hotspot; sizing params (w, h, rect) are ignored.

Note

The next-sanity/image API is in alpha and may change in a minor release.

Troubleshooting

Draft mode cookies are blocked in the Presentation Tool

When the Presentation Tool loads your site in a cross-site iframe (for example a Studio hosted on *.sanity.studio previewing your production domain), defineEnableDraftMode sets the draft-mode cookies with the CHIPS Partitioned attribute so browsers that block third-party cookies (Chrome, Safari 18.4+) still store them.

Some browser configurations reject even Partitioned cookies — most commonly Firefox with Enhanced Tracking Protection set to block all cross-site cookies, which logs errors like:

Cookie "__prerender_bypass" has been rejected as third-party.

defineEnableDraftMode detects this and shows a dialog inside the preview iframe that requests cookie access through the Storage Access API and retries. If the Presentation Tool reports "Unable to connect" on top of the preview, choose "Continue anyway" to interact with the dialog. If the browser denies storage access there is no programmatic escape hatch; the dialog then explains the remaining options:

  • Allow cross-site cookies for the Studio site — in Firefox, click the shield icon in the address bar and turn off Enhanced Tracking Protection for the Studio, then reload the preview.
  • Open the preview in a new tab, where the cookies are first-party and always allowed.

Migration guides

License

MIT-licensed. See LICENSE.

About

Sanity toolkit for Next.js

Topics

Resources

Code of conduct

Security policy

Stars

955 stars

Watchers

24 watching

Forks

Releases

Used by

Contributors

Languages