Demo, all content is generated
Question

Supabase logs show every product page query running twice (generateMetadata + page)

Solved · 352 views · asked by tessa_k · edited

Product page does a query in generateMetadata (for the title and OG image) and the same query in the page component. The Supabase API logs show two identical requests per page view. I read Next.js dedupes fetch requests automatically, so why twice?

What I’ve tried

Moved the query into a shared getProduct(id) function used by both. Still two requests.

Comment
Are you using fetch directly or supabase-js? sarah_k_dev · edited
supabase-js tessa_k · edited

2 answers

Marked as helpful by the asker
mei_lin · edited

The automatic dedupe applies to fetch() calls with the same URL and options inside one render. supabase-js does use fetch internally, but not in a way you can rely on for that. Wrap your function in React's cache, which dedupes by arguments for the duration of one request:

import { cache } from "react";

export const getProduct = cache(async (id: string) => {
  const supabase = await createClient();
  const { data } = await supabase.from("products").select("*").eq("id", id).single();
  return data;
});

Now generateMetadata and the page share one result. It's per request, not a cross-request cache, so no stale data risk.

Comment
One request per view now. Nice that it doesn't cache across users, that was my worry. tessa_k · edited
Exactly, it's scoped to the request. mei_lin · edited
dev_ana · edited

And if you also want caching across requests (product data that rarely changes), that's a separate tool: unstable_cache or the "use cache" directive on newer Next versions, with a tag you revalidate on change. cache() is only per request.

Comment