Skip to content

The Open Standard for Generative UI

Fix missing GitHub star count in site header (#1249)

rahuldovald61038f85659
diff --git a/docs/app/(home)/components/GitHubButton/GitHubButton.tsx b/docs/app/(home)/components/GitHubButton/GitHubButton.tsx
index 666e6a92a..26cf42009 100644
--- a/docs/app/(home)/components/GitHubButton/GitHubButton.tsx
+++ b/docs/app/(home)/components/GitHubButton/GitHubButton.tsx
@@ -1,7 +1,8 @@
"use client";
-import type { JSX, ReactNode } from "react";
import { GitHubIcon, useGitHubStarCount } from "@/components/brand-logo";
+import { GITHUB_STAR_FALLBACK } from "@/lib/github-stars";
+import type { JSX, ReactNode } from "react";
import { PillLink } from "../Button/Button";
import styles from "./GitHubButton.module.css";
@@ -12,22 +13,12 @@ import styles from "./GitHubButton.module.css";
/** Default OpenUI repo URL — was duplicated as a GitHubBanner default. */
export const DEFAULT_GITHUB_REPO_URL = "https://github.com/thesysdev/openui";
-/** Fallback star count used before the live count resolves (was `?? 7016`). */
-export const GITHUB_STAR_FALLBACK = 7016;
-
-/** Strip the `https://github.com/` prefix to get `owner/repo`. */
-export function parseRepoFromUrl(href: string): string {
- return href.replace(/^https?:\/\/github\.com\//, "");
-}
-
/**
* Canonical animated star-count hook. Wraps brand-logo's `useGitHubStarCount`
- * (count-up via requestAnimationFrame) and folds in the repo-parse + fallback
- * that Hero duplicated in two places.
+ * (count-up via requestAnimationFrame) with a visible fallback.
*/
-export function useGitHubStars(hrefOrRepo: string, options?: { fallback?: number }): number {
- const repo = hrefOrRepo.includes("github.com/") ? parseRepoFromUrl(hrefOrRepo) : hrefOrRepo;
- const count = useGitHubStarCount(repo);
+export function useGitHubStars(options?: { fallback?: number }): number {
+ const count = useGitHubStarCount();
return count ?? options?.fallback ?? GITHUB_STAR_FALLBACK;
}
@@ -136,7 +127,7 @@ function DesktopGlowVariant({
keepBlack?: boolean;
arrow?: ReactNode;
}): JSX.Element {
- const count = useGitHubStars(href);
+ const count = useGitHubStars();
const label = String(count);
return (
@@ -178,7 +169,7 @@ function MobileBannerVariant({
arrow?: ReactNode;
classes?: GitHubButtonProps["classes"];
}): JSX.Element {
- const count = useGitHubStars(href);
+ const count = useGitHubStars();
return (
<a href={href} target="_blank" rel="noopener noreferrer" className={cx(className)}>
diff --git a/docs/app/(home)/sections/TweetWallSection/TweetWallStats.tsx b/docs/app/(home)/sections/TweetWallSection/TweetWallStats.tsx
index 9e8b16831..20eaf1e8b 100644
--- a/docs/app/(home)/sections/TweetWallSection/TweetWallStats.tsx
+++ b/docs/app/(home)/sections/TweetWallSection/TweetWallStats.tsx
@@ -3,8 +3,6 @@
import { GitHubMark, useGitHubStars } from "../../components/GitHubButton/GitHubButton";
import styles from "./TweetWallSection.module.css";
-const GITHUB_REPO = "thesysdev/openui";
-
function NpmMark() {
return (
<svg viewBox="0 7 24 10" width="36" height="15" fill="currentColor" aria-hidden="true">
@@ -14,7 +12,7 @@ function NpmMark() {
}
export function TweetWallStats() {
- const stars = useGitHubStars(GITHUB_REPO);
+ const stars = useGitHubStars();
return (
<div className={styles.stats}>
diff --git a/docs/app/api/github-stars/route.ts b/docs/app/api/github-stars/route.ts
new file mode 100644
index 000000000..d5f14cbd8
--- /dev/null
+++ b/docs/app/api/github-stars/route.ts
@@ -0,0 +1,38 @@
+import {
+ GITHUB_STAR_FALLBACK,
+ OPENUI_GITHUB_REPOSITORY,
+ readGitHubStarCount,
+ type GitHubStarsResponse,
+} from "@/lib/github-stars";
+
+const GITHUB_API_URL = `https://api.github.com/repos/${OPENUI_GITHUB_REPOSITORY}`;
+const CACHE_CONTROL = "public, max-age=300, s-maxage=3600, stale-while-revalidate=86400";
+
+function json(body: GitHubStarsResponse): Response {
+ return Response.json(body, { headers: { "Cache-Control": CACHE_CONTROL } });
+}
+
+export async function GET(): Promise<Response> {
+ const headers: HeadersInit = {
+ Accept: "application/vnd.github+json",
+ "X-GitHub-Api-Version": "2022-11-28",
+ };
+ const token = process.env.GITHUB_TOKEN?.trim();
+ if (token) headers.Authorization = `Bearer ${token}`;
+
+ try {
+ const response = await fetch(GITHUB_API_URL, {
+ headers,
+ signal: AbortSignal.timeout(3000),
+ next: { revalidate: 3600 },
+ });
+ if (!response.ok) return json({ stars: GITHUB_STAR_FALLBACK, source: "fallback" });
+
+ const stars = readGitHubStarCount(await response.json());
+ if (stars === null) return json({ stars: GITHUB_STAR_FALLBACK, source: "fallback" });
+
+ return json({ stars, source: "github" });
+ } catch {
+ return json({ stars: GITHUB_STAR_FALLBACK, source: "fallback" });
+ }
+}
diff --git a/docs/components/brand-logo.tsx b/docs/components/brand-logo.tsx
index 4176b0d23..812ca57c7 100644
--- a/docs/components/brand-logo.tsx
+++ b/docs/components/brand-logo.tsx
@@ -1,6 +1,7 @@
"use client";
import svgPaths from "@/imports/svg-urruvoh2be";
+import { GITHUB_STAR_FALLBACK, type GitHubStarsResponse } from "@/lib/github-stars";
import { AnimatePresence, motion } from "motion/react";
import Link from "next/link";
import { useEffect, useState } from "react";
@@ -109,48 +110,43 @@ export function OpenUILogo({ variant = "light" }: { variant?: LogoVariant }) {
// GitHub Star Button
// ---------------------------------------------------------------------------
-// Module-level cache + in-flight dedup for the star count, keyed by repo. Every
-// star button on the page (header, hero, tweet-wall stats) shares one request
-// instead of each firing its own. Without this the home page made ~5 identical
-// calls per load and exhausted GitHub's 60-req/hr unauthenticated limit, after
-// which every counter fell back to the default. The cache also survives client-
-// side navigation, so returning to a page doesn't refetch.
-const starCountCache = new Map<string, number>();
-const starCountInflight = new Map<string, Promise<number | null>>();
-
-function fetchGitHubStarCount(repo: string): Promise<number | null> {
- const cached = starCountCache.get(repo);
- if (cached !== undefined) return Promise.resolve(cached);
-
- let inflight = starCountInflight.get(repo);
- if (!inflight) {
- inflight = fetch(`https://api.github.com/repos/${repo}`)
+// Module-level cache + in-flight dedup for OpenUI's star count. Every
+// star button on the page (header, hero, tweet-wall stats) shares one request.
+// The same-origin endpoint adds server/CDN caching so visitors do not spend
+// GitHub's unauthenticated API allowance individually.
+let starCountCache: number | null = null;
+let starCountInflight: Promise<number | null> | null = null;
+
+function fetchGitHubStarCount(): Promise<number | null> {
+ if (starCountCache !== null) return Promise.resolve(starCountCache);
+
+ if (!starCountInflight) {
+ starCountInflight = fetch("/api/github-stars")
.then((res) => {
if (!res.ok) throw new Error(`GitHub star count fetch failed: ${res.status}`);
- return res.json();
+ return res.json() as Promise<GitHubStarsResponse>;
})
.then((data): number | null => {
- const target: unknown = data.stargazers_count;
- if (typeof target !== "number") return null;
- starCountCache.set(repo, target);
+ const target = data.stars;
+ if (typeof target !== "number" || !Number.isFinite(target) || target < 0) return null;
+ starCountCache = target;
return target;
})
.catch(() => null)
.finally(() => {
- starCountInflight.delete(repo);
+ starCountInflight = null;
});
- starCountInflight.set(repo, inflight);
}
- return inflight;
+ return starCountInflight;
}
-export function useGitHubStarCount(repo: string) {
- const [count, setCount] = useState<number | null>(null);
+export function useGitHubStarCount() {
+ const [count, setCount] = useState<number | null>(GITHUB_STAR_FALLBACK);
useEffect(() => {
let cancelled = false;
- void fetchGitHubStarCount(repo).then((target) => {
+ void fetchGitHubStarCount().then((target) => {
if (cancelled || target === null) return;
const startCount = Math.max(target - 50, 0);
const startTime = performance.now();
@@ -170,7 +166,7 @@ export function useGitHubStarCount(repo: string) {
return () => {
cancelled = true;
};
- }, [repo]);
+ }, []);
return count;
}
@@ -230,7 +226,7 @@ export function GitHubStarButton({
isScrolled?: boolean;
}) {
const [isHovered, setIsHovered] = useState(false);
- const starCount = useGitHubStarCount(repo);
+ const starCount = useGitHubStarCount();
return (
<a
diff --git a/docs/lib/github-stars.test.ts b/docs/lib/github-stars.test.ts
new file mode 100644
index 000000000..156a9e243
--- /dev/null
+++ b/docs/lib/github-stars.test.ts
@@ -0,0 +1,15 @@
+import assert from "node:assert/strict";
+import { describe, it } from "node:test";
+import { readGitHubStarCount } from "./github-stars";
+
+describe("readGitHubStarCount", () => {
+ it("reads a valid GitHub repository response", () => {
+ assert.equal(readGitHubStarCount({ stargazers_count: 9860 }), 9860);
+ });
+
+ it("rejects missing, negative, and non-numeric counts", () => {
+ assert.equal(readGitHubStarCount({}), null);
+ assert.equal(readGitHubStarCount({ stargazers_count: -1 }), null);
+ assert.equal(readGitHubStarCount({ stargazers_count: "9860" }), null);
+ });
+});
diff --git a/docs/lib/github-stars.ts b/docs/lib/github-stars.ts
new file mode 100644
index 000000000..2a8047df6
--- /dev/null
+++ b/docs/lib/github-stars.ts
@@ -0,0 +1,14 @@
+export const OPENUI_GITHUB_REPOSITORY = "thesysdev/openui";
+export const GITHUB_STAR_FALLBACK = 9860;
+
+export type GitHubStarsResponse = {
+ stars: number;
+ source: "github" | "fallback";
+};
+
+export function readGitHubStarCount(value: unknown): number | null {
+ if (typeof value !== "object" || value === null || !("stargazers_count" in value)) return null;
+
+ const count = value.stargazers_count;
+ return typeof count === "number" && Number.isFinite(count) && count >= 0 ? count : null;
+}