Unlock seamless workflows and faster delivery with our latest releases - Join the deep dive

Best practice for using literal strings in GROQ queries with JavaScript 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?
Oct 21, 2021, 10:15 AM
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.
Oct 21, 2021, 10:26 AM
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.
Oct 21, 2021, 10:27 AM
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.
Oct 21, 2021, 12:23 PM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?