Last active
February 21, 2024 16:44
-
-
Save ulises-codes/2228f7fb77ad37d3cebc82f4a1e885e5 to your computer and use it in GitHub Desktop.
Custom Sanity loader for Next JS Image component.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sanityClient, { ClientConfig } from '@sanity/client' | |
import sanityImage from '@sanity/image-url' | |
const options: ClientConfig = { | |
dataset: process.env.NEXT_PUBLIC_SANITY_DATASET, | |
projectId: process.env.NEXT_PUBLIC_SANITY_PROJECT_ID, | |
useCdn: true, | |
useProjectHostname: true, | |
} | |
const client = sanityClient(options) | |
export const imageBuilder = sanityImage(client) | |
export default client |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Image, { ImageProps } from 'next/image'; | |
import { imageBuilder } from './sanity'; | |
import type { SanityImageSource } from '@sanity/image-url/lib/types/types'; | |
interface MyImageProps extends Omit<ImageProps, 'src'> { | |
src: SanityImageSource; | |
quality?: number; | |
blur?: number; | |
} | |
export default function MyImage({ | |
quality = 80, | |
blur = 0, | |
src, | |
...props | |
}: MyImageProps) { | |
const baseURL = 'https://cdn.sanity.io/images/'; | |
return ( | |
<Image | |
{...props} | |
loader={({ width: srcWidth }) => { | |
let url = | |
imageBuilder | |
.image(src) | |
.width(srcWidth) | |
.height(Number(props.height) || 256) | |
.auto('format') | |
.quality(quality) | |
.fit('clip') | |
.url() ?? ''; | |
if (blur) { | |
url += `&blur=${blur}`; | |
} | |
return url; | |
}} | |
src={imageBuilder.image(src).url()?.toString().replace(baseURL, '') ?? ''} | |
/> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment