Projects
Services
Migration
Blog
Alt textAlt text

Clean Your GROQ

Reading Time

4 min read

Published on

February 13, 2023

Author

Hrithik

Hrithik

The open-source query language developed by Sanity. GROQ is a game-changer in data retrieval and manipulation, offering the ability to do things like: manipulate and mutate data before your frontend is even involved.

A good example of this: I want to get data only for events that have a launch date later than October.

With GROQ, developers are empowered to describe precisely what information their applications require without any limitations. This opens up a whole new world of possibilities, enabling the creation of sophisticated and highly tailored responses to complex queries.

One of the critical strengths of GROQ is its ability to seamlessly join information from multiple sets of documents, making it an ideal solution for large and complex data structures. This means that developers can quickly stitch together a highly specific response with only the exact fields they need, resulting in a highly optimised and efficient solution.

Problems with GROQ

One issue that is often discussed with GROQ is that its syntax can become unwieldy and difficult to manage as queries become more complex, especially when using long and repetitive fragments. This can reduce the code's readability and maintainability, making it difficult for developers to modify and update their queries efficiently. This issue emphasizes the importance of using best practices and effective coding techniques when using GROQ to keep queries manageable and easy to understand even as they become more complex.

E.g:

const pageQuery = groq` *[_type == "page" && slug.current == $slug][0]{ ..., pageBuilder[]{ ..., buttons[]{ ..., url{ ..., internal->{ slug } } } categories->{ title }, richText[]{ ..., markDefs[]{ ..., customLink{ ..., internal->{ slug } } } }, link{ ..., internal->{ slug } } } } `

This query, for example, is extremely difficult to comprehend. We can refactor this to make it more readable and clean.

Understanding GROQ

GROQ is a query language, but it is just plain text in the javascript environment, which we can use to create a refactoring approach.

First, identifying the repetitive parts

As we can see from the above query and list of queries, some blocks are abstractable, such as rich text, links, buttons, etc.

Create blocks

This entire rich text can be a separate GROQ fragment, such as

const richText = groq` richText[]{ ..., markDefs[]{ ..., customLink{ ..., internal->{ slug } } } }`;

Combine blocks into into fragments

Alternatively, this variable can be a function that takes in the projection parameters and generates a GROQ fragment dynamically.

If you have a page builder (component list), you can have levels of fragments. This could also be a separate fragment, such as

const pageBuilder = groq` pageBuilder[]{ ..., ${[buttons,categories,richText,link].join(",")} }`;

Combine fragments into into query

Using this method, we can clean up our GROQ queries. From the above GROQ query, we can now refactor it as follows.

export const pageQuery = groq` *[_type == "page" && slug.current == $slug][0]{ ..., ${pageBuilder} }`;

You can also create a reference extend function that will make your groq query more readable. you can look into it here

VSCode tooling

If you're just getting into GROQ make sure you download the Sanity.io VSCode extension...

Sanity.io GROQ syntax highlighter as well as GROQ executer

It's going to save you hours. It lets you do two things:

  1. Execute GROQ queries
  2. Give you GROQ syntax highlighting

Execute GROQ queries

If you're struggling with the first and you're in a mono-repo environment, you can simply add your Sanity instance at the root of your Next/Remix/Gatsby environment.

What's really clever is it actually lets you pass in variables, like the $slug:

export const projectQuery = groq` *[_type == "project" && slug.current == $slug][0]{ ..., categories[]->{ ... }, pageBuilder[]{ ..., ${buttons}, ${categories}, ${richText}, ${link} } }`;

GROQ Syntax Highlighting

Just by adding the:

groq``

You're going to get all the syntax highlighting goodness.

A note about prettier

There aren't any official solutions right this second to be able to prettify GROQ within JavaScript. That being said, these community options exist:

https://github.com/alevroub/prettier-plugin-groq

https://github.com/mcky/prettier-plugin-groq

However, if you're looking to quickly format your GROQ query before you clean it up with the techniques above there is something official you can use (and it's fantastic 🎉).

https://github.com/sanity-io/groq-cli

Want to get better at GROQ?

Okay, so now you've seen what you can to tidy up GROQ, but there's always the opportunity to improve your GROQ knowledge. That's why we recommend checking out the free GROQ course on egghead.io.

Don't say we don't ever give you anything...

Any more questions?

We're always trying to improve knowledge around Sanity, GROQ & Next.js. We've tried to collate a bunch of questions we wanted answers to when we first started working with the composable content cloud. If you have any more questions you'd like answers to, drop me an email at hello@roboto.studio

Get in touch

Learning GROQ?

We're not claiming to be masters of GROQ, but we know a thing or two about scaling a headless content management system like Sanity. Why not get in touch to see how we could get your website running clean as a whistle

Services

Legal

Like what you see ?

Sign up for a 30 min chat and see if we can help

© 2024 Roboto Studio Ltd - 11126043

Roboto Studio Ltd,

86-90 Paul Street,

London, EC2A 4NE

Registered in England & Wales | VAT Number 426637679