Sorting GROQ results using query params instead of template strings
Unfortunately, you cannot pass the order direction (asc or desc) as a parameter in GROQ. The direction keywords are part of the GROQ syntax itself and must be written directly in the query string. So your current approach using template strings is actually the correct way to handle dynamic sorting:
| order(date ${query.sort})This limitation is mentioned in the Sanity documentation on the order() function, which notes that while you can pass document types and reference tags as parameters to GROQ queries, passing the order expression itself as a parameter (like $orderBy containing "publishedAt desc") doesn't work as expected.
Why This Happens
GROQ params are designed for values that get substituted into the query, not for syntax elements like asc/desc keywords or field names in the order clause. The parser expects these to be literal parts of the query structure.
Best Practices for Your Approach
When using template strings for dynamic sorting, make sure to:
- Validate the input to prevent injection issues:
const allowedSortDirections = ['asc', 'desc'];
const sortDirection = allowedSortDirections.includes(query.sort) ? query.sort : 'asc';
const groqQuery = `*[_type == "post"] | order(date ${sortDirection})`;- Consider allowing field name variation too:
const allowedFields = ['date', 'title', 'publishedAt'];
const allowedDirections = ['asc', 'desc'];
const field = allowedFields.includes(query.field) ? query.field : 'date';
const direction = allowedDirections.includes(query.sort) ? query.sort : 'asc';
const groqQuery = `*[_type == "post"] | order(${field} ${direction})`;This template string approach is the standard pattern for dynamic ordering in GROQ, so you're doing it the right way!
Show original thread6 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.