Don't fetch your own API from a server component at all. Both run on the server, so you are making an HTTP request to yourself, and during next build there is nobody listening, hence ECONNREFUSED.
Move the logic into a plain function and call it from both places:
// lib/stats.ts
export async function getStats(userId: string) {
const supabase = await createClient();
const { data } = await supabase.from("orders").select("total").eq("user_id", userId);
return summarize(data ?? []);
}// app/dashboard/page.tsx
const stats = await getStats(user.id);Keep /api/stats only if something outside your app (a mobile app, a client component) needs it; it can call getStats too. One less network hop, no URL juggling, and it works in every environment.