Unlock seamless workflows and faster delivery with our latest releases - Join the deep dive

Using `urlFor()` to generate OG image URL in Sanity

5 replies
Last updated: Jun 8, 2023
So if Im using type
image
to populate my OG Image in Sanity. When I query the image asset what should I be using for the path? I see in
asset
theres
url
which is the cd.sanity.io url,
publicUrl
that returns a long string. Is there a preferred way to do the OG image here?
Jun 8, 2023, 12:16 PM
You can look at building a "urlFor()"

https://www.sanity.io/docs/image-url
it let's you grab the image based the size you need.
Jun 8, 2023, 1:51 PM
This should get you the link you need if you just want to grab the base url
*[ _type == "pages" ]{
"imageUrl": image{
asset->{
url
}
}
}
Jun 8, 2023, 1:54 PM
I think the preferred way is to use the URL builder.
Jun 8, 2023, 1:58 PM
Yeah I've used urlFor and pass it the asset id and then use the generated url as the value for the og url field.
Jun 8, 2023, 3:03 PM
For some reason when trying to implement the Sanity client in Gatsby after using the plugin
gatsby-source-sanity
the component wont even render anything. _sanityClient.js_:
const { createClient } = require('@sanity/client')
import imageUrlBuilder from '@sanity/image-url'

const client = createClient({
  projectId: process.env.SANITY_STUDIO_PROJECT_ID,
  dataset: process.env.SANITY_STUDIO_PROJECT_DATASET,
  useCdn: false, // set to `false` to bypass the edge cache
  apiVersion: process.env.SANITY_API_VERSION, // use current date (YYYY-MM-DD) to target the latest API version
  token: process.env.SANITY_SECRET_TOKEN, // Only if you want to update content with the client
})

const builder = imageUrlBuilder(client)

export const clientCheck = client
  .fetch(`count(*)`)
  .then(data => console.log(`Number of documents: ${data}`))
  .catch(console.error)

export const getOgImage = async source => {
  return builder.image(source)
}
Jun 8, 2023, 4:16 PM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?