DEV Community

Cover image for Next.js site breaking when Sanity is down or slow: the fix
Nayan Kyada
Nayan Kyada

Posted on Originally published at nayankyada.com

Next.js site breaking when Sanity is down or slow: the fix

If your Next.js site breaking when Sanity is down or slow is something you have seen in production, you are not unlucky, you are exposed. Most Sanity-backed sites I audit have no plan for the content API being unavailable. The result is a blank homepage, a failed deploy, or worse, an empty page that gets cached and stays empty after Sanity recovers.

This post covers the symptoms, what each one costs you, the fix path, and what to ask a developer.

Symptoms that point to a Sanity dependency problem

  • Pages return a 500 or show a generic error screen during a short Sanity incident or a network blip.
  • A page renders with no content (empty hero, no posts) and keeps doing so after Sanity is healthy again.
  • A deploy fails with a fetch error inside generateStaticParams or a page component, even though nothing in your code changed.
  • Pages feel slow only occasionally, with response times that jump from fast to many seconds and then recover.
  • Your hosting logs show functions running until they hit the platform time limit.

If you recognise two or more, the site treats Sanity as if it can never fail. No hosted API can promise that.

What ignoring it costs

An outage that should have been invisible becomes a visible one. Visitors see errors, paid traffic lands on empty pages, and search crawlers may see 5xx responses or thin content. A cached empty page is the most expensive variant because nobody gets an alert. The site looks up, monitoring is green, and the page is simply wrong until someone republishes.

A failed build is the other expensive case. If a deploy cannot complete because one fetch timed out, you cannot ship an urgent fix while the API is unhappy.

Cause 1: swallowing errors and caching the empty result

This is the most common one, and it is written with good intentions.

// app/blog/page.tsx — broken pattern
import { client } from "@/sanity/lib/client";
import { postsQuery } from "@/sanity/lib/queries";

export const revalidate = 3600;

export default async function BlogPage() {
  let posts = [];
  try {
    posts = await client.fetch(postsQuery);
  } catch (e) {
    console.error(e);
  }
  return <PostGrid posts={posts} />;
}
Enter fullscreen mode Exit fullscreen mode

When the fetch fails during a revalidation, the catch hides it, the page renders with zero posts, and Next.js treats that as a successful render. The empty version replaces the good one for the whole revalidate window.

The fix is counterintuitive: do not catch it. With ISR, if regeneration throws, Next.js keeps serving the last successfully generated page and tries again later. A thrown error is your safety net.

Cause 2: no timeout on requests

Without a timeout, a slow API ties up a build worker or a serverless function until the platform ends it. Put a ceiling on every fetch with an abort signal.

// sanity/lib/fetch.ts
import { client } from "./client";

export async function sanityFetch<T>(
  query: string,
  params: Record<string, unknown> = {},
  tags: string[] = [],
  timeoutMs = 8000
): Promise<T> {
  const signal = AbortSignal.timeout(timeoutMs);
  return client.fetch<T>(query, params, {
    signal,
    next: { tags },
  });
}
Enter fullscreen mode Exit fullscreen mode

The function throws on timeout or API error and never returns a fake empty value. That is deliberate. Callers decide what a failure means, and for cached pages the answer is almost always: fail, keep the old page.

If you see slow queries rather than an outage, the problem is usually the query itself. My post on a slow or timing-out GROQ query covers that path.

Cause 3: pages that fetch on every request

A route that reads cookies, headers, or uses cache: "no-store" hits Sanity for every visitor. Any hiccup is a visitor-facing error, and traffic spikes also multiply requests. Check which routes are actually dynamic in your build output. Marketing pages, blog posts, and landing pages rarely need to be. Make them static with tag-based revalidation from a webhook, and keep dynamic rendering for pages that genuinely personalise.

Request volume is also where bills come from. See why Sanity API requests explode on Next.js sites.

Cause 4: builds that depend on a perfect API

If every page is prerendered at build time, a single failed fetch fails the deploy. Two practical mitigations:

  1. Prerender only your most important routes in generateStaticParams and let the rest generate on first request and then cache.
  2. Keep the timeout and let errors throw, but make sure your deploy process lets you retry quickly rather than blocking on a manual step.
// app/blog/[slug]/page.tsx
export const dynamicParams = true;

export async function generateStaticParams() {
  const slugs = await sanityFetch<string[]>(
    `*[_type == "post" && defined(slug.current)][0...50].slug.current`,
    {},
    ["post"]
  );
  return slugs.map((slug) => ({ slug }));
}
Enter fullscreen mode Exit fullscreen mode

Fifty hand-picked slugs at build is a small blast radius. The remaining posts render on demand and get cached. Order by publish date so the freshest content is prebuilt.

Cause 5: no handling of a genuinely missing document

A failed fetch and a missing document are different things. A timeout should throw. A query that returns null because the slug does not exist should call notFound(). Mixing these up is how sites end up serving 404s during an outage, which search engines treat very differently from a temporary 5xx. If you are chasing odd status codes, the soft 404 post is worth reading alongside this one.

How to verify the fix

  1. In a staging environment, point the client at an invalid project ID or block the API host, then trigger revalidation on a cached page. The old content should still be served.
  2. Confirm no route returns an empty list as a success. Search your codebase for catch blocks around Sanity fetches.
  3. Check the build output and confirm that your high-traffic pages are static, not dynamic.
  4. Add an alert on error rates from your hosting platform so a failed revalidation is noticed even though visitors do not see it.
  5. Run a build with the block in place. It should fail quickly and clearly, not hang.

One related point: if editors say their changes do not appear, that is a different failure, covered in editors publishing changes that do not show on the live site.

What to ask a developer

  • What happens to a cached page if Sanity returns an error during revalidation?
  • Is there a timeout on every Sanity request, and what happens when it fires?
  • Which routes are dynamic, and why?
  • Can a deploy succeed if only part of the content is prebuilt?
  • How would I find out if a page had been cached empty?

A developer who answers these without hesitation has built production sites before. Vague answers mean the site only works on a good day.

Work I do

This kind of resilience review is part of what I do in a Performance & Sanity audit, from $800, and the fixes are usually a small number of focused changes rather than a rebuild.

Top comments (1)

Collapse
 
friga profile image
Artur Pokładek •

The catch that hides the error got me from the other side. My fallback on a failed Shopify read was "refresh everything just in case", so a throttled read did more damage than the change it was guarding against. Throwing and keeping the old page would have been the cheaper default.