Sorting GROQ results using query params instead of template strings

6 replies
Last updated: Jan 28, 2026
Another question: is there a way to sort results based on query params? Currently I’m doing this:
| order(date ${query.sort})
…where
${query.sort}
is a JavaScript expression inside a template string, but I’m curious if this can be done using params.
AI Update

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:

  1. 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})`;
  1. 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 thread
6 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.

Was this answer helpful?