GROQ Queries in Sanity: From Basics to Advanced Optimization
Picture this: you’re building a headless site with Sanity and Next.js. Your content model has grown—6 document types, complex relationships, dynamic zones. On the very first promo landing page, you hit frustration: N+1 queries, nested fetches, and a “related articles” block that takes 7 seconds to load. We faced this on a major media portal project: 12-second load time, 47 separate requests. The solution was a single GROQ query that cut time to 0.8 seconds. Sound familiar? We’ve handled this more than once.
GROQ (Graph-Relational Object Queries) is not REST, not SQL, not GraphQL. It’s more flexible than REST for complex structures: projections, joins via ->, conditional selections, aggregations—all in one query without N+1 issues. Our team, with over five years of Sanity experience, has tuned dozens of projects, cutting API load by up to three times. In this article, we’ll show you how to write GROQ queries properly, avoid common mistakes, and optimize speed.
Why GROQ Instead of REST or GraphQL?
Sanity offers an HTTP API out of the box, but custom endpoints for every page lead to chaos. GROQ gives you a unified syntax for any retrieval. Compare:
| Criterion |
GROQ |
REST API |
GraphQL |
| Queries per page |
1 (complex) |
5–15 (multiple) |
1–3 (but N+1 with pagination) |
| Join (resolve) |
Built-in -> |
Requires separate queries |
Requires batch loading |
| Conditional projections |
Built-in _type == "..." => |
None, must filter client‑side |
Yes, via fragments |
| Aggregations (count, unique) |
Built-in functions |
None, need server hooks |
Yes, but more complex |
GROQ is 2–3 times faster when fetching pages with multiple block types—proven on our projects.
How to Properly Execute Join Queries in GROQ?
Joins in GROQ are done with the resolve operator ->. It replaces relational JOINs and lets you pull related documents without extra queries. Step by step:
- Identify the reference field (e.g.,
author of type reference).
- Use
-> after the field: author->{name}.
- Limit fields with a projection to avoid loading unnecessary data.
A single query returns posts together with author data:
*[_type == "post"]{
title,
"author": author->{name, "avatar": image.asset->url}
}
Limit resolve depth—two to three levels is enough in practice.
Case Study: Optimizing Blog Load Time
A client came to us with a problem: their blog page on Sanity + Next.js loaded in 12 seconds. We found that for the article list, 47 separate queries were executed (each post fetched author, categories, related articles, and metadata). The solution was a single GROQ query with resolve and pagination:
*[_type == "post" && status == "published"] | order(publishedAt desc) [$start...$end] {
_id, title, "slug": slug.current, publishedAt,
"author": author->{ name, "avatar": image.asset->url },
"categories": categories[]->{ title, "slug": slug.current },
"excerpt": string::slice(pt::text(body), 0, 200)
}
count(*[_type == "post" && status == "published"])
Result: 1 query, 0.8 seconds instead of 12. Plus a bonus—total article count for pagination. We build such optimizations into our standard query set.
What's Included in GROQ Query Setup
We offer turnkey development—from audit to documentation. The package includes:
- Analysis of your content model and identification of bottlenecks (N+1, redundant queries)
- Design of universal queries for 4–6 page types: landing pages, lists, detail cards, search
- Implementation with TypeScript typing—each query wrapped in a groq tag returning the correct type
- Optimization via projections, resolve, and aggregations—minimal payload
- Integration with Sanity Vision for debugging and testing
- Team training—documentation and templates handed over
The standard set covers basic syntax, parameterized queries, Portable Text, pagination, full-text search with Algolia (if needed), and reverse lookups (refs). All tested on 30+ projects.
Common GROQ Writing Mistakes
- String concatenation instead of parameters—risk of injection, no caching. Always use
$variable.
- Excessive resolve depth—more than three levels kills performance. Stick to 2–3.
- Ignoring
defined() when checking fields—fields can be null in Sanity.
- Missing pagination on lists over 100 items. Use
[$start...$end].
- Forgetting the count—return both array and count simultaneously.
Example: Full Query Set (with Typing)
import { createClient } from '@sanity/client'
import { groq } from 'next-sanity'
const postQuery = groq`
*[_type == "post" && slug.current == $slug][0] {
_id, title, "slug": slug.current, publishedAt, body,
"author": author->{ name, "image": image.asset->url },
"relatedPosts": *[_type == "post" && references(^.categories[]._ref) && _id != ^._id] | order(publishedAt desc) [0...3] {
title, "slug": slug.current
}
}
`
type PostResult = {
_id: string
title: string
slug: string
publishedAt: string
body: any[]
author: { name: string; image: string }
relatedPosts: { title: string; slug: string }[]
}
const post = await client.fetch<PostResult>(postQuery, { slug: params.slug })
Full GROQ documentation is available on the official Sanity site. If you want to speed up development—our engineers are ready to help with setup. Contact us to discuss your project and find the optimal solution. Get a consultation from a Sanity engineer.
Timeline and Cost
Developing a set of queries takes one to three days depending on model complexity. Cost is determined individually. We don’t hide numbers: reach out—we’ll assess your project in one business day. We guarantee the queries will be optimized for Core Web Vitals and won’t cause N+1 issues.
Headless CMS: Strapi, Directus, Sanity, Contentful, Drupal
Traditional CMS works well until the designer says “I want scroll animation with parallax,” the frontend says “we need React,” and the SEO specialist asks “why is TTFB 3.4 seconds?” At that point, monolithic architecture starts to hinder everyone. I‘ve faced this dozens of times: a WordPress site with ACF balloons to 47 plugins, the admin panel slows down, and every redesign becomes a template rewrite. Headless CMS separates content management from presentation. Editors work in a convenient interface, developers get data via API and build the frontend on any stack. Sounds simple. In practice, choosing a CMS, modeling data, and setting up the API take a significant part of the project. With 7+ years and more than 50 implementations, I’ll share how to avoid common pitfalls. Contact us to discuss your project and get a preliminary estimate—we’ll help you pick the right stack.
What are the key benefits of headless CMS over monolithic?
Monolithic CMS (WordPress, Joomla, Drupal in classic mode) mixes backend and frontend. Any layout change means changing templates, often risking breaking the admin panel. Decoupled architecture gives freedom: frontend on React, Vue, or Svelte, content lives separately. Result: improved load speed (LCP often drops from 4–6 s to 1–1.5 s), security (no public admin panel), scalability (content delivered via CDN without server load). Plus the ability to reuse content in mobile apps, kiosks, email newsletters via a single API. A client we recently helped saw LCP improve from 6.2 s to 1.1 s — a 5.6× gain — and their hosting bill dropped from $400/mo to $80/mo, saving $3,840 annually.
How to choose a headless CMS for your project?
No universal tool exists. The choice depends on team, content complexity, and infrastructure. Let’s break down the key options.
Strapi — open-source, self-hosted, Node.js. Suitable for teams needing data control and API customization. Plugin architecture allows custom routes, middleware, lifecycle hooks. REST and GraphQL out of the box. Deploys in about an hour — three times faster than Drupal. Weakness: versions v4 and v5 are incompatible, migration is painful. Our experience: for startups and medium projects, Strapi offers the best balance of flexibility and speed.
Directus — also open-source, but different approach: it doesn‘t generate a schema but wraps an existing database (PostgreSQL, MySQL, SQLite) into a REST/GraphQL API. If you already have a database, Directus connects without migrations. Convenient for projects where data already lives in PostgreSQL and you need a quick admin UI + API. Saves up to 30% integration time.
Sanity — cloud CMS with real-time editor. Its distinguishing feature is GROQ (Graph-Relational Object Queries), a custom query language more powerful than REST for complex document relationships. Portable Text for structured content. Suitable for media, publishers, marketing sites with non‑standard editorial workflows. Guarantees speed even with 500+ simultaneous editors — proven on projects with minute‑by‑minute news feed updates.
Contentful — enterprise cloud CMS. Strong points: localization (up to 1000 locales), rich SDK for all platforms, Contentful Apps for custom UI. Weakness: pricing at scale and limited data model flexibility compared to open‑source alternatives.
Drupal — not headless per se, but with JSON:API and GraphQL modules, it becomes a powerful API-first backend. Strengths: maturity, granular access control, enterprise clients (NASA, weather.com). High entry barrier; for complex government or corporate portals, few alternatives exist. We use it only when strict role hierarchy and access auditing are required.
| CMS |
Hosting |
API |
Best Use Case |
| Strapi |
Self-hosted / Cloud |
REST, GraphQL |
Startups, customization |
| Directus |
Self-hosted / Cloud |
REST, GraphQL |
Wrapper for existing DB |
| Sanity |
Cloud |
GROQ, GraphQL |
Media, complex content |
| Contentful |
Cloud |
REST, GraphQL |
Enterprise, localization |
| Drupal |
Self-hosted |
JSON:API, GraphQL |
Government, complex permissions |
Consequences of poor content modeling
Content modeling is critical. Mistakes at this stage are costly. A typical problem: a body field of type rich text for everything. Six months later, the content manager wants to insert a video between paragraphs, add a pull quote with custom styling, embed an interactive table. Rich text can‘t handle that. Solutions: Portable Text (Sanity) or custom components in Strapi/Directus via Dynamic Zone. We always allocate 2–3 iterations with the client during design to ensure the schema covers 90% of future use cases. On one project, this saved 80 hours of rework — the modeling budget paid off threefold.
How we build projects on headless CMS
Frontend for headless CMS almost always uses Next.js (App Router) or Nuxt. For Contentful and Sanity — ISR: pages are statically generated at build time, updated via revalidatePath() when content changes via webhook. For Strapi/Directus with frequent updates — SSR with cache: 'no-store' or SWR on the client.
Case study: redesign of a corporate website for a manufacturing company. Previous site: WordPress with ACF, 200+ pages, 4 languages. Problems: TTFB 3.8 s, editors complained about slow admin. Migrated to Strapi (self-hosted, PostgreSQL), Next.js App Router. Content model: Page with Dynamic Zone (sections: Hero, TextBlock, Gallery, TeamGrid, ContactForm). Localization via Strapi i18n plugin + next-intl on frontend. Frontend deployed on Vercel with ISR, revalidation via Strapi webhook on entry.publish. According to the client: TTFB dropped from 3.8 s to 180 ms (static with CDN) — a 21× improvement. Editors got a clean interface without 47 plugins. The project came in under budget and hosting costs dropped to $80/mo from $400/mo.
Implementation process broken into stages:
- Content needs audit — collect all content types, relationships, localization requirements, integrations.
- Data schema design — create models, fields, validation, access roles. Document in Swagger/OpenAPI.
- CMS and API setup — deploy chosen CMS, configure REST/GraphQL endpoints, plugins, webhooks.
- Frontend development — connect Next.js/Nuxt, configure ISR/SSR, section components, routing.
- Content migration (if legacy) — automated loading via API or scripts.
- Testing — check API endpoints, regression, load testing, Core Web Vitals.
- Deployment — configure CDN, SSL, CI/CD, monitoring.
How long does implementation take?
The standard path includes all stages. Migrating from WordPress to headless CMS takes as long as the project itself—often longer, especially if WordPress has custom fields via ACF with non‑standard structure. Our typical timelines:
| Project Type |
Timeline |
| Simple site on Strapi + Next.js |
4–8 weeks |
| Multilingual corporate site |
8–16 weeks |
| Migration from WordPress to headless |
+4–8 weeks additional |
| Drupal enterprise portal |
3–6 months |
Cost is calculated individually after a brief. Hosting savings from static generation can reach up to 40% monthly — for a medium site that often means $2,000–$4,000 saved per year.
Non‑obvious considerations when choosing a headless CMS
- Check if the CMS supports multisite — if you plan multiple domains, many open‑source solutions can‘t separate content by domain without workarounds.
- Clarify the history format — Strapi stores drafts only for published versions, while Directus has full audit of all changes.
- Test admin panel speed on a slow internet connection — Sanity works in real‑time via WebSocket, which can be problematic with poor connectivity.
- Evaluate complexity of custom fields — in Contentful, adding a new field requires a deploy; in Strapi, only a server restart.
- Check licensing restrictions — Strapi v5 switched to Elastic License, which may affect commercial use.
What is included
- Data schema and API documentation (Swagger/OpenAPI)
- Configured admin panel with access rights
- Editor training (2‑hour session)
- Test environment during development
- 1‑month warranty on bugs after launch
- Post‑release support (including hotfixes 24/7)
Headless CMS development is not just a tool replacement but a paradigm shift in content management. We help make this transition without downtime or data loss. Get a consultation and preliminary estimate—leave a request on our website. Order headless CMS implementation with guaranteed results.