Get image width and height with @sanity/image-url
The @sanity/image-url package itself doesn't provide methods to get image dimensions - it's focused on building image transformation URLs. However, you can easily extract width and height from Sanity image assets using the @sanity/asset-utils package.
Using @sanity/asset-utils
Install the package:
npm install @sanity/asset-utilsThen use getImageDimensions():
import {getImageDimensions} from '@sanity/asset-utils'
const dimensions = getImageDimensions(imageAsset)
// Returns: { width: 1920, height: 1080, aspectRatio: 1.777... }You can pass either:
- The full image asset object
- Just the asset reference (
imageAsset.asset) - The asset
_refstring
Why dimensions aren't in the metadata object
Sanity always includes dimensions metadata for every image automatically (along with hasAlpha and isOpaque), but these aren't stored in the metadata field you might see in your schema configuration. As explained in the image metadata documentation, dimensions are fundamental properties that can't be disabled.
The getImageDimensions() helper extracts this information from the asset's _ref ID, which encodes the dimensions in the format image-{id}-{width}x{height}-{format}. This means you don't even need to fetch the full asset document to get dimensions - the reference string contains everything you need.
Practical example with Next.js Image
import {getImageDimensions} from '@sanity/asset-utils'
import imageUrlBuilder from '@sanity/image-url'
const builder = imageUrlBuilder(client)
function MyImage({imageAsset}) {
const {width, height} = getImageDimensions(imageAsset)
return (
<img
src={builder.image(imageAsset).width(800).url()}
width={width}
height={height}
alt="My image"
/>
)
}This approach helps prevent cumulative layout shift (CLS) by providing explicit dimensions to your image components.
Show original thread1 reply
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.