Skip to content

Query image dimensions from Sanity

I haven't used Sanity before, so it took me a while to figure out, how to get photos dimensions using GROQ queries.

Here's how I've done it:

GROQ query

ts
export const query = groq`
  *[_type == "photo"] {
    image{
      "dimensions": asset->metadata.dimensions
    }
  }
`

Response

json
{
  "image": {
    "dimensions": {
      "_type": "sanity.imageDimensions",
      "aspectRatio": 0.6825192802056556,
      "height": 778,
      "width": 531
    }
  }
}

Fetch example

ts
export async function getStaticProps() {
  const dimensions = await sanityClient.fetch(query)

  return {
    props: {dimensions},
  }
}