Usage


@nuxtjs/sanity provides key composables to interact with data from your Sanity project.

  1. useSanityQuery and useLazySanityQuery. These composables allow automatic fetching of Sanity queries.
  2. useSanity. This is the most customisable way to access data from your Sanity project, and exposes a Sanity client you can use to perform fetches or more advanced patterns (like subscribing to updates).

useSanityQuery

This is a data fetching composable that wraps useAsyncData from Nuxt 3 (see docs).

The only mandatory argument is the query for it to fetch. You can also pass params, and an options object. In addition to the options you can pass to useAsyncData, there is also a client option for specifying which configured Sanity client you would like to use.

If you pass any ref/computed parameters in params, useSanityQuery will automatically refetch the query when these parameters change.

This composable is only available in Nuxt 3. For Bridge, you will need to use useLazySanityQuery instead.

Example

const query = groq`*[_type == "post" && topic == $topic][0..10]`
const { data, refresh } = useSanityQuery(query, { topic: 'News' })

You can also type the result of your query by passing a generic to useSanityQuery:

// data will be typed as Ref<Post | null>
const query = groq`*[_type == "post" && topic == $topic][0..10]`
const { data, refresh } = useSanityQuery<Post>(query, { topic: 'News' })

useLazySanityQuery

This is an equivalent query that does not block client-side navigation and uses useLazyAsyncData under the hood. Other than that, the API is identical to useSanityQuery above.

useSanity

You can access a Sanity helper/client throught your application with the globally available useSanity() composable.

Unlike useSanityQuery and useLazySanityQuery, useSanity is also available within your Nitro server routes in exactly the same way as within your Nuxt app.

If you want to access this helper globally through $sanity - as in a prior version of this module - ensure you've set the globalHelper option to true.

Reference

fetch

This enables you to perform a GROQ query against your Sanity dataset. By default it returns a Promise<unknown> although you can customise the type of the return.

Example with asyncData

JavaScript
<script setup>
const query = groq`{ "articles": *[_type == "article"] }`

const sanity = useSanity()

const { data } = await useAsyncData('articles', () => sanity.fetch(query))
</script>
TypeScript
<script setup lang="ts">
const query = groq`{ "articles": *[_type == "article"] }`

const sanity = useSanity()

// By default it returns a `Promise<unknown>`,
// but you can customise the type of the return.
const { data } = await useAsyncData('articles', () => sanity.fetch<{ articles: Article[] }>(query))
</script>

client

You can access the underlying client with this property. This is most useful if not using the minimal client.

const query = groq`*[_type == "article"][0].title`

export default defineComponent({
  setup() {
    const sanity = useSanity()
    onMounted(() => {
      const observable = sanity.client.listen(query)
      observable.subscribe(event => {
        // Do something
      })
    })
  },
})

setToken

You can securely set the token for your Sanity client in a Nuxt plugin.

plugins/sanity.server.ts
export default defineNuxtPlugin((nuxtApp) => {
  const sanity = useSanity()
  const token = getTokenFromReq(nuxtApp.ssrContext.req)
  sanity.setToken(token)
})

config

You can access the Sanity config you have passed into the module if you need to do so (for example, with @sanity/image-url):

plugins/sanity.ts
import imageUrlBuilder from '@sanity/image-url'
export default defineNuxtPlugin(() => {
  const sanity = useSanity()
  const builder = imageUrlBuilder(sanity.config)

  function urlFor(source) {
    return builder.image(source)
  }

  return {
    provide: { urlFor }
  }
})

Additional clients

If you have configured additional clients you can access them by passing in a client name to useSanity. It returns a sanity helper, with all the same properties and methods as specified above. So, for example:

plugins/fetch.ts
export default defineNuxtPlugin(() => {
  const otherSanityHelper = useSanity('other')
  otherSanityHelper.fetch('*[type == "article"][0]')
})