Difficulty using sanity client object in sanity studio document file in sanity 3.

2 replies
Last updated: Nov 7, 2023
One question.I am going to use sanity client object in sanity studio document file,
In sanity 2, I can use this module
import client from 'part:@sanity/base/client'
,but in sanity 3, I cannot use that, also we have two environments, so it's difficult to create client with current environment.
AI Update

In Sanity v3, the old import client from 'part:@sanity/base/client' pattern has been replaced with the useClient hook for React components and context-based access for schema functions.

For React Components

When you need the client in a React component (like custom tools, form components, or document actions), use the useClient hook:

import { useClient } from 'sanity'

function MyComponent() {
  const client = useClient({ apiVersion: '2023-05-24' })
  
  // Use the client
  const data = await client.fetch(query)
  return <div>{/* ... */}</div>
}

For Schema Files (prepare, initialValue, isUnique, etc.)

When you need the client inside schema functions like prepare, initialValue, or isUnique, you access it through the context parameter that's passed to these functions:

In prepare function:

export default defineType({
  name: 'myDoc',
  type: 'document',
  preview: {
    select: {
      title: 'title',
      id: '_id'
    },
    prepare: async (selection, context) => {
      const { getClient } = context
      const client = getClient({ apiVersion: '2023-05-24' })
      
      const parentData = await client.fetch('*[_type == "parent"][0]')
      
      return {
        title: `${parentData.title} - ${selection.title}`
      }
    }
  }
})

In initialValue:

defineField({
  name: 'author',
  type: 'reference',
  to: { type: 'author' },
  initialValue: async (props, context) => {
    const { getClient } = context
    const client = getClient({ apiVersion: '2023-05-24' })
    
    return await client.fetch(`
      *[_type == "author"][0]{
        "_type": "reference",
        "_ref": _id
      }
    `)
  }
})

In isUnique for slugs:

const isSlugUnique = async (value, context) => {
  const { client } = context  // Note: client is directly available here
  const slugs = await client.fetch(`*[defined(slug.current)].slug.current`)
  return !slugs.includes(value)
}

// In your schema:
{
  name: 'slug',
  type: 'slug',
  options: {
    source: 'title',
    isUnique: isSlugUnique
  }
}

Handling Multiple Environments

For multiple environments (different datasets), the client obtained through useClient or getClient is already configured with your current Studio environment settings. It automatically uses the correct dataset, project ID, and API version based on your sanity.config.ts configuration.

If you need to explicitly target a different dataset:

const client = useClient({ apiVersion: '2023-05-24' })
const productionClient = client.withConfig({ dataset: 'production' })

Important Notes

  • Don't use getCliClient from 'sanity/cli' in schema files or Studio components - this was causing your "Buffer is not defined" error. That method is meant for CLI scripts only.
  • The hidden property doesn't support async functions or receive context, so you'll need to use a custom field component if you need client access for conditional visibility.
  • Different schema functions receive context differently - isUnique provides client directly, while prepare and initialValue provide getClient.

This approach ensures your client is properly configured for the current Studio environment without manual configuration.

This is covered in the documentation here .
thanks very much

Sanity – Build the way you think, not the way your CMS thinks

Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.

Was this answer helpful?