Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

next-sanity

Package Overview
Dependencies
Maintainers
62
Versions
391
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

next-sanity

Sanity.io toolkit for Next.js

  • 9.7.1
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
72K
decreased by-15.13%
Maintainers
62
Weekly downloads
 
Created
Source

next-sanity

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

Features:

Quicklinks: Sanity docsNext.js docsClean starter templateFully-featured starter template

Table of contents

Installation

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 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 section.

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

Manual configuration

The npx sanity@latest init command offers to write some configuration files for your Next.js application. Most importantly is one that writes your chosen Sanity project ID and dataset name to your local environment variables. Note that unlike access tokens, the project ID and dataset name are not considered sensitive information.

Create this file at the root of your Next.js application if it does not already exist.

# .env.local

NEXT_PUBLIC_SANITY_PROJECT_ID=<your-project-id>
NEXT_PUBLIC_SANITY_DATASET=<your-dataset-name>

Create a file to access and export these values

// ./src/sanity/env.ts

export const dataset = process.env.NEXT_PUBLIC_SANITY_DATASET!
export const projectId = process.env.NEXT_PUBLIC_SANITY_PROJECT_ID!

// Values you may additionally want to configure globally
export const apiVersion = process.env.NEXT_PUBLIC_SANITY_API_VERSION || '2024-07-11'

Remember to add these environment variables to your hosting provider's environment as well.

Write GROQ queries

next-sanity exports the defineQuery function which will give you syntax highlighting in VS Code with the Sanity extension installed. It’s also used for GROQ query result type generation with Sanity TypeGen.

// ./src/sanity/lib/queries.ts

import {defineQuery} from 'next-sanity'

export const POSTS_QUERY = defineQuery(`*[_type == "post" && defined(slug.current)][0...12]{
  _id, title, slug
}`)

export const POST_QUERY = defineQuery(`*[_type == "post" && slug.current == $slug][0]{
  title, body, mainImage
}`)

Generate TypeScript Types

You can use Sanity TypeGen to generate TypeScript types for your schema types and GROQ query results in your Next.js application. It should be readily available if you have used sanity init and chosen the embedded Studio.

[!TIP] Sanity TypeGen will create Types for queries that are assigned to a variable and use the groq template literal or defineQuery function.

If your Sanity Studio schema types are in a different project or repository, you can configure Sanity TypeGen to write types to your Next.js project.

Create a sanity-typegen.json file at the root of your project to configure Sanity TypeGen:

// sanity-typegen.json
{
  "path": "./src/**/*.{ts,tsx,js,jsx}",
  "schema": "./src/sanity/extract.json",
  "generates": "./src/sanity/types.ts"
}

Note: This configuration is strongly opinionated that the generated Types and the schema extraction are both within the /src/sanity directory, not the root which is the default. This configuration is complimented by setting the path of the schema extraction in the updated package.json scripts below.

Run the following command in your terminal to extract your Sanity Studio schema to a JSON file

# Run this each time your schema types change
npx sanity@latest schema extract

Run the following command in your terminal to generate TypeScript types for both your Sanity Studio schema and GROQ queries

# Run this each time your schema types or GROQ queries change
npx sanity@latest typegen generate

Update your Next.js project's package.json to perform both of these commands by running npm run typegen

"scripts": {
  "predev": "npm run typegen",
  "dev": "next",
  "prebuild": "npm run typegen",
  "build": "next build",
  "start": "next start",
  "lint": "next lint",
  "typegen": "sanity schema extract --path=src/sanity/extract.json && sanity typegen generate"
},

Using query result types

Sanity TypeGen creates TypeScript types for the results of your GROQ queries, which can be used as generics like this:

import {client} from '@/sanity/lib/client'
import {POSTS_QUERY} from '@/sanity/lib/queries'
import {POSTS_QUERYResult} from '@/sanity/types'

const posts = await client.fetch<POSTS_QUERYResult>(POSTS_QUERY)
//    ^? const post: POST_QUERYResult

However, it is much simpler to use automatic type inference. So long as your GROQ queries are wrapped in defineQuery, the results should be inferred automatically:

import {client} from '@/sanity/lib/client'
import {POSTS_QUERY} from '@/sanity/lib/queries'

const posts = await client.fetch(POSTS_QUERY)
//    ^? const post: POST_QUERYResult

Query content from Sanity Content Lake

Sanity content is typically queried with GROQ queries from a configured Sanity Client. Sanity also supports GraphQL.

Configuring Sanity Client

To interact with Sanity content in a Next.js application, we recommend creating a client.ts file:

// ./src/sanity/lib/client.ts
import {createClient} from 'next-sanity'

import {apiVersion, dataset, projectId} from '../env'

export const client = createClient({
  projectId,
  dataset,
  apiVersion, // https://www.sanity.io/docs/api-versioning
  useCdn: true, // Set to false if statically generating pages, using ISR or tag-based revalidation
})

Fetching in App Router Components

To fetch data in a React Server Component using the App Router you can await results from the Sanity Client inside a server component:

// ./src/app/page.tsx

import {client} from '@/sanity/lib/client'
import {POSTS_QUERY} from '@/sanity/lib/queries'

export default async function PostIndex() {
  const posts = await client.fetch(POSTS_QUERY)

  return (
    <ul>
      {posts.map((post) => (
        <li key={post._id}>
          <a href={`/posts/${post?.slug.current}`}>{post?.title}</a>
        </li>
      ))}
    </ul>
  )
}

Fetching in Page Router Components

If you're using the Pages Router you can await results from Sanity Client inside a getStaticProps function:

// ./src/pages/index.tsx

import {client} from '@/sanity/lib/client'
import {POSTS_QUERY} from '@/sanity/lib/queries'

export async function getStaticProps() {
  const posts = await client.fetch(POSTS_QUERY)

  return {posts}
}

export default async function PostIndex({posts}) {
  return (
    <ul>
      {posts.map((post) => (
        <li key={post._id}>
          <a href={`/posts/${post?.slug.current}`}>{post?.title}</a>
        </li>
      ))}
    </ul>
  )
}

Should useCdn be true or false?

You might notice that you have to set the useCdn to true or false in the client configuration. Sanity offers caching on a CDN for queries. Since Next.js has its own caching, using the Sanity CDN might not be necessary, but there are some exceptions.

In general, set useCdn to true when:

  • Data fetching happens client-side, for example, in a useEffect hook or in response to a user interaction where the client.fetch call is made in the browser.
  • Server-side rendered (SSR) data fetching is dynamic and has a high number of unique requests per visitor, for example, a "For You" feed.

Set useCdn to false when:

  • Used in a static site generation context, for example, getStaticProps or getStaticPaths.
  • Used in an ISR on-demand webhook responder.
  • Good stale-while-revalidate caching is in place that keeps API requests on a consistent low, even if traffic to Next.js spikes.
  • For Preview or Draft modes as part of an editorial workflow, you need to ensure that the latest content is always fetched.

How does apiVersion work?

Sanity uses date-based API versioning. You can configure the date in a YYYY-MM-DD format, and it will automatically fall back on the latest API version of that time. Then, if a breaking change is introduced later, it won't break your application and give you time to test before upgrading.

Caching and revalidation

This toolkit includes the @sanity/client which fully supports Next.js fetch based features for caching and revalidation. This ensures great performance while preventing stale content in a way that's native to Next.js.

[!NOTE] Some hosts (like Vercel) will keep the content cache in a dedicated data layer and not part of the static app bundle, which means re-deploying the app will not purge the cache. We recommend reading up on caching behavior in the Next.js docs.

sanityFetch() helper function

It can be beneficial to set revalidation defaults for all queries. In all of the following examples, a sanityFetch() helper function is used for this purpose.

While this function is written to accept both Next.js caching options revalidate and tags, your application should only rely on one. For this reason, if tags are supplied, the revalidate setting will be set to false (cache indefinitely) and you will need to bust the cache for these pages using revalidateTag().

In short:

  • Time-based revalidate is good enough for most applications.
  • Content-based tags will give you more fine-grained control for complex applications.
// ./src/sanity/lib/client.ts

import {createClient, type QueryParams} from 'next-sanity'

import {apiVersion, dataset, projectId} from '../env'

export const client = createClient({
  projectId,
  dataset,
  apiVersion, // https://www.sanity.io/docs/api-versioning
  useCdn: true, // Set to false if statically generating pages, using ISR or tag-based revalidation
})

export async function sanityFetch<const QueryString extends string>({
  query,
  params = {},
  revalidate = 60, // default revalidation time in seconds
  tags = [],
}: {
  query: QueryString
  params?: QueryParams
  revalidate?: number | false
  tags?: string[]
}) {
  return client.fetch(query, params, {
    next: {
      revalidate: tags.length ? false : revalidate, // for simple, time-based revalidation
      tags, // for tag-based revalidation
    },
  })
}

Be aware that you can get errors if you use cache and revalidate configurations for Next.js together. See the Next.js documentation on revalidation.

Time-based revalidation

Time-based revalidation is often good enough for the majority of applications.

Increase the revalidate setting for longer-lived and less frequently modified content.

// ./src/app/pages/index.tsx

import {sanityFetch} from '@/sanity/lib/client'
import {POSTS_QUERY} from '@/sanity/lib/queries'

export default async function PostIndex() {
  const posts = await sanityFetch({
    query: POSTS_QUERY,
    revalidate: 3600, // update cache at most once every hour
  })

  return (
    <ul>
      {posts.map((post) => (
        <li key={post._id}>
          <a href={`/posts/${post?.slug.current}`}>{post?.title}</a>
        </li>
      ))}
    </ul>
  )
}

Path-based revalidation

For on-demand revalidation of individual pages, Next.js has a revalidatePath() function. You can create an API route in your Next.js application to execute it, and a GROQ-powered webhook in your Sanity Project to instantly request it when content is created, updated or deleted.

Create a new environment variable SANITY_REVALIDATE_SECRET with a random string that is shared between your Sanity project and your Next.js application. This is considered sensitive and should not be committed to your repository.

# .env.local

SANITY_REVALIDATE_SECRET=<some-random-string>

Create a new API route in your Next.js application

The code example below uses the built-in parseBody function to validate that the request comes from your Sanity project (using a shared secret and looking at the request headers). Then it looks at the document type information in the webhook payload and matches that against the revalidation tags in your application

// ./src/app/api/revalidate-path/route.ts

import {revalidatePath} from 'next/cache'
import {type NextRequest, NextResponse} from 'next/server'
import {parseBody} from 'next-sanity/webhook'

type WebhookPayload = {path?: string}

export async function POST(req: NextRequest) {
  try {
    if (!process.env.SANITY_REVALIDATE_SECRET) {
      return new Response('Missing environment variable SANITY_REVALIDATE_SECRET', {status: 500})
    }

    const {isValidSignature, body} = await parseBody<WebhookPayload>(
      req,
      process.env.SANITY_REVALIDATE_SECRET,
    )

    if (!isValidSignature) {
      const message = 'Invalid signature'
      return new Response(JSON.stringify({message, isValidSignature, body}), {status: 401})
    } else if (!body?.path) {
      const message = 'Bad Request'
      return new Response(JSON.stringify({message, body}), {status: 400})
    }

    revalidatePath(body.path)
    const message = `Updated route: ${body.path}`
    return NextResponse.json({body, message})
  } catch (err) {
    console.error(err)
    return new Response(err.message, {status: 500})
  }
}

Create a new GROQ-powered webhook in your Sanity project.

You can copy this template to quickly add the webhook to your Sanity project.

The Projection uses GROQ's select() function to dynamically create paths for nested routes like /posts/[slug], you can extend this example your routes and other document types.

{
  "path": select(
    _type == "post" => "/posts/" + slug.current,
    "/" + slug.current
  )
}

[!TIP] If you wish to revalidate all routes on demand, create an API route that calls revalidatePath('/', 'layout')

Tag-based revalidation

Tag-based revalidation is preferable for instances where many pages are affected by a single document being created, updated or deleted.

For on-demand revalidation of many pages, Next.js has a revalidateTag() function. You can create an API route in your Next.js application to execute it, and a GROQ-powered webhook in your Sanity Project to instantly request it when content is created, updated or deleted.

// ./src/app/pages/index.tsx

import {sanityFetch} from '@/sanity/lib/client'
import {POSTS_QUERY} from '@/sanity/lib/queries'

export default async function PostIndex() {
  const posts = await sanityFetch({
    query: POSTS_QUERY,
    tags: ['post', 'author'], // revalidate all pages with the tags 'post' and 'author'
  })

  return (
    <ul>
      {posts.map((post) => (
        <li key={post._id}>
          <a href={`/posts/${post?.slug.current}`}>{post?.title}</a>
        </li>
      ))}
    </ul>
  )
}

Create a new environment variable SANITY_REVALIDATE_SECRET with a random string that is shared between your Sanity project and your Next.js application. This is considered sensitive and should not be committed to your repository.

# .env.local

SANITY_REVALIDATE_SECRET=<some-random-string>

Create a new API route in your Next.js application

The code example below uses the built-in parseBody function to validate that the request comes from your Sanity project (using a shared secret and looking at the request headers). Then it looks at the document type information in the webhook payload and matches that against the revalidation tags in your application

// ./src/app/api/revalidate-tag/route.ts

import {revalidateTag} from 'next/cache'
import {type NextRequest, NextResponse} from 'next/server'
import {parseBody} from 'next-sanity/webhook'

type WebhookPayload = {
  _type: string
}

export async function POST(req: NextRequest) {
  try {
    if (!process.env.SANITY_REVALIDATE_SECRET) {
      return new Response('Missing environment variable SANITY_REVALIDATE_SECRET', {status: 500})
    }

    const {isValidSignature, body} = await parseBody<WebhookPayload>(
      req,
      process.env.SANITY_REVALIDATE_SECRET,
    )

    if (!isValidSignature) {
      const message = 'Invalid signature'
      return new Response(JSON.stringify({message, isValidSignature, body}), {status: 401})
    } else if (!body?._type) {
      const message = 'Bad Request'
      return new Response(JSON.stringify({message, body}), {status: 400})
    }

    // If the `_type` is `post`, then all `client.fetch` calls with
    // `{next: {tags: ['post']}}` will be revalidated
    revalidateTag(body._type)

    return NextResponse.json({body})
  } catch (err) {
    console.error(err)
    return new Response(err.message, {status: 500})
  }
}

Create a new GROQ-powered webhook in your Sanity project.

You can copy this template to quickly add the webhook to your Sanity project.

Debugging caching and revalidation

To aid in debugging and understanding what's in the cache, revalidated, skipped, and more, add the following to your Next.js configuration file:

// ./next.config.js
module.exports = {
  logging: {
    fetches: {
      fullUrl: true,
    },
  },
}

Example implementation

Check out the Personal website template to see a feature-complete example of how revalidateTag is used together with Visual Editing.

Visual Editing

Interactive live previews of draft content are the best way for authors to find and edit content with the least amount of effort and the most confidence to press publish.

[!TIP] Visual Editing is available on all Sanity plans and can be enabled on all hosting environments.

[!NOTE] Vercel "Content Link" adds an "edit" button to the Vercel toolbar on preview builds and is available on Vercel Pro and Enterprise plans.

An end-to-end tutorial of how to configure Sanity and Next.js for Visual Editing using the same patterns demonstrated in this README is available on the Sanity Exchange.

Embedded Sanity Studio

Sanity Studio is a near-infinitely configurable content editing interface that can be embedded into any React application. For Next.js, you can embed the Studio on a route (like /studio). The Studio will still require authentication and be available only for members of your Sanity project.

This opens up many possibilities including dynamic configuration of your Sanity Studio based on a network request or user input.

[!WARNING] The convenience of co-locating the Studio with your Next.js application is appealing, but it can also influence your content model to be too website-centric, and potentially make collaboration with other developers more difficult. Consider a standalone or monorepo Studio repository for larger projects and teams.

Creating a Studio route

next-sanity exports a <NextStudio /> component to load Sanity's <Studio /> component wrapped in a Next.js friendly layout. metadata specifies the necessary <meta> tags for making the Studio adapt to mobile devices and prevents the route from being indexed by search engines.

Automatic installation of embedded Studio

To quickly connect an existing - or create a new - Sanity project to your Next.js application, run the following command in your terminal. You will be prompted to create a route for the Studio during setup.

npx sanity@latest init

Manual installation of embedded Studio

Create a file sanity.config.ts in the project's root and copy the example below:

// ./sanity.config.ts

import {defineConfig} from 'sanity'
import {structureTool} from 'sanity/structure'

const projectId = process.env.NEXT_PUBLIC_SANITY_PROJECT_ID!
const dataset = process.env.NEXT_PUBLIC_SANITY_DATASET!

export default defineConfig({
  basePath: '/studio', // `basePath` must match the route of your Studio
  projectId,
  dataset,
  plugins: [structureTool()],
  schema: {types: []},
})

Optionally, create a sanity.cli.ts with the same projectId and dataset as your sanity.config.ts to the project root so that you can run npx sanity <command> from the terminal inside your Next.js application:

// ./sanity.cli.ts

import {defineCliConfig} from 'sanity/cli'

const projectId = process.env.NEXT_PUBLIC_SANITY_PROJECT_ID!
const dataset = process.env.NEXT_PUBLIC_SANITY_DATASET!

export default defineCliConfig({api: {projectId, dataset}})

Now you can run commands like npx sanity cors add. Run npx sanity help for a full list of what you can do.

Studio route with App Router

Even if the rest of your app is using Pages Router, you can and should mount the Studio on an App Router route. Next.js supports both routers in the same app.

Create a new route to render the Studio, with the default metadata and viewport configuration:

// ./src/app/studio/[[...tool]]/page.tsx

import {NextStudio} from 'next-sanity/studio'
import config from '../../../../sanity.config'

export const dynamic = 'force-static'

export {metadata, viewport} from 'next-sanity/studio'

export default function StudioPage() {
  return <NextStudio config={config} />
}

The default meta tags exported by next-sanity can be customized if necessary:

// ./src/app/studio/[[...tool]]/page.tsx

import type {Metadata, Viewport} from 'next'
import {metadata as studioMetadata, viewport as studioViewport} from 'next-sanity/studio'

// Set the correct `viewport`, `robots` and `referrer` meta tags
export const metadata: Metadata = {
  ...studioMetadata,
  // Overrides the title until the Studio is loaded
  title: 'Loading Studio...',
}

export const viewport: Viewport = {
  ...studioViewport,
  // Overrides the viewport to resize behavior
  interactiveWidget: 'resizes-content',
}

export default function StudioPage() {
  return <NextStudio config={config} />
}

Lower-level control with StudioProvider and StudioLayout

If you need even more control over the Studio, you can pass StudioProvider and StudioLayout from sanity as children:

// ./src/app/studio/[[...tool]]/page.tsx

'use client'

import {NextStudio} from 'next-sanity/studio'
import {StudioProvider, StudioLayout} from 'sanity'

import config from '../../../sanity.config'

function StudioPage() {
  return (
    <NextStudio config={config}>
      <StudioProvider config={config}>
        {/* Put components here and you'll have access to the same React hooks as Studio gives you when writing plugins */}
        <StudioLayout />
      </StudioProvider>
    </NextStudio>
  )
}

Migration guides

[!IMPORTANT] You're looking at the README for v9, the README for v8 is available here as well as an migration guide.

License

MIT-licensed. See LICENSE.

Keywords

FAQs

Package last updated on 23 Oct 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc