Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
132 changes: 132 additions & 0 deletions app/api/speed-insight/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
/**
* @author ColdByDefault
* @copyright 2026 ColdByDefault. All Rights Reserved.
*/

import { NextResponse } from "next/server";
import { sanitizeErrorMessage } from "@/lib/security";
import type {
RawPageSpeedResponse,
SpeedInsightResult,
SpeedInsightScore,
SpeedInsightApiResponse,
} from "@/types/configs/speed-insight";

const PAGESPEED_API_URL =
"https://www.googleapis.com/pagespeedonline/v5/runPagespeed";
const TARGET_URL =
process.env.PAGESPEED_TARGET_URL || "https://coldbydefault.com";
const API_KEY = process.env.GOOGLE_PAGESPEED_API_KEY;

/** Map a 0–1 score to a Tailwind color class */
function getScoreColor(score: number): string {
if (score >= 90) return "text-green-500";
if (score >= 50) return "text-yellow-500";
return "text-red-500";
}

/** Parse the raw Google API response into our clean type */
function parseResult(
raw: RawPageSpeedResponse,
strategy: "mobile" | "desktop",
): SpeedInsightResult {
const cats = raw.lighthouseResult.categories;

const categories: SpeedInsightScore[] = Object.values(cats).map((cat) => {
const pct = Math.round((cat.score ?? 0) * 100);
return {
label: cat.title,
score: pct,
color: getScoreColor(pct),
};
});

return {
url: raw.id,
strategy,
categories,
fetchedAt: raw.lighthouseResult.fetchTime,
};
}

/** Fetch PageSpeed data for a given strategy */
async function fetchPageSpeed(
strategy: "mobile" | "desktop",
forceRefresh = false,
): Promise<SpeedInsightResult> {
const params = new URLSearchParams({
url: TARGET_URL,
strategy,
category: "performance",
});

// Add all categories
["accessibility", "best-practices", "seo"].forEach((cat) =>
params.append("category", cat),
);

if (API_KEY) {
params.set("key", API_KEY);
}

const response = await fetch(`${PAGESPEED_API_URL}?${params.toString()}`, {
headers: {
Referer: TARGET_URL,
},
...(forceRefresh
? { cache: "no-store" as const }
: { next: { revalidate: 3600 } }), // Cache for 1 hour unless force refresh
});

if (!response.ok) {
const errorText = await response.text();
throw new Error(
`PageSpeed API error (${strategy}): ${response.status} – ${errorText}`,
);
}

const data = (await response.json()) as RawPageSpeedResponse;
return parseResult(data, strategy);
}

export async function GET(request: Request): Promise<NextResponse> {
const { searchParams } = new URL(request.url);
const forceRefresh = searchParams.has("refresh");

try {
const [desktop, mobile] = await Promise.all([
fetchPageSpeed("desktop", forceRefresh),
fetchPageSpeed("mobile", forceRefresh),
]);

const body: SpeedInsightApiResponse = { desktop, mobile };

return NextResponse.json(body, {
headers: {
"Cache-Control": "public, s-maxage=3600, stale-while-revalidate=7200",
"X-Content-Type-Options": "nosniff",
"X-Frame-Options": "DENY",
"X-XSS-Protection": "1; mode=block",
"Referrer-Policy": "strict-origin-when-cross-origin",
},
});
} catch (error) {
console.error("PageSpeed API Error:", error);

return NextResponse.json(
{
error: "Failed to fetch PageSpeed data",
message: sanitizeErrorMessage(error),
desktop: null,
mobile: null,
} satisfies SpeedInsightApiResponse & { message: string },
{
status: 500,
headers: {
"X-Content-Type-Options": "nosniff",
"X-Frame-Options": "DENY",
},
},
);
}
}
Comment on lines +92 to +132
Copy link

Copilot AI Feb 21, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The speed-insight API route lacks rate limiting, which could allow abuse of the Google PageSpeed API. Other API routes in this codebase (e.g., app/api/github/route.ts, app/api/about/route.ts) implement RateLimiter to protect against excessive requests. Consider adding rate limiting to prevent abuse and protect the Google PageSpeed API quota, especially since API calls are expensive and the endpoint is publicly accessible.

Copilot uses AI. Check for mistakes.
4 changes: 2 additions & 2 deletions app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import { ThemeProvider } from "@/components/theme/theme-provider";
import { Navbar } from "@/components/nav";
import { Footer } from "@/components/footer";
import { CookiesBanner } from "@/components/cookies";
import { BrowserTranslationNotice } from "@/components/languages";
import { LocaleAutoDetect } from "@/components/languages";
import { ChatBot } from "@/components/chatbot";
import { NoSSR } from "@/components/NoSSR";
import { seoConfigEN, generateStructuredData } from "@/lib/configs/seo";
Expand Down Expand Up @@ -215,7 +215,7 @@ export default async function RootLayout({
</main>
<Footer />
<CookiesBanner />
<BrowserTranslationNotice />
<LocaleAutoDetect />
<NoSSR>
<ChatBot position="bottom-left" />
</NoSSR>
Expand Down
22 changes: 22 additions & 0 deletions app/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,17 @@ const ClientBackground = dynamic(
},
);

const SpeedInsight = dynamic(
() =>
import("@/components/speed-insight").then((mod) => ({
default: mod.SpeedInsight,
})),
{
loading: () => <LoadingSkeleton />,
ssr: false,
},
);

export default function Home() {
const t = useTranslations("Home");
const tt = useTranslations("Services");
Expand Down Expand Up @@ -75,6 +86,17 @@ export default function Home() {
<div className="relative" id="main-content">
{/* Content Container */}
<div className="relative z-10">
{/* PageSpeed Insights Section */}
<Suspense
fallback={
<div className="min-h-80">
<LoadingSkeleton />
</div>
}
>
<SpeedInsight className="py-12 px-4 sm:px-6 lg:px-8" />
</Suspense>

<Suspense
fallback={
<div className="min-h-100">
Expand Down
27 changes: 13 additions & 14 deletions components/cookies/cookies-banner.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/**
* @author ColdByDefault
* @copyright 2026 ColdByDefault. All Rights Reserved.
*/
*/

"use client";

Expand All @@ -15,15 +15,17 @@ import {
import { Button } from "@/components/ui/button";
import { X, Cookie } from "lucide-react";
import { cn } from "@/lib/utils";
import { useTranslations } from "next-intl";

const emptySubscribe = () => () => {};

export function CookiesBanner() {
const [isVisible, setIsVisible] = useState(false);
const t = useTranslations("CookieBanner");
const mounted = useSyncExternalStore(
emptySubscribe,
() => true,
() => false
() => false,
);

useEffect(() => {
Expand Down Expand Up @@ -69,7 +71,7 @@ export function CookiesBanner() {
className={cn(
"fixed bottom-4 left-4 right-4 md:left-6 md:right-6 z-10",
"animate-in slide-in-from-bottom-5 duration-500",
"max-w-md md:max-w-lg lg:max-w-xl ml-auto"
"max-w-md md:max-w-lg lg:max-w-xl ml-auto",
)}
>
<Card className="border-2 shadow-lg">
Expand All @@ -80,7 +82,7 @@ export function CookiesBanner() {
onClick={handleClose}
>
<X className="h-4 w-4" />
<span className="sr-only">close</span>
<span className="sr-only">{t("close")}</span>
</Button>

<CardContent className="p-6">
Expand All @@ -91,20 +93,17 @@ export function CookiesBanner() {
<div className="flex-1 space-y-3">
<div>
<CardTitle className="text-sm font-semibold text-gray-900 dark:text-white">
We value your privacy
{t("title")}
</CardTitle>
<CardDescription className="text-xs text-gray-600 dark:text-gray-300 mt-1">
I bake my own cookies! Theme preferences are stored locally in
your browser. I use Vercel Analytics and Speed Insights to
monitor performance, which are privacy-friendly and do not
track personal data.{" "}
{t("description")}{" "}
<a
href="/privacy"
className="text-primary hover:underline"
onClick={handleClose}
aria-label="Learn more about privacy policy and cookie usage"
aria-label={t("learnMoreAriaLabel")}
>
Learn more about privacy policy
{t("learnMore")}
</a>
</CardDescription>
</div>
Expand All @@ -116,15 +115,15 @@ export function CookiesBanner() {
size="sm"
className="flex-1 text-xs"
>
Accept All Cookies
{t("acceptAll")}
</Button>
<Button
onClick={handleDecline}
variant="outline"
size="sm"
className="flex-1 text-xs"
>
Essential Only
{t("essentialOnly")}
</Button>
</div>
<Button
Expand All @@ -133,7 +132,7 @@ export function CookiesBanner() {
size="sm"
className="text-xs text-muted-foreground hover:text-foreground"
>
Decline Analytics
{t("declineAnalytics")}
</Button>
</div>
</div>
Expand Down
Loading
Loading