I'm having a hard time doing a client side query, tried using the HTTP API but the URI encoding for '&&' and '->' seemed to be causing problems so I tried importing...
I can help you with querying Sanity from the browser! The issue you're experiencing with URL encoding for GROQ operators like && and -> is a common challenge. Here's the solution:
Use POST Instead of GET
The best approach for client-side queries is to use POST requests instead of GET with the query in the request body. This completely avoids URL encoding issues with GROQ's special characters.
Here's how to do it with a simple fetch call:
const projectId = 'your-project-id'
const dataset = 'production'
const query = `*[_type == "post" && defined(slug)]{title, slug}`
fetch(`https://${projectId}.api.sanity.io/v2021-10-21/data/query/${dataset}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ query })
})
.then(res => res.json())
.then(data => console.log(data.result))This approach:
- Sends the query in the POST body as JSON (no URL encoding needed)
- Works perfectly with
&&,->, and all other GROQ operators - Is simpler than wrestling with
encodeURIComponent
Using the JavaScript Client
If you prefer using @sanity/client in the browser, it's actually straightforward and handles all the encoding for you automatically:
import {createClient} from '@sanity/client'
const client = createClient({
projectId: 'your-project-id',
dataset: 'production',
useCdn: true,
apiVersion: '2021-10-21',
})
// The client handles all encoding automatically
client.fetch(`*[_type == "post" && defined(slug)]{title, slug}`)
.then(posts => console.log(posts))For Sapper specifically, you can import the client in your routes/components as needed. The client works in both server-side and client-side contexts.
Why POST is Better
When using the HTTP API with GET requests and query parameters, you need to encode special characters, which can get messy:
&&becomes%26%26->becomes-%3E- Complex queries become unreadable URLs
The POST method with JSON body sidesteps all of this and is the recommended approach for complex GROQ queries from the browser, as documented in the query aspects guide.
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.