
Grab your gear: The official Sanity swag store
Read Grab your gear: The official Sanity swag storeUnfortunately, 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.
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.
When using template strings for dynamic sorting, make sure to:
const allowedSortDirections = ['asc', 'desc'];
const sortDirection = allowedSortDirections.includes(query.sort) ? query.sort : 'asc';
const groqQuery = `*[_type == "post"] | order(date ${sortDirection})`;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!
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.
Content operations
Content backend


The only platform powering content operations
By Industry


Tecovas strengthens their customer connections
Build and Share

Grab your gear: The official Sanity swag store
Read Grab your gear: The official Sanity swag store