GROQ query: String interpolation vs parameterized queries in Sanity client

3 replies
Last updated: Oct 21, 2021
Not directly a GROQ question but is it better to do
// 1.
const id = 'my-id';
client.fetch(`_id == '${id}'`)
Or

// 2.
const id = 'my-id'
client.fetch('_id == $id', {id})
with javascript client?
AI Update

Definitely use option 2 with parameters ($id). It's the recommended best practice for several important reasons:

// ✅ Recommended approach
const id = 'my-id'
client.fetch('*[_id == $id]', {id})

// ❌ Avoid this
const id = 'my-id'
client.fetch(`*[_id == '${id}']`)

Why Parameters Are Better

Security: Parameters prevent GROQ injection attacks. Since parameters are JSON literals, they can't contain GROQ expressions that could alter your query structure. With string interpolation, if a user-supplied value contains special characters or GROQ syntax, it could potentially break or manipulate your query.

Automatic Escaping: The Sanity client automatically handles proper escaping of parameter values. If your id contains quotes or other special characters, you don't have to worry about syntax errors. String interpolation requires you to manually handle this.

Caching: Parameterized queries can be more effectively cached since the query structure remains constant while only the values change. This can improve performance in some scenarios.

Maintainability: Parameters make your code cleaner and easier to read, especially with complex queries or multiple dynamic values:

client.fetch(
  `*[_type == $type && publishedAt > $date && author._ref == $authorId]`,
  { type: 'post', date: '2024-01-01', authorId: 'abc123' }
)

This is much clearer than trying to interpolate multiple variables with template literals.

Type Safety

Parameters maintain their data types automatically. You can pass strings, numbers, booleans, arrays, or objects, and they'll be handled correctly without manual type conversion.

The GROQ parameters documentation covers all of this in detail, and it's the approach you'll see throughout Sanity's official examples and guides.

Show original thread
3 replies
Better to do the second so it's converted to a string. I believe #1 might not work as it has no quotes around it.
Oh this what a typo from me.The question was more about literal strings with JS and if it's the same in term of performance or something else.
Stitching together queries using template literals is totally fine! But for dynamic values in the query themselves I'd always use $variables and pass them into the query.

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?