How to get the URL for an image in Sanity?
Hey there! π
To get the URL for an image from Sanity, you'll want to use the @sanity/image-url package. It's a handy library that builds optimized image URLs from your Sanity image assets.
Here's how to set it up:
1. Install the package:
pnpm add @sanity/image-url2. Create a helper function:
import imageUrlBuilder from "@sanity/image-url";
import type { SanityImageSource } from "@sanity/image-url/lib/types/types";
import { client } from "./client"; // your Sanity client
const builder = imageUrlBuilder(client);
export function urlFor(source: SanityImageSource) {
return builder.image(source);
}3. Use it to get your image URL:
// Assuming your image field is called 'image'
const imageUrl = urlFor(myDocument.image).url();
// Or with transformations:
const imageUrl = urlFor(myDocument.image)
.width(800)
.height(600)
.format('webp')
.url();The cool thing about this approach is that you can chain transformation methods to resize, crop, change format, adjust quality, and more - all on the fly! Sanity's image CDN handles the transformations and caches them globally for fast delivery.
If you're using this with Next.js, don't forget to add Sanity's CDN to your allowed image domains in next.config.ts:
images: {
remotePatterns: [
{ protocol: "https", hostname: "cdn.sanity.io" },
],
}Hope this helps! Let me know if you need any clarification on the transformations or setup. π
Show original thread2 replies
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.