How to get the URL for an image in Sanity?

2 replies
Last updated: Nov 8, 2023
Hello, everyone! how can I get the URL for this Image? πŸ™‚ thank you.
AI Update

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-url

2. 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 thread
2 replies
should be something like
hero[]{heroImage[]{asset->{url}}}
The above assumes
hero
is an array which I think it's not, so I suggest:
heroSection->{
   hero{
    ...,
    "heroImageURL": heroImage->asset.url
   }

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.

Was this answer helpful?