Retrieve file source/URL in GROQ query for SVG uploads

4 replies
Last updated: Aug 5, 2022
is there a way to retrieve the source of a
file
type in a groq query? (an svg uploaded via file type for example)
AI Update

Yes! You can retrieve the source/content of an SVG file uploaded via the file type, but it requires a specific approach since GROQ cannot directly return file contents.

The Solution: CORS + HTTP Fetch

You cannot directly fetch the SVG source code through a GROQ query alone. However, here's the recommended approach:

Step 1: Configure CORS

First, add your domain to your project's CORS origins:

sanity cors add http://localhost:3000

Or add it through your Sanity project dashboard. Note that credentials are not needed for these origins.

Step 2: Query for the URL

In your GROQ query, get the file URL:

*[_type == "yourDocType"] {
  "svgUrl": svgFile.asset->url
}

Step 3: Fetch the SVG Content

In your frontend code, fetch the actual SVG source:

const response = await fetch(svgUrl);
const svgContent = await response.text();
// Now you can inject it inline or manipulate it

This approach lets you inject the SVG inline and control colors/properties with CSS using currentColor and other techniques, which is often why developers want the raw SVG source.

Why Not Through GROQ?

As discussed in this community thread, while it would be convenient to fetch file contents directly through GROQ, there are practical limitations. SVGs can potentially be megabytes in size, and Sanity's asset system is optimized for storing and serving files via CDN rather than embedding them in query responses.

Alternative Approach

If you absolutely need the SVG source in your query response, you could use a text field type instead of file type and have editors paste the SVG code directly. However, this is less user-friendly and doesn't leverage Sanity's asset management capabilities.

The CORS + fetch approach gives you the flexibility of inline SVG manipulation while keeping assets properly managed in Sanity's asset pipeline.

Show original thread
4 replies
You can resolve the asset reference with
->
.
by source, I mean the raw contents of the file itself; so in this case, the actual inline svg inside the file. I didn't see it under
->
, unless I'm missing something?
Ooooh I see. No you won’t be able to have that out of the box.
alright, thank you for the quick answers 👍

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?