Using @sanity/asset-utils to load SVGs in Next.js

8 replies
Last updated: Jun 7, 2023
Can we tell GROQ to format SVG to JPG? Sanity Url image builder doesn’t like svgs in nextjs.
AI Update

Good news! Yes, you can convert SVG images to JPG (or PNG) using Sanity's image CDN, and you don't need GROQ to do it directly—though you can handle it in your queries.

The Sanity image transformation API supports format conversion using the fm parameter. Simply add ?fm=jpg or ?fm=png to your image URL to convert SVG to a rasterized bitmap format:

https://cdn.sanity.io/images/[project-id]/[dataset]/[asset-id]-[dimensions].svg?fm=png

Handling it in GROQ

If you want to conditionally convert SVGs in your GROQ queries (which is great for automation), you can check the file extension and append the format parameter. Here's an example from the Sanity community:

*[_type == 'blogPost'] {
  images[] {
    asset->{
      url,
      extension == 'svg' => {
        'url': url + '?fm=png'
      }
    }
  }
}

This pattern checks if the asset extension is svg, and if so, reassigns the url field with the ?fm=png parameter appended. You can use ?fm=jpg instead if you prefer JPEG output.

Next.js Image Component Workaround

If you're specifically dealing with Next.js's <Image> component rejecting SVGs, you have two options:

  1. Use the conversion approach above - Convert SVGs to PNG/JPG via the CDN before passing to next/image
  2. Enable SVG support in Next.js - Add dangerouslyAllowSVG: true to your next.config.js:
module.exports = {
  images: {
    remotePatterns: [
      {
        protocol: 'https',
        hostname: 'cdn.sanity.io',
      },
    ],
    dangerouslyAllowSVG: true,
    contentSecurityPolicy: "default-src 'self'; script-src 'none'; sandbox;",
  },
}

The CDN conversion approach is generally safer and more performant since it lets Sanity's globally-distributed CDN handle the transformation and caching at the edge.

format xml into byte data? no. whats the issue you’re having?
Using the Sanity image urlBuilder wont load svg’s inside my next js application
pretty sure you just need to use the assetUrl helper
I cant remember what its called
@sanity/asset-utils
either
buildFileUrl()
or
getFileAsset()
Thanks Parker! i will check this out 👍 🙏 :saluting_face:

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?