Get current dataset and project ID in Sanity without hardcoding

5 replies
Last updated: Apr 27, 2020
Is there a way to get the current dataset and project id inside the code, without hardcoding it? To use on BlockContent, to set imageOptions
AI Update

Yes! You can use the useClient hook to get the current project ID and dataset without hardcoding them. The hook returns a configured Sanity Client instance that you can query for this information.

Here's how to do it:

import { useClient } from 'sanity'

function MyComponent() {
  const client = useClient({ apiVersion: '2023-05-24' })
  
  // Get the project ID and dataset from the client config
  const projectId = client.config().projectId
  const dataset = client.config().dataset
  
  // Use them in your BlockContent imageOptions
  const imageOptions = {
    projectId,
    dataset
  }
  
  return (
    <BlockContent
      blocks={yourContent}
      imageOptions={imageOptions}
      // ... other props
    />
  )
}

The useClient hook returns a fully configured Sanity Client instance that inherits the project ID and dataset from your Studio's configuration. You can access these values by calling client.config() which returns an object containing the client's configuration properties.

Important note: Since useClient is a React hook, it must be called inside a React component or custom hook - you can't use it at the module level or outside of React's component tree.

If you're using @sanity/client directly (outside of Studio), you can also get the configuration from any client instance:

import { createClient } from '@sanity/client'

const client = createClient({
  projectId: 'your-project-id',
  dataset: 'production',
  // ... other config
})

// Later, retrieve the config
const config = client.config()
console.log(config.projectId, config.dataset)

This approach ensures your configuration stays DRY (Don't Repeat Yourself) and makes it easier to maintain when working across different environments or datasets.

Show original thread
5 replies
In the studio or the frontend?
in the studio
In the studio or the frontend?
import client from 'part:@sanity/base/client'

const config = client.config()
There you go!
awesome thanks!

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?