Retrieve file source/URL in GROQ query for SVG uploads
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:3000Or 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 itThis 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 thread4 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.